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
|
bsd-3-clause
|
36242e1634effb5c331279b0ff68f75da5d56ca6
| 0
|
codehaus/jbehave-git,codehaus/jbehave-git,codehaus/jbehave-git
|
package org.jbehave.core.story.codegen.velocity;
import java.io.File;
import org.jbehave.core.mock.UsingMatchers;
import org.jbehave.core.story.codegen.domain.ScenarioDetails;
import org.jbehave.core.story.codegen.domain.StoryDetails;
/**
*
* @author Mauro Talevi
*/
public class VelocityCodeGeneratorBehaviour extends UsingMatchers {
public void shouldGenerateCodeForStoryWithFullScenario() throws Exception {
// given
StoryDetails story = new StoryDetails("Joe drinks vodka", "", "", "");
ScenarioDetails scenario1 = new ScenarioDetails();
scenario1.name = "Happy path";
scenario1.context.givens.add("a bar downtown");
scenario1.context.givens.add("a thirsty Joe");
scenario1.event.name = "Joe asks for a Smirnov";
scenario1.outcome.outcomes.add("bartender serves Joe");
scenario1.outcome.outcomes.add("Joe is happy");
story.addScenario(scenario1);
ScenarioDetails scenario2 = new ScenarioDetails();
scenario2.name = "Unhappy path";
scenario2.context.givens.add("a pub uptown");
scenario2.context.givens.add("an equally thirsty Joe");
scenario2.event.name = "Joe asks for an Absolut";
scenario2.outcome.outcomes.add("bartender tells Joe it is sold out");
scenario2.outcome.outcomes.add("Joe is unhappy");
story.addScenario(scenario2);
// when
String rootSourceDirectory = "delete_me/generated-src";
String rootPackageName = "generated.code";
VelocityCodeGenerator generator = new VelocityCodeGenerator(rootSourceDirectory, rootPackageName);
generator.generateStory(story);
// then
String[] generatedPaths = new String[]{
"stories/JoeDrinksVodka.java",
"scenarios/HappyPath.java",
"scenarios/UnhappyPath.java",
"events/JoeAsksForASmirnov.java",
"events/JoeAsksForAnAbsolut.java",
"givens/ABarDowntown.java",
"givens/APubUptown.java",
"givens/AThirstyJoe.java",
"givens/AnEquallyThirstyJoe.java",
"outcomes/BartenderServesJoe.java",
"outcomes/BartenderTellsJoeItIsSoldOut.java",
"outcomes/JoeIsHappy.java",
"outcomes/JoeIsUnhappy.java"
};
for ( int i = 0; i < generatedPaths.length; i++ ){
ensureThat(new File(rootSourceDirectory+File.separator+generatedPaths[i]).exists() );
}
}
}
|
trunk/core/src/behaviour/org/jbehave/core/story/codegen/velocity/VelocityCodeGeneratorBehaviour.java
|
package org.jbehave.core.story.codegen.velocity;
import java.io.File;
import org.jbehave.core.mock.UsingMatchers;
import org.jbehave.core.story.codegen.domain.ScenarioDetails;
import org.jbehave.core.story.codegen.domain.StoryDetails;
/**
*
* @author Mauro Talevi
*/
public class VelocityCodeGeneratorBehaviour extends UsingMatchers {
public void shouldGenerateCodeForStoryWithFullScenario() throws Exception {
// given
StoryDetails storyDetails = new StoryDetails("Joe drinks vodka", "", "", "");
ScenarioDetails scenario1 = new ScenarioDetails();
scenario1.name = "Happy path";
scenario1.context.givens.add("a bar downtown");
scenario1.context.givens.add("a thirsty Joe");
scenario1.event.name = "Joe asks for a Smirnov";
scenario1.outcome.outcomes.add("bartender serves Joe");
scenario1.outcome.outcomes.add("Joe is happy");
storyDetails.addScenario(scenario1);
ScenarioDetails scenario2 = new ScenarioDetails();
scenario2.name = "Unhappy path";
scenario2.context.givens.add("a pub uptown");
scenario2.context.givens.add("an equally thirsty Joe");
scenario2.event.name = "Joe asks for an Absolut";
scenario2.outcome.outcomes.add("bartender tells Joe it is sold out");
scenario2.outcome.outcomes.add("Joe is unhappy");
storyDetails.addScenario(scenario2);
// when
String generatedSourceDir = "delete_me/generated-src";
VelocityCodeGenerator generator = new VelocityCodeGenerator(generatedSourceDir,
"generated.stories");
generator.generateStory(storyDetails);
// then
String[] generatedPaths = new String[]{
"events/JoeAsksForASmirnov.java",
"events/JoeAsksForAnAbsolut.java",
"givens/ABarDowntown.java",
"givens/APubUptown.java",
"givens/AThirstyJoe.java",
"givens/AnEquallyThirstyJoe.java",
"outcomes/BartenderServesJoe.java",
"outcomes/BartenderTellsJoeItIsSoldOut.java",
"outcomes/JoeIsHappy.java",
"outcomes/JoeIsUnhappy.java"
};
for ( int i = 0; i < generatedPaths.length; i++ ){
ensureThat(new File(generatedSourceDir+File.separator+generatedPaths[i]).exists() );
}
}
}
|
Added checks on generated code for story and scenarios.
git-svn-id: 1c3b30599278237804f5418c838e2a3e6391d478@765 df8dfae0-ecdd-0310-b8d8-a050f7ac8317
|
trunk/core/src/behaviour/org/jbehave/core/story/codegen/velocity/VelocityCodeGeneratorBehaviour.java
|
Added checks on generated code for story and scenarios.
|
|
Java
|
bsd-3-clause
|
35b54364b9af136171c20a9bc92f7fb253e4c9e1
| 0
|
eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j
|
/*******************************************************************************
* Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*******************************************************************************/
package org.eclipse.rdf4j.sail.nativerdf.datastore;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.eclipse.rdf4j.common.io.NioFile;
/**
* Class supplying access to a hash file.
*
* @author Arjohn Kampman
*/
public class HashFile implements Closeable {
/*-----------*
* Constants *
*-----------*/
// The size of an item (32-bit hash + 32-bit ID), in bytes
private static final int ITEM_SIZE = 8;
/**
* Magic number "Native Hash File" to detect whether the file is actually a hash file. The first three bytes of the
* file should be equal to this magic number.
*/
private static final byte[] MAGIC_NUMBER = new byte[] { 'n', 'h', 'f' };
/**
* File format version, stored as the fourth byte in hash files.
*/
private static final byte FILE_FORMAT_VERSION = 1;
/**
* The size of the file header in bytes. The file header contains the following data: magic number (3 bytes) file
* format version (1 byte), number of buckets (4 bytes), bucket size (4 bytes) and number of stored items (4 bytes).
*/
private static final long HEADER_LENGTH = 16;
private static final int INIT_BUCKET_COUNT = 64;
private static final int INIT_BUCKET_SIZE = 8;
/*-----------*
* Variables *
*-----------*/
private final NioFile nioFile;
private final boolean forceSync;
// The number of (non-overflow) buckets in the hash file
private volatile int bucketCount;
// The number of items that can be stored in a bucket
private final int bucketSize;
// The number of items in the hash file
private volatile int itemCount;
// Load factor (fixed, for now)
private final float loadFactor = 0.75f;
// recordSize = ITEM_SIZE * bucketSize + 4
private final int recordSize;
/**
* A read/write lock that is used to prevent structural changes to the hash file while readers are active in order
* to prevent concurrency issues.
*/
private final ReentrantReadWriteLock structureLock = new ReentrantReadWriteLock();
/*--------------*
* Constructors *
*--------------*/
public HashFile(File file) throws IOException {
this(file, false);
}
public HashFile(File file, boolean forceSync) throws IOException {
this.nioFile = new NioFile(file);
this.forceSync = forceSync;
try {
if (nioFile.size() == 0L) {
// Empty file, insert bucket count, bucket size
// and item count at the start of the file
bucketCount = INIT_BUCKET_COUNT;
bucketSize = INIT_BUCKET_SIZE;
itemCount = 0;
recordSize = ITEM_SIZE * bucketSize + 4;
// Initialize the file by writing <_bucketCount> empty buckets
writeEmptyBuckets(HEADER_LENGTH, bucketCount);
sync();
} else {
// Read bucket count, bucket size and item count from the file
ByteBuffer buf = ByteBuffer.allocate((int) HEADER_LENGTH);
nioFile.read(buf, 0L);
buf.rewind();
if (buf.remaining() < HEADER_LENGTH) {
throw new IOException("File too short to be a compatible hash file");
}
byte[] magicNumber = new byte[MAGIC_NUMBER.length];
buf.get(magicNumber);
byte version = buf.get();
bucketCount = buf.getInt();
bucketSize = buf.getInt();
itemCount = buf.getInt();
if (!Arrays.equals(MAGIC_NUMBER, magicNumber)) {
throw new IOException("File doesn't contain compatible hash file data");
}
if (version > FILE_FORMAT_VERSION) {
throw new IOException("Unable to read hash file; it uses a newer file format");
} else if (version != FILE_FORMAT_VERSION) {
throw new IOException("Unable to read hash file; invalid file format version: " + version);
}
recordSize = ITEM_SIZE * bucketSize + 4;
}
} catch (IOException e) {
this.nioFile.close();
throw e;
}
}
/*---------*
* Methods *
*---------*/
public File getFile() {
return nioFile.getFile();
}
public int getItemCount() {
return itemCount;
}
/**
* Gets an iterator that iterates over the IDs with hash codes that match the specified hash code.
*/
public IDIterator getIDIterator(int hash) throws IOException {
return new IDIterator(hash);
}
/**
* Stores ID under the specified hash code in this hash file.
*/
public void storeID(int hash, int id) throws IOException {
structureLock.readLock().lock();
try {
// Calculate bucket offset for initial bucket
long bucketOffset = getBucketOffset(hash);
storeID(bucketOffset, hash, id);
} finally {
structureLock.readLock().unlock();
}
if (++itemCount >= loadFactor * bucketCount * bucketSize) {
structureLock.writeLock().lock();
try {
increaseHashTable();
} finally {
structureLock.writeLock().unlock();
}
}
}
private void storeID(long bucketOffset, int hash, int id) throws IOException {
boolean idStored = false;
ByteBuffer bucket = ByteBuffer.allocate(recordSize);
while (!idStored) {
nioFile.read(bucket, bucketOffset);
// Find first empty slot in bucket
int slotID = findEmptySlotInBucket(bucket);
if (slotID >= 0) {
// Empty slot found, store dataOffset in it
bucket.putInt(ITEM_SIZE * slotID, hash);
bucket.putInt(ITEM_SIZE * slotID + 4, id);
bucket.rewind();
nioFile.write(bucket, bucketOffset);
idStored = true;
} else {
// No empty slot found, check if bucket has an overflow bucket
int overflowID = bucket.getInt(ITEM_SIZE * bucketSize);
if (overflowID == 0) {
// No overflow bucket yet, create one
overflowID = createOverflowBucket();
// Link overflow bucket to current bucket
bucket.putInt(ITEM_SIZE * bucketSize, overflowID);
bucket.rewind();
nioFile.write(bucket, bucketOffset);
}
// Continue searching for an empty slot in the overflow bucket
bucketOffset = getOverflowBucketOffset(overflowID);
bucket.clear();
}
}
}
public void clear() throws IOException {
structureLock.writeLock().lock();
try {
// Truncate the file to remove any overflow buffers
nioFile.truncate(HEADER_LENGTH + (long) bucketCount * recordSize);
// Overwrite normal buckets with empty ones
writeEmptyBuckets(HEADER_LENGTH, bucketCount);
itemCount = 0;
} finally {
structureLock.writeLock().unlock();
}
}
/**
* Syncs any unstored data to the hash file.
*/
public void sync() throws IOException {
structureLock.readLock().lock();
try {
// Update the file header
writeFileHeader();
} finally {
structureLock.readLock().unlock();
}
if (forceSync) {
nioFile.force(false);
}
}
@Override
public void close() throws IOException {
nioFile.close();
}
/*-----------------*
* Utility methods *
*-----------------*/
private RandomAccessFile createEmptyFile(File file) throws IOException {
// Make sure the file exists
if (!file.exists()) {
boolean created = file.createNewFile();
if (!created) {
throw new IOException("Failed to create file " + file);
}
}
// Open the file in read-write mode and make sure the file is empty
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.setLength(0L);
return raf;
}
/**
* Writes the bucket count, bucket size and item count to the file header.
*/
private void writeFileHeader() throws IOException {
ByteBuffer buf = ByteBuffer.allocate((int) HEADER_LENGTH);
buf.put(MAGIC_NUMBER);
buf.put(FILE_FORMAT_VERSION);
buf.putInt(bucketCount);
buf.putInt(bucketSize);
buf.putInt(itemCount);
buf.rewind();
nioFile.write(buf, 0L);
}
/**
* Returns the offset of the bucket for the specified hash code.
*/
private long getBucketOffset(int hash) {
int bucketNo = hash % bucketCount;
if (bucketNo < 0) {
bucketNo += bucketCount;
}
return HEADER_LENGTH + (long) bucketNo * recordSize;
}
/**
* Returns the offset of the overflow bucket with the specified ID.
*/
private long getOverflowBucketOffset(int bucketID) {
return HEADER_LENGTH + ((long) bucketCount + (long) bucketID - 1L) * recordSize;
}
/**
* Creates a new overflow bucket and returns its ID.
*/
private int createOverflowBucket() throws IOException {
long offset = nioFile.size();
writeEmptyBuckets(offset, 1);
return (int) ((offset - HEADER_LENGTH) / recordSize) - bucketCount + 1;
}
private void writeEmptyBuckets(long fileOffset, int bucketCount) throws IOException {
ByteBuffer emptyBucket = ByteBuffer.allocate(recordSize);
for (int i = 0; i < bucketCount; i++) {
nioFile.write(emptyBucket, fileOffset + i * (long) recordSize);
emptyBucket.rewind();
}
}
private int findEmptySlotInBucket(ByteBuffer bucket) {
for (int slotNo = 0; slotNo < bucketSize; slotNo++) {
// Check for offsets that are equal to 0
if (bucket.getInt(ITEM_SIZE * slotNo + 4) == 0) {
return slotNo;
}
}
return -1;
}
/**
* Double the number of buckets in the hash file and rehashes the stored items.
*/
private void increaseHashTable() throws IOException {
long oldTableSize = HEADER_LENGTH + (long) bucketCount * recordSize;
long newTableSize = HEADER_LENGTH + (long) bucketCount * recordSize * 2;
long oldFileSize = nioFile.size(); // includes overflow buckets
// Move any overflow buckets out of the way to a temporary file
File tmpFile = new File(getFile().getParentFile(), "rehash_" + getFile().getName());
try (RandomAccessFile tmpRaf = createEmptyFile(tmpFile)) {
FileChannel tmpChannel = tmpRaf.getChannel();
// Transfer the overflow buckets to the temp file
// FIXME: work around java bug 6431344:
// "FileChannel.transferTo() doesn't work if address space runs out"
nioFile.transferTo(oldTableSize, oldFileSize - oldTableSize, tmpChannel);
// Increase hash table by factor 2
writeEmptyBuckets(oldTableSize, bucketCount);
bucketCount *= 2;
// Discard any remaining overflow buffers
nioFile.truncate(newTableSize);
ByteBuffer bucket = ByteBuffer.allocate(recordSize);
ByteBuffer newBucket = ByteBuffer.allocate(recordSize);
// Rehash items in non-overflow buckets, half of these will move to a
// new location, but none of them will trigger the creation of new overflow
// buckets. Any (now deprecated) references to overflow buckets are
// removed too.
// All items that are moved to a new location end up in one and the same
// new and empty bucket. All items are divided between the old and the
// new bucket and the changes to the buckets are written to disk only once.
for (long bucketOffset = HEADER_LENGTH; bucketOffset < oldTableSize; bucketOffset += recordSize) {
nioFile.read(bucket, bucketOffset);
boolean bucketChanged = false;
long newBucketOffset = 0L;
for (int slotNo = 0; slotNo < bucketSize; slotNo++) {
int id = bucket.getInt(ITEM_SIZE * slotNo + 4);
if (id != 0) {
// Slot is not empty
int hash = bucket.getInt(ITEM_SIZE * slotNo);
long newOffset = getBucketOffset(hash);
if (newOffset != bucketOffset) {
// Move this item to new bucket...
newBucket.putInt(hash);
newBucket.putInt(id);
// ...and remove it from the current bucket
bucket.putInt(ITEM_SIZE * slotNo, 0);
bucket.putInt(ITEM_SIZE * slotNo + 4, 0);
bucketChanged = true;
newBucketOffset = newOffset;
}
}
}
if (bucketChanged) {
// Some of the items were moved to the new bucket, write it to
// the file
newBucket.flip();
nioFile.write(newBucket, newBucketOffset);
newBucket.clear();
}
// Reset overflow ID in the old bucket to 0 if necessary
if (bucket.getInt(ITEM_SIZE * bucketSize) != 0) {
bucket.putInt(ITEM_SIZE * bucketSize, 0);
bucketChanged = true;
}
if (bucketChanged) {
// Some of the items were moved to the new bucket or the
// overflow ID has been reset; write the bucket back to the file
bucket.rewind();
nioFile.write(bucket, bucketOffset);
}
bucket.clear();
} // Rehash items in overflow buckets. This might trigger the creation of
// new overflow buckets so we can't optimize this in the same way as we
// rehash the normal buckets.
long tmpFileSize = tmpChannel.size();
for (long bucketOffset = 0L; bucketOffset < tmpFileSize; bucketOffset += recordSize) {
tmpChannel.read(bucket, bucketOffset);
for (int slotNo = 0; slotNo < bucketSize; slotNo++) {
int id = bucket.getInt(ITEM_SIZE * slotNo + 4);
if (id != 0) {
// Slot is not empty
int hash = bucket.getInt(ITEM_SIZE * slotNo);
long newBucketOffset = getBucketOffset(hash);
// Copy this item to its new location
storeID(newBucketOffset, hash, id);
}
}
bucket.clear();
}
// Discard the temp file
}
tmpFile.delete();
}
/*------------------------*
* Inner class IDIterator *
*------------------------*/
public class IDIterator {
private final int queryHash;
private ByteBuffer bucketBuffer;
private int slotNo;
private IDIterator(int hash) throws IOException {
queryHash = hash;
bucketBuffer = ByteBuffer.allocate(recordSize);
structureLock.readLock().lock();
try {
// Read initial bucket
long bucketOffset = getBucketOffset(hash);
nioFile.read(bucketBuffer, bucketOffset);
slotNo = -1;
} catch (IOException e) {
structureLock.readLock().unlock();
throw e;
} catch (RuntimeException e) {
structureLock.readLock().unlock();
throw e;
}
}
public void close() {
bucketBuffer = null;
structureLock.readLock().unlock();
}
/**
* Returns the next ID that has been mapped to the specified hash code, or <tt>-1</tt> if no more IDs were
* found.
*/
public int next() throws IOException {
while (bucketBuffer != null) {
// Search in current bucket
while (++slotNo < bucketSize) {
if (bucketBuffer.getInt(ITEM_SIZE * slotNo) == queryHash) {
return bucketBuffer.getInt(ITEM_SIZE * slotNo + 4);
}
}
// No matching hash code in current bucket, check overflow
// bucket
int overflowID = bucketBuffer.getInt(ITEM_SIZE * bucketSize);
if (overflowID == 0) {
// No overflow bucket, end the search
bucketBuffer = null;
break;
} else {
// Continue with overflow bucket
bucketBuffer.clear();
long bucketOffset = getOverflowBucketOffset(overflowID);
nioFile.read(bucketBuffer, bucketOffset);
slotNo = -1;
}
}
return -1;
}
} // End inner class IDIterator
} // End class HashFile
|
nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/HashFile.java
|
/*******************************************************************************
* Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*******************************************************************************/
package org.eclipse.rdf4j.sail.nativerdf.datastore;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.eclipse.rdf4j.common.io.NioFile;
/**
* Class supplying access to a hash file.
*
* @author Arjohn Kampman
*/
public class HashFile implements Closeable {
/*-----------*
* Constants *
*-----------*/
// The size of an item (32-bit hash + 32-bit ID), in bytes
private static final int ITEM_SIZE = 8;
/**
* Magic number "Native Hash File" to detect whether the file is actually a hash file. The first three bytes of the
* file should be equal to this magic number.
*/
private static final byte[] MAGIC_NUMBER = new byte[] { 'n', 'h', 'f' };
/**
* File format version, stored as the fourth byte in hash files.
*/
private static final byte FILE_FORMAT_VERSION = 1;
/**
* The size of the file header in bytes. The file header contains the following data: magic number (3 bytes) file
* format version (1 byte), number of buckets (4 bytes), bucket size (4 bytes) and number of stored items (4 bytes).
*/
private static final long HEADER_LENGTH = 16;
private static final int INIT_BUCKET_COUNT = 64;
private static final int INIT_BUCKET_SIZE = 8;
/*-----------*
* Variables *
*-----------*/
private final NioFile nioFile;
private final boolean forceSync;
// The number of (non-overflow) buckets in the hash file
private volatile int bucketCount;
// The number of items that can be stored in a bucket
private final int bucketSize;
// The number of items in the hash file
private volatile int itemCount;
// Load factor (fixed, for now)
private final float loadFactor = 0.75f;
// recordSize = ITEM_SIZE * bucketSize + 4
private final int recordSize;
/**
* A read/write lock that is used to prevent structural changes to the hash file while readers are active in order
* to prevent concurrency issues.
*/
private final ReentrantReadWriteLock structureLock = new ReentrantReadWriteLock();
/*--------------*
* Constructors *
*--------------*/
public HashFile(File file) throws IOException {
this(file, false);
}
public HashFile(File file, boolean forceSync) throws IOException {
this.nioFile = new NioFile(file);
this.forceSync = forceSync;
try {
if (nioFile.size() == 0L) {
// Empty file, insert bucket count, bucket size
// and item count at the start of the file
bucketCount = INIT_BUCKET_COUNT;
bucketSize = INIT_BUCKET_SIZE;
itemCount = 0;
recordSize = ITEM_SIZE * bucketSize + 4;
// Initialize the file by writing <_bucketCount> empty buckets
writeEmptyBuckets(HEADER_LENGTH, bucketCount);
sync();
} else {
// Read bucket count, bucket size and item count from the file
ByteBuffer buf = ByteBuffer.allocate((int) HEADER_LENGTH);
nioFile.read(buf, 0L);
buf.rewind();
if (buf.remaining() < HEADER_LENGTH) {
throw new IOException("File too short to be a compatible hash file");
}
byte[] magicNumber = new byte[MAGIC_NUMBER.length];
buf.get(magicNumber);
byte version = buf.get();
bucketCount = buf.getInt();
bucketSize = buf.getInt();
itemCount = buf.getInt();
if (!Arrays.equals(MAGIC_NUMBER, magicNumber)) {
throw new IOException("File doesn't contain compatible hash file data");
}
if (version > FILE_FORMAT_VERSION) {
throw new IOException("Unable to read hash file; it uses a newer file format");
} else if (version != FILE_FORMAT_VERSION) {
throw new IOException("Unable to read hash file; invalid file format version: " + version);
}
recordSize = ITEM_SIZE * bucketSize + 4;
}
} catch (IOException e) {
this.nioFile.close();
throw e;
}
}
/*---------*
* Methods *
*---------*/
public File getFile() {
return nioFile.getFile();
}
public int getItemCount() {
return itemCount;
}
/**
* Gets an iterator that iterates over the IDs with hash codes that match the specified hash code.
*/
public IDIterator getIDIterator(int hash) throws IOException {
return new IDIterator(hash);
}
/**
* Stores ID under the specified hash code in this hash file.
*/
public void storeID(int hash, int id) throws IOException {
structureLock.readLock().lock();
try {
// Calculate bucket offset for initial bucket
long bucketOffset = getBucketOffset(hash);
storeID(bucketOffset, hash, id);
} finally {
structureLock.readLock().unlock();
}
if (++itemCount >= loadFactor * bucketCount * bucketSize) {
structureLock.writeLock().lock();
try {
increaseHashTable();
} finally {
structureLock.writeLock().unlock();
}
}
}
private void storeID(long bucketOffset, int hash, int id) throws IOException {
boolean idStored = false;
ByteBuffer bucket = ByteBuffer.allocate(recordSize);
while (!idStored) {
nioFile.read(bucket, bucketOffset);
// Find first empty slot in bucket
int slotID = findEmptySlotInBucket(bucket);
if (slotID >= 0) {
// Empty slot found, store dataOffset in it
bucket.putInt(ITEM_SIZE * slotID, hash);
bucket.putInt(ITEM_SIZE * slotID + 4, id);
bucket.rewind();
nioFile.write(bucket, bucketOffset);
idStored = true;
} else {
// No empty slot found, check if bucket has an overflow bucket
int overflowID = bucket.getInt(ITEM_SIZE * bucketSize);
if (overflowID == 0) {
// No overflow bucket yet, create one
overflowID = createOverflowBucket();
// Link overflow bucket to current bucket
bucket.putInt(ITEM_SIZE * bucketSize, overflowID);
bucket.rewind();
nioFile.write(bucket, bucketOffset);
}
// Continue searching for an empty slot in the overflow bucket
bucketOffset = getOverflowBucketOffset(overflowID);
bucket.clear();
}
}
}
public void clear() throws IOException {
structureLock.writeLock().lock();
try {
// Truncate the file to remove any overflow buffers
nioFile.truncate(HEADER_LENGTH + (long) bucketCount * recordSize);
// Overwrite normal buckets with empty ones
writeEmptyBuckets(HEADER_LENGTH, bucketCount);
itemCount = 0;
} finally {
structureLock.writeLock().unlock();
}
}
/**
* Syncs any unstored data to the hash file.
*/
public void sync() throws IOException {
structureLock.readLock().lock();
try {
// Update the file header
writeFileHeader();
} finally {
structureLock.readLock().unlock();
}
if (forceSync) {
nioFile.force(false);
}
}
@Override
public void close() throws IOException {
nioFile.close();
}
/*-----------------*
* Utility methods *
*-----------------*/
private RandomAccessFile createEmptyFile(File file) throws IOException {
// Make sure the file exists
if (!file.exists()) {
boolean created = file.createNewFile();
if (!created) {
throw new IOException("Failed to create file " + file);
}
}
// Open the file in read-write mode and make sure the file is empty
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.setLength(0L);
return raf;
}
/**
* Writes the bucket count, bucket size and item count to the file header.
*/
private void writeFileHeader() throws IOException {
ByteBuffer buf = ByteBuffer.allocate((int) HEADER_LENGTH);
buf.put(MAGIC_NUMBER);
buf.put(FILE_FORMAT_VERSION);
buf.putInt(bucketCount);
buf.putInt(bucketSize);
buf.putInt(itemCount);
buf.rewind();
nioFile.write(buf, 0L);
}
/**
* Returns the offset of the bucket for the specified hash code.
*/
private long getBucketOffset(int hash) {
int bucketNo = hash % bucketCount;
if (bucketNo < 0) {
bucketNo += bucketCount;
}
return HEADER_LENGTH + (long) bucketNo * recordSize;
}
/**
* Returns the offset of the overflow bucket with the specified ID.
*/
private long getOverflowBucketOffset(int bucketID) {
return HEADER_LENGTH + ((long) bucketCount + (long) bucketID - 1L) * recordSize;
}
/**
* Creates a new overflow bucket and returns its ID.
*/
private int createOverflowBucket() throws IOException {
long offset = nioFile.size();
writeEmptyBuckets(offset, 1);
return (int) ((offset - HEADER_LENGTH) / recordSize) - bucketCount + 1;
}
private void writeEmptyBuckets(long fileOffset, int bucketCount) throws IOException {
ByteBuffer emptyBucket = ByteBuffer.allocate(recordSize);
for (int i = 0; i < bucketCount; i++) {
nioFile.write(emptyBucket, fileOffset + i * (long) recordSize);
emptyBucket.rewind();
}
}
private int findEmptySlotInBucket(ByteBuffer bucket) {
for (int slotNo = 0; slotNo < bucketSize; slotNo++) {
// Check for offsets that are equal to 0
if (bucket.getInt(ITEM_SIZE * slotNo + 4) == 0) {
return slotNo;
}
}
return -1;
}
/**
* Double the number of buckets in the hash file and rehashes the stored items.
*/
private void increaseHashTable() throws IOException {
long oldTableSize = HEADER_LENGTH + (long) bucketCount * recordSize;
long newTableSize = HEADER_LENGTH + (long) bucketCount * recordSize * 2;
long oldFileSize = nioFile.size(); // includes overflow buckets
// Move any overflow buckets out of the way to a temporary file
File tmpFile = new File(getFile().getParentFile(), "rehash_" + getFile().getName());
try (RandomAccessFile tmpRaf = createEmptyFile(tmpFile)) {
FileChannel tmpChannel = tmpRaf.getChannel();
// Transfer the overflow buckets to the temp file
// FIXME: work around java bug 6431344:
// "FileChannel.transferTo() doesn't work if address space runs out"
nioFile.transferTo(oldTableSize, oldFileSize - oldTableSize, tmpChannel);
// Increase hash table by factor 2
writeEmptyBuckets(oldTableSize, bucketCount);
bucketCount *= 2;
// Discard any remaining overflow buffers
nioFile.truncate(newTableSize);
ByteBuffer bucket = ByteBuffer.allocate(recordSize);
ByteBuffer newBucket = ByteBuffer.allocate(recordSize);
// Rehash items in non-overflow buckets, half of these will move to a
// new location, but none of them will trigger the creation of new overflow
// buckets. Any (now deprecated) references to overflow buckets are
// removed too.
// All items that are moved to a new location end up in one and the same
// new and empty bucket. All items are divided between the old and the
// new bucket and the changes to the buckets are written to disk only once.
for (long bucketOffset = HEADER_LENGTH; bucketOffset < oldTableSize; bucketOffset += recordSize) {
nioFile.read(bucket, bucketOffset);
boolean bucketChanged = false;
long newBucketOffset = 0L;
for (int slotNo = 0; slotNo < bucketSize; slotNo++) {
int id = bucket.getInt(ITEM_SIZE * slotNo + 4);
if (id != 0) {
// Slot is not empty
int hash = bucket.getInt(ITEM_SIZE * slotNo);
long newOffset = getBucketOffset(hash);
if (newOffset != bucketOffset) {
// Move this item to new bucket...
newBucket.putInt(hash);
newBucket.putInt(id);
// ...and remove it from the current bucket
bucket.putInt(ITEM_SIZE * slotNo, 0);
bucket.putInt(ITEM_SIZE * slotNo + 4, 0);
bucketChanged = true;
newBucketOffset = newOffset;
}
}
}
if (bucketChanged) {
// Some of the items were moved to the new bucket, write it to
// the file
newBucket.flip();
nioFile.write(newBucket, newBucketOffset);
newBucket.clear();
}
// Reset overflow ID in the old bucket to 0 if necessary
if (bucket.getInt(ITEM_SIZE * bucketSize) != 0) {
bucket.putInt(ITEM_SIZE * bucketSize, 0);
bucketChanged = true;
}
if (bucketChanged) {
// Some of the items were moved to the new bucket or the
// overflow ID has been reset; write the bucket back to the file
bucket.rewind();
nioFile.write(bucket, bucketOffset);
}
bucket.clear();
} // Rehash items in overflow buckets. This might trigger the creation of
// new overflow buckets so we can't optimize this in the same way as we
// rehash the normal buckets.
long tmpFileSize = tmpChannel.size();
for (long bucketOffset = 0L; bucketOffset < tmpFileSize; bucketOffset += recordSize) {
tmpChannel.read(bucket, bucketOffset);
for (int slotNo = 0; slotNo < bucketSize; slotNo++) {
int id = bucket.getInt(ITEM_SIZE * slotNo + 4);
if (id != 0) {
// Slot is not empty
int hash = bucket.getInt(ITEM_SIZE * slotNo);
long newBucketOffset = getBucketOffset(hash);
// Copy this item to its new location
storeID(newBucketOffset, hash, id);
}
}
bucket.clear();
}
// Discard the temp file
}
tmpFile.delete();
}
/*------------------------*
* Inner class IDIterator *
*------------------------*/
public class IDIterator {
private final int queryHash;
private ByteBuffer bucketBuffer;
private int slotNo;
private IDIterator(int hash) throws IOException {
queryHash = hash;
bucketBuffer = ByteBuffer.allocate(recordSize);
structureLock.readLock().lock();
try {
// Read initial bucket
long bucketOffset = getBucketOffset(hash);
nioFile.read(bucketBuffer, bucketOffset);
slotNo = -1;
} catch (IOException e) {
structureLock.readLock().unlock();
throw e;
} catch (RuntimeException e) {
structureLock.readLock().unlock();
throw e;
}
}
public void close() {
bucketBuffer = null;
structureLock.readLock().unlock();
}
/**
* Returns the next ID that has been mapped to the specified hash code, or <tt>-1</tt> if no more IDs were
* found.
*/
public int next() throws IOException {
while (bucketBuffer != null) {
// Search in current bucket
while (++slotNo < bucketSize) {
if (bucketBuffer.getInt(ITEM_SIZE * slotNo) == queryHash) {
return bucketBuffer.getInt(ITEM_SIZE * slotNo + 4);
}
}
// No matching hash code in current bucket, check overflow
// bucket
int overflowID = bucketBuffer.getInt(ITEM_SIZE * bucketSize);
if (overflowID == 0) {
// No overflow bucket, end the search
bucketBuffer = null;
break;
} else {
// Continue with overflow bucket
bucketBuffer.clear();
long bucketOffset = getOverflowBucketOffset(overflowID);
nioFile.read(bucketBuffer, bucketOffset);
slotNo = -1;
}
}
return -1;
}
} // End inner class IDIterator
} // End class HashFile
|
Revert "fixed overlooked file formatting"
This reverts commit 57c7e098226e41006bdec12dd10d0b38d3884fad.
|
nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/HashFile.java
|
Revert "fixed overlooked file formatting"
|
|
Java
|
bsd-3-clause
|
b009f05ce0b45fbb1d3233735b0a75e3f6ac9884
| 0
|
NCIP/cananolab,NCIP/cananolab,NCIP/cananolab
|
/*
The caNanoLab Software License, Version 1.5.2
Copyright 2006 SAIC. This software was developed in conjunction with the National
Cancer Institute, and so to the extent government employees are co-authors, any
rights in such works shall be subject to Title 17 of the United States Code,
section 105.
*/
package gov.nih.nci.cananolab.ui.curation;
/**
* This class handles batch data availability request in a separate thread
*
* @author lethai, pansu
*/
import gov.nih.nci.cananolab.dto.common.AccessibilityBean;
import gov.nih.nci.cananolab.dto.common.UserBean;
import gov.nih.nci.cananolab.service.common.LongRunningProcess;
import gov.nih.nci.cananolab.service.sample.DataAvailabilityService;
import gov.nih.nci.cananolab.service.sample.SampleService;
import gov.nih.nci.cananolab.service.sample.impl.BatchDataAvailabilityProcess;
import gov.nih.nci.cananolab.service.sample.impl.SampleServiceLocalImpl;
import gov.nih.nci.cananolab.service.security.SecurityService;
import gov.nih.nci.cananolab.ui.core.AbstractDispatchAction;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
public class BatchDataAvailabilityAction extends AbstractDispatchAction {
private DataAvailabilityService dataAvailabilityService;
private static final int CUT_OFF_NUM_SAMPLES = 50;
public DataAvailabilityService getDataAvailabilityService() {
return dataAvailabilityService;
}
public void setDataAvailabilityService(
DataAvailabilityService dataAvailabilityService) {
this.dataAvailabilityService = dataAvailabilityService;
}
public ActionForward setupNew(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaActionForm theForm = (DynaActionForm) form;
theForm.set("option", BatchDataAvailabilityProcess.BATCH_OPTION1);
return mapping.findForward("input");
}
// option1 - generate all: update existing one and generate new ones.
// option2 - re-generate for samples with existing data availability
// option3 - delete existing data availability
public ActionForward generate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaActionForm theForm = (DynaActionForm) form;
String option = theForm.getString("option");
HttpSession session = request.getSession();
UserBean user = (UserBean) session.getAttribute("user");
ActionMessages messages = new ActionMessages();
SecurityService securityService = new SecurityService(
AccessibilityBean.CSM_APP_NAME, user);
SampleService sampleService = new SampleServiceLocalImpl(
securityService);
List<String> sampleIdsToRun = new ArrayList<String>();
if (option.equals(BatchDataAvailabilityProcess.BATCH_OPTION1)) {
// find all sampleIds
sampleIdsToRun = sampleService.findSampleIdsBy("", "", null, null,
null, null, null, null, null, null, null);
} else {
// find samplesIds with existing data availability
sampleIdsToRun = dataAvailabilityService
.findSampleIdsWithDataAvailability(securityService);
}
// empty sampleIds
if (sampleIdsToRun.isEmpty()) {
if (option.equals(BatchDataAvailabilityProcess.BATCH_OPTION2)
|| option
.equals(BatchDataAvailabilityProcess.BATCH_OPTION3)) {
ActionMessage msg = new ActionMessage(
"message.batchDataAvailability.empty.metrics");
messages.add(ActionMessages.GLOBAL_MESSAGE, msg);
} else {
ActionMessage msg = new ActionMessage(
"message.batchDataAvailability.nosamples");
messages.add(ActionMessages.GLOBAL_MESSAGE, msg);
}
saveMessages(request, messages);
return mapping.findForward("input");
}
// check how many samples to run, if less than the CUT_OFF_NUM_SAMPLES,
// we don't have to run batch in a separate thread
if (sampleIdsToRun.size() < CUT_OFF_NUM_SAMPLES) {
int i = 0;
if (option.equals(BatchDataAvailabilityProcess.BATCH_OPTION1)
|| option
.equals(BatchDataAvailabilityProcess.BATCH_OPTION2)) {
i = dataAvailabilityService.saveBatchDataAvailability(
sampleIdsToRun, securityService);
ActionMessage msg = new ActionMessage(
"message.batchDataAvailability.generate.success",
sampleIdsToRun.size());
messages.add(ActionMessages.GLOBAL_MESSAGE, msg);
}
if (option.equals(BatchDataAvailabilityProcess.BATCH_OPTION3)) {
i = dataAvailabilityService.deleteBatchDataAvailability(
sampleIdsToRun, securityService);
ActionMessage msg = new ActionMessage(
"message.batchDataAvailability.delete.success",
sampleIdsToRun.size());
messages.add(ActionMessages.GLOBAL_MESSAGE, msg);
}
if (i > 0) {
ActionMessage msg = new ActionMessage(
"message.batchDataAvailability.failed", i);
messages.add(ActionMessages.GLOBAL_MESSAGE, msg);
}
saveMessages(request, messages);
return mapping.findForward("input");
}
// run in a separate thread
//
// We only want one BatchDataAvailabilityProcess per session.
//
BatchDataAvailabilityProcess batchProcess = (BatchDataAvailabilityProcess) session
.getAttribute("batchDataAvailabilityProcess");
if (batchProcess == null || batchProcess.isComplete()) {
this.startThreadForBatchProcess(batchProcess, session,
sampleIdsToRun, dataAvailabilityService, securityService,
option, user);
} else {
if (!batchProcess.isComplete()) {
ActionMessage msg = new ActionMessage(
"message.batchDataAvailability.duplicateRequest");
messages.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveMessages(request, messages);
return mapping.findForward("input");
}
}
String optionMessage = "generate";
if (option.equals(BatchDataAvailabilityProcess.BATCH_OPTION3)) {
optionMessage = "delete";
}
ActionMessage msg = new ActionMessage(
"message.batchDataAvailability.longRunning", sampleIdsToRun
.size(), optionMessage);
messages.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveMessages(request, messages);
return mapping.findForward("input");
}
private void startThreadForBatchProcess(
BatchDataAvailabilityProcess batchProcess, HttpSession session,
List<String> sampleIdsToRun,
DataAvailabilityService dataAvailabilityService,
SecurityService securityService, String option, UserBean user)
throws Exception {
session.setAttribute("hasResultsWaiting", true);
batchProcess = new BatchDataAvailabilityProcess(
dataAvailabilityService, securityService, sampleIdsToRun,
option, user);
batchProcess.process();
session.setAttribute("batchDataAvailabilityProcess", batchProcess);
// obtain the list of long running processes
List<LongRunningProcess> longRunningProcesses = new ArrayList<LongRunningProcess>();
if (session.getAttribute("longRunningProcesses") != null) {
longRunningProcesses = (List<LongRunningProcess>) session
.getAttribute("longRunningProcesses");
}
longRunningProcesses.add(batchProcess);
session.setAttribute("longRunningProcesses", longRunningProcesses);
}
}
|
software/cananolab-webapp/src/gov/nih/nci/cananolab/ui/curation/BatchDataAvailabilityAction.java
|
/*
The caNanoLab Software License, Version 1.5.2
Copyright 2006 SAIC. This software was developed in conjunction with the National
Cancer Institute, and so to the extent government employees are co-authors, any
rights in such works shall be subject to Title 17 of the United States Code,
section 105.
*/
package gov.nih.nci.cananolab.ui.curation;
/**
* This class handles batch data availability request in a separate thread
*
* @author lethai, pansu
*/
import gov.nih.nci.cananolab.dto.common.UserBean;
import gov.nih.nci.cananolab.service.sample.DataAvailabilityService;
import gov.nih.nci.cananolab.service.sample.impl.BatchDataAvailabilityProcess;
import gov.nih.nci.cananolab.ui.core.AbstractDispatchAction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
public class BatchDataAvailabilityAction extends AbstractDispatchAction {
private DataAvailabilityService dataAvailabilityService;
public DataAvailabilityService getDataAvailabilityService() {
return dataAvailabilityService;
}
public void setDataAvailabilityService(
DataAvailabilityService dataAvailabilityService) {
this.dataAvailabilityService = dataAvailabilityService;
}
public ActionForward setupNew(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaActionForm theForm = (DynaActionForm) form;
theForm.set("option", BatchDataAvailabilityProcess.BATCH_OPTION1);
return mapping.findForward("input");
}
// option1 - generate all: update existing one and generate new ones.
// option2 - re-generate for samples with existing data availability
// option3 - delete data availability for all samples
public ActionForward generate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaActionForm theForm = (DynaActionForm) form;
String option = theForm.getString("option");
HttpSession session = request.getSession();
UserBean user = (UserBean) session.getAttribute("user");
ActionMessages messages = new ActionMessages();
//
// We only want one BatchDataAvailabilityProcess per session.
//
BatchDataAvailabilityProcess batchProcess = (BatchDataAvailabilityProcess) session
.getAttribute("batchDataAvailabilityProcess");
if (batchProcess == null) {
session.setAttribute("hasResultsWaiting", true);
batchProcess = new BatchDataAvailabilityProcess(
dataAvailabilityService, option, user);
session.setAttribute("batchDataAvailabilityProcess", batchProcess);
session.setAttribute("processType", "dataAvailability");
batchProcess.process();
} else {
if (!batchProcess.isComplete()) {
ActionMessage msg = new ActionMessage(
"message.batchDataAvailability.duplicateRequest");
messages.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveMessages(request, messages);
return mapping.findForward("input");
}
}
return mapping.findForward("batchDataAvailabilityResults");
}
}
|
updated to run requests that have samples more than the cutoff in a separate thread only.
SVN-Revision: 19394
|
software/cananolab-webapp/src/gov/nih/nci/cananolab/ui/curation/BatchDataAvailabilityAction.java
|
updated to run requests that have samples more than the cutoff in a separate thread only.
|
|
Java
|
mit
|
0554047ca78a7d079b6f2692797faaf56b1774d4
| 0
|
LoicDelorme/Polytech-Slides-Software
|
package com.delormeloic.generator.model.slides;
import org.json.JSONObject;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.text.Font;
/**
* This class represents an header.
*
* @author DELORME Loïc
* @since 1.0.0
*/
public class Header implements ISerializable
{
/**
* The middle text attribute.
*/
public static final String MIDDLE_TEXT_ATTRIBUTE = "middleText";
/**
* The middle text font attribute.
*/
public static final String MIDDLE_TEXT_FONT_ATTRIBUTE = "middleTextFont";
/**
* The middle text.
*/
private final StringProperty middleText;
/**
* The middle text font.
*/
private final ObjectProperty<Font> middleTextFont;
/**
* Create an header.
*
* @param data
* The data.
*/
public Header(JSONObject data)
{
this.middleText = new SimpleStringProperty(data.getString(MIDDLE_TEXT_ATTRIBUTE));
this.middleTextFont = new SimpleObjectProperty<Font>(new Font(data.getString(MIDDLE_TEXT_FONT_ATTRIBUTE), IConstants.DEFAULT_FONT_SIZE));
}
/**
* Create an header.
*/
public Header()
{
this.middleText = new SimpleStringProperty(IConstants.DEFAULT_TEXT);
this.middleTextFont = new SimpleObjectProperty<Font>(IConstants.DEFAULT_FONT);
}
/**
* Get the middle text.
*
* @return The middle text.
*/
public String getMiddleText()
{
return this.middleText.get();
}
/**
* Get the middle text property.
*
* @return The middle text property.
*/
public StringProperty getMiddleTextProperty()
{
return this.middleText;
}
/**
* Get the middle text font.
*
* @return The middle text font.
*/
public Font getMiddleTextFont()
{
return this.middleTextFont.get();
}
/**
* Get the middle text font property.
*
* @return The middle text font property.
*/
public ObjectProperty<Font> getMiddleTextFontProperty()
{
return this.middleTextFont;
}
/**
* @see com.delormeloic.generator.model.slides.ISerializable#toJSON()
*/
@Override
public JSONObject toJSON()
{
final JSONObject data = new JSONObject();
data.put(MIDDLE_TEXT_ATTRIBUTE, getMiddleText());
data.put(MIDDLE_TEXT_FONT_ATTRIBUTE, getMiddleTextFont().getName());
return data;
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
return (getMiddleText().hashCode() + getMiddleTextFont().hashCode());
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object object)
{
if (object == null)
{
return false;
}
if (this == object)
{
return true;
}
if (!(object instanceof Header))
{
return false;
}
final Header header = (Header) object;
if (!getMiddleText().equals(header.getMiddleText()))
{
return false;
}
if (!getMiddleTextFont().equals(header.getMiddleTextFont()))
{
return false;
}
return true;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return toJSON().toString();
}
}
|
src/com/delormeloic/generator/model/slides/Header.java
|
package com.delormeloic.generator.model.slides;
import org.json.JSONObject;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.text.Font;
/**
* This class represents an header.
*
* @author DELORME Loïc
* @since 1.0.0
*/
public class Header implements ISerializable
{
/**
* The middle text attribute.
*/
public static final String MIDDLE_TEXT_ATTRIBUTE = "middleText";
/**
* The middle text font attribute.
*/
public static final String MIDDLE_TEXT_FONT_ATTRIBUTE = "middleTextFont";
/**
* The middle text size attribute.
*/
public static final String MIDDLE_TEXT_SIZE_ATTRIBUTE = "middleTextSize";
/**
* The middle text.
*/
private final StringProperty middleText;
/**
* The middle text font.
*/
private final ObjectProperty<Font> middleTextFont;
/**
* The middle text size.
*/
private final IntegerProperty middleTextSize;
/**
* Create an header.
*
* @param data
* The data.
*/
public Header(JSONObject data)
{
this.middleText = new SimpleStringProperty(data.getString(MIDDLE_TEXT_ATTRIBUTE));
this.middleTextFont = new SimpleObjectProperty<Font>(new Font(data.getString(MIDDLE_TEXT_FONT_ATTRIBUTE), IConstants.DEFAULT_FONT_SIZE));
this.middleTextSize = new SimpleIntegerProperty(data.getInt(MIDDLE_TEXT_SIZE_ATTRIBUTE));
}
/**
* Create an header.
*/
public Header()
{
this.middleText = new SimpleStringProperty(IConstants.DEFAULT_TEXT);
this.middleTextFont = new SimpleObjectProperty<Font>(IConstants.DEFAULT_FONT);
this.middleTextSize = new SimpleIntegerProperty(IConstants.DEFAULT_FONT_SIZE);
}
/**
* Get the middle text.
*
* @return The middle text.
*/
public String getMiddleText()
{
return this.middleText.get();
}
/**
* Get the middle text property.
*
* @return The middle text property.
*/
public StringProperty getMiddleTextProperty()
{
return this.middleText;
}
/**
* Get the middle text font.
*
* @return The middle text font.
*/
public Font getMiddleTextFont()
{
return this.middleTextFont.get();
}
/**
* Get the middle text font property.
*
* @return The middle text font property.
*/
public ObjectProperty<Font> getMiddleTextFontProperty()
{
return this.middleTextFont;
}
/**
* Get the middle text size.
*
* @return The middle text size.
*/
public int getMiddleTextSize()
{
return this.middleTextSize.get();
}
/**
* Get the middle text size property.
*
* @return The middle text size property.
*/
public IntegerProperty getMiddleTextSizeProperty()
{
return this.middleTextSize;
}
/**
* @see com.delormeloic.generator.model.slides.ISerializable#toJSON()
*/
@Override
public JSONObject toJSON()
{
final JSONObject data = new JSONObject();
data.put(MIDDLE_TEXT_ATTRIBUTE, getMiddleText());
data.put(MIDDLE_TEXT_FONT_ATTRIBUTE, getMiddleTextFont().getName());
data.put(MIDDLE_TEXT_SIZE_ATTRIBUTE, getMiddleTextSize());
return data;
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
return (getMiddleText().hashCode() + getMiddleTextFont().hashCode() + getMiddleTextSize());
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object object)
{
if (object == null)
{
return false;
}
if (this == object)
{
return true;
}
if (!(object instanceof Header))
{
return false;
}
final Header header = (Header) object;
if (!getMiddleText().equals(header.getMiddleText()))
{
return false;
}
if (!getMiddleTextFont().equals(header.getMiddleTextFont()))
{
return false;
}
if (getMiddleTextSize() != header.getMiddleTextSize())
{
return false;
}
return true;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return toJSON().toString();
}
}
|
[update] remove size attribute
|
src/com/delormeloic/generator/model/slides/Header.java
|
[update] remove size attribute
|
|
Java
|
mit
|
46fe6e17bd01e83dcbd920d99612e676c17f2a2e
| 0
|
technecloud/cronapi-java
|
package cronapi.pushnotification;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.springframework.http.HttpEntity;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import cronapi.CronapiMetaData;
import cronapi.ParamMetaData;
import cronapi.Var;
import cronapi.CronapiMetaData.CategoryType;
import cronapi.CronapiMetaData.ObjectType;
import org.springframework.web.client.RestTemplate;
/**
* Classe que representa ...
*
* @author Usuário de Teste
* @version 1.0
* @since 2018-01-24
*
*/
@CronapiMetaData(category = CategoryType.UTIL, categoryTags = { "UTIL", "Util" })
public class Operations {
@CronapiMetaData(type = "function", name = "{{firebaseSendNotification}}", nameTags = {
"SendNotification" }, description = "{{firebaseSendNotificationDescription}}" )
public static final void sendNotification(
@ParamMetaData(type = ObjectType.STRING, description = "{{FirebaseServerKey}}") Var serverKey,
@ParamMetaData(type = ObjectType.OBJECT, description = "{{FirebaseTo}}") Var paramTo,
@ParamMetaData(type = ObjectType.STRING, description = "{{FirebaseTitle}}") Var paramTitle,
@ParamMetaData(type = ObjectType.STRING, description = "{{FirebaseBody}}") Var paramBody,
@ParamMetaData(type = ObjectType.JSON, description = "{{FirebaseData}}") Var paramData)
throws Exception {
JsonObject body = new JsonObject();
body.addProperty("to", paramTo.getObjectAsString());
body.addProperty("priority", "high");
JsonObject notification = new JsonObject();
notification.addProperty("title", paramTitle.getObjectAsString());
notification.addProperty("body", paramBody.getObjectAsString());
body.add("notification", notification);
body.add("data", (JsonObject) paramData.getObject());
HttpEntity<String> request = new HttpEntity<>(body.toString());
FirebasePushNotificationService firebaseService = new FirebasePushNotificationService(serverKey.getObjectAsString());
CompletableFuture<String> pushNotification = firebaseService.send(request);
CompletableFuture.allOf(pushNotification).join();
try {
String firebaseResponse = pushNotification.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
@CronapiMetaData(type = "function", name = "{{firebaseRegister}}", nameTags = {
"Firebase","Topic","Register","Registrar" } , description = "{{firebaseRegisterDescription}}")
public static void firebaseRegister(
@ParamMetaData(type = ObjectType.STRING, description = "{{firebaseServerKey}}") Var serverKey,
@ParamMetaData(type = ObjectType.STRING, description = "{{firebaseTopicName}}") Var topicName,
@ParamMetaData(type = ObjectType.STRING, description = "{{firebaseToken}}") Var token)
throws Exception {
String baseUrl = "https://iid.googleapis.com/iid/v1/";
String topicUrl = "/rel/topics/";
RestTemplate restTemplate = new RestTemplate();
ArrayList<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new HeaderRequestInterceptor("Authorization", "key=" + serverKey.toString()));
interceptors.add(new HeaderRequestInterceptor("Content-Type", "application/json"));
restTemplate.setInterceptors(interceptors);
HttpEntity<String> request = new HttpEntity<>("");
if (token.getType().equals(Var.Type.LIST)) {
for (Var tokenItem : token.getObjectAsList()) {
String url = baseUrl + tokenItem.getObjectAsString() + topicUrl + topicName.getObjectAsString();
restTemplate.postForObject(url, request, String.class);
}
} else {
String url = baseUrl + token.getObjectAsString() + topicUrl + topicName.getObjectAsString();
restTemplate.postForObject(url, request, String.class);
}
}
}
|
src/main/java/cronapi/pushnotification/Operations.java
|
package cronapi.pushnotification;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.springframework.http.HttpEntity;
import com.google.gson.JsonObject;
import cronapi.CronapiMetaData;
import cronapi.ParamMetaData;
import cronapi.Var;
import cronapi.CronapiMetaData.CategoryType;
import cronapi.CronapiMetaData.ObjectType;
/**
* Classe que representa ...
*
* @author Usuário de Teste
* @version 1.0
* @since 2018-01-24
*
*/
@CronapiMetaData(category = CategoryType.UTIL, categoryTags = { "UTIL", "Util" })
public class Operations {
@CronapiMetaData(type = "function", name = "{{firebaseSendNotification}}", nameTags = {
"SendNotification" }, description = "{{firebaseSendNotificationDescription}}" )
public static final void sendNotification(
@ParamMetaData(type = ObjectType.STRING, description = "{{FirebaseServerKey}}") Var serverKey,
@ParamMetaData(type = ObjectType.OBJECT, description = "{{FirebaseTo}}") Var paramTo,
@ParamMetaData(type = ObjectType.STRING, description = "{{FirebaseTitle}}") Var paramTitle,
@ParamMetaData(type = ObjectType.STRING, description = "{{FirebaseBody}}") Var paramBody,
@ParamMetaData(type = ObjectType.JSON, description = "{{FirebaseData}}") Var paramData)
throws Exception {
JsonObject body = new JsonObject();
body.addProperty("to", paramTo.getObjectAsString());
body.addProperty("priority", "high");
JsonObject notification = new JsonObject();
notification.addProperty("title", paramTitle.getObjectAsString());
notification.addProperty("body", paramBody.getObjectAsString());
body.add("notification", notification);
body.add("data", (JsonObject) paramData.getObject());
HttpEntity<String> request = new HttpEntity<>(body.toString());
FirebasePushNotificationService firebaseService = new FirebasePushNotificationService(serverKey.getObjectAsString());
CompletableFuture<String> pushNotification = firebaseService.send(request);
CompletableFuture.allOf(pushNotification).join();
try {
String firebaseResponse = pushNotification.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
@CronapiMetaData(type = "function", name = "{{firebaseRegister}}", description = "{{firebaseRegisterDescription}}")
public static void firebaseRegister(
@ParamMetaData(type = ObjectType.STRING, description = "{{firebaseServerKey}}") Var serverKey,
@ParamMetaData(type = ObjectType.STRING, description = "{{firebaseTopicName}}") Var topicName,
@ParamMetaData(type = ObjectType.STRING, description = "{{firebaseToken}}") Var token)
throws Exception {
String baseUrl = "https://iid.googleapis.com/iid/v1/";
String topicUrl = "/rel/topics/";
RestTemplate restTemplate = new RestTemplate();
ArrayList<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new HeaderRequestInterceptor("Authorization", "key=" + serverKey.toString()));
interceptors.add(new HeaderRequestInterceptor("Content-Type", "application/json"));
restTemplate.setInterceptors(interceptors);
HttpEntity<String> request = new HttpEntity<>("");
if (token.getType().equals(Var.Type.LIST)) {
for (Var tokenItem : token.getObjectAsList()) {
String url = baseUrl + tokenItem.getObjectAsString() + topicUrl + topicName.getObjectAsString();
restTemplate.postForObject(url, request, String.class);
}
} else {
String url = baseUrl + token.getObjectAsString() + topicUrl + topicName.getObjectAsString();
restTemplate.postForObject(url, request, String.class);
}
}
}
|
Correção nos imports do firebase
|
src/main/java/cronapi/pushnotification/Operations.java
|
Correção nos imports do firebase
|
|
Java
|
mit
|
2beecee777f6c7e4812fce7c02700ac733d829f0
| 0
|
ClickHandlerIO/camber,ClickHandlerIO/camber,ClickHandlerIO/camber
|
package io.clickhandler.camber.client.util;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;
@JsType(isNative = true, namespace = JsPackage.GLOBAL)
public class Lodash {
public static native Object assign(Object object, Object... sources);
public static native boolean isEqual(Object o1, Object o2);
}
|
src/main/java/io/clickhandler/camber/client/util/Lodash.java
|
package io.clickhandler.camber.client.util;
import jsinterop.annotations.JsType;
@JsType(isNative = true, namespace = "Camber")
public class Lodash {
public static native Object assign(Object object, Object ... sources);
public static native boolean isEqual(Object o1, Object o2);
}
|
lodash update
|
src/main/java/io/clickhandler/camber/client/util/Lodash.java
|
lodash update
|
|
Java
|
mit
|
f42ea8136c370a41573d6f7bbf6776ab250d5660
| 0
|
Ruk33/vrJASS2
|
package ruke.vrj;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import java.io.File;
import ruke.vrj.compiler.Compiler;
public class Main {
public static void main(String[] args) {
final Compiler compiler = new Compiler();
try {
for (final String arg : args) {
final String toCompile = Files.toString(new File(arg), Charsets.UTF_8);
final String compiled = compiler.compile(toCompile);
final long start = System.nanoTime();
if (compiler.getResults().isEmpty()) {
System.out.println(compiled);
} else {
System.out.println(compiler.getResults());
}
System.out.println(
"Compiled in " +
MILLISECONDS.convert(System.nanoTime() - start, NANOSECONDS) +
" milliseconds"
);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
src/main/java/ruke/vrj/Main.java
|
package ruke.vrj;
import ruke.vrj.server.LanguageServer;
public class Main {
public static void main(String[] args) {
new LanguageServer().listen(System.in);
}
}
|
Remove LanguageServer from Main (for the moment)
|
src/main/java/ruke/vrj/Main.java
|
Remove LanguageServer from Main (for the moment)
|
|
Java
|
mit
|
975a547389d55e0d79e970892b659918511fdebe
| 0
|
DMDirc/Plugins,DMDirc/Plugins,csmith/DMDirc-Plugins,DMDirc/Plugins,csmith/DMDirc-Plugins,csmith/DMDirc-Plugins,csmith/DMDirc-Plugins,DMDirc/Plugins,csmith/DMDirc-Plugins,DMDirc/Plugins
|
/*
* Copyright (c) 2006-2014 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.addons.ui_swing;
import com.dmdirc.ServerManager;
import com.dmdirc.addons.ui_swing.commands.ChannelSettings;
import com.dmdirc.addons.ui_swing.commands.Input;
import com.dmdirc.addons.ui_swing.commands.PopInCommand;
import com.dmdirc.addons.ui_swing.commands.PopOutCommand;
import com.dmdirc.addons.ui_swing.commands.ServerSettings;
import com.dmdirc.addons.ui_swing.framemanager.FrameManagerProvider;
import com.dmdirc.addons.ui_swing.injection.SwingModule;
import com.dmdirc.config.prefs.PreferencesDialogModel;
import com.dmdirc.events.FeedbackNagEvent;
import com.dmdirc.events.FirstRunEvent;
import com.dmdirc.events.UnknownURLEvent;
import com.dmdirc.interfaces.config.AggregateConfigProvider;
import com.dmdirc.interfaces.config.ConfigProvider;
import com.dmdirc.interfaces.config.IdentityController;
import com.dmdirc.interfaces.ui.UIController;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.plugins.Exported;
import com.dmdirc.plugins.PluginInfo;
import com.dmdirc.plugins.implementations.BaseCommandPlugin;
import com.dmdirc.updater.Version;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import net.miginfocom.layout.PlatformDefaults;
import dagger.ObjectGraph;
/**
* Controls the main swing UI.
*/
public class SwingController extends BaseCommandPlugin implements UIController {
/** This plugin's plugin info object. */
private final PluginInfo pluginInfo;
/** Global config manager. */
private final AggregateConfigProvider globalConfig;
/** Addon config identity. */
private final ConfigProvider addonIdentity;
/** Apple handler, deals with Mac specific code. */
private final Apple apple;
/** The manager we're using for dependencies. */
private SwingManager swingManager;
/** This plugin's settings domain. */
private final String domain;
/** Event bus to subscribe to events with. */
private final EventBus eventBus;
/**
* Instantiates a new SwingController.
*
* @param pluginInfo Plugin info
* @param identityManager Identity Manager
* @param serverManager Server manager to use for server information.
* @param eventBus The bus to publish and subscribe to events on.
*/
public SwingController(
final PluginInfo pluginInfo,
final IdentityController identityManager,
final ServerManager serverManager,
final EventBus eventBus) {
this.pluginInfo = pluginInfo;
this.domain = pluginInfo.getDomain();
this.eventBus = eventBus;
globalConfig = identityManager.getGlobalConfiguration();
addonIdentity = identityManager.getAddonSettings();
apple = new Apple(globalConfig, serverManager, eventBus);
setAntiAlias();
}
@Override
public void load(final PluginInfo pluginInfo, final ObjectGraph graph) {
super.load(pluginInfo, graph);
setObjectGraph(graph.plus(new SwingModule(this, pluginInfo.getDomain())));
getObjectGraph().validate();
swingManager = getObjectGraph().get(SwingManager.class);
registerCommand(ServerSettings.class, ServerSettings.INFO);
registerCommand(ChannelSettings.class, ChannelSettings.INFO);
registerCommand(Input.class, Input.INFO);
registerCommand(PopOutCommand.class, PopOutCommand.INFO);
registerCommand(PopInCommand.class, PopInCommand.INFO);
}
@Override
public void onLoad() {
if (GraphicsEnvironment.isHeadless()) {
throw new IllegalStateException(
"Swing UI can't be run in a headless environment");
}
// Init the UI settings before we start any DI, as we might create frames etc.
initUISettings();
swingManager.load();
UIUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
getMainFrame().setVisible(true);
}
});
addonIdentity.setOption("ui", "textPaneFontName",
UIManager.getFont("TextPane.font").getFamily());
addonIdentity.setOption("ui", "textPaneFontSize",
UIManager.getFont("TextPane.font").getSize());
eventBus.register(this);
super.onLoad();
}
@Override
public void onUnload() {
swingManager.unload();
eventBus.unregister(this);
super.onUnload();
}
@Override
public void showConfig(final PreferencesDialogModel manager) {
manager.getCategory("GUI").addSubCategory(
new SwingPreferencesModel(pluginInfo, domain, manager.getConfigManager(),
manager.getIdentity()).getSwingUICategory());
}
@Subscribe
public void showFirstRunWizard(final FirstRunEvent event) {
if (!event.isHandled()) {
swingManager.getFirstRunExecutor().showWizardAndWait();
event.setHandled(true);
}
}
@Subscribe
public void showURLDialog(final UnknownURLEvent event) {
if (!event.isHandled()) {
event.setHandled(true);
UIUtilities.invokeLater(new Runnable() {
@Override
public void run() {
swingManager.getUrlDialogFactory().getURLDialog(event.getURI()).display();
}
});
}
}
@Subscribe
public void showFeedbackNag(final FeedbackNagEvent event) {
UIUtilities.invokeLater(new Runnable() {
@Override
public void run() {
swingManager.getFeedbackNagProvider().get();
}
});
}
/**
* Returns the version of this swing UI.
*
* @return Swing version
*/
public Version getVersion() {
return pluginInfo.getMetaData().getVersion();
}
/**
* Returns the current look and feel.
*
* @return Current look and feel
*/
public static String getLookAndFeel() {
return UIManager.getLookAndFeel().getName();
}
/**
* Returns an instance of SwingController. This method is exported for use in other plugins.
*
* @return A reference to this SwingController.
*/
@Exported
public UIController getController() {
return this;
}
/**
* Returns the exported tree manager provider.
*
* @return A tree manager provider.
*/
@Exported
public FrameManagerProvider getTreeManager() {
return swingManager.getTreeProvider();
}
/**
* Returns the exported button manager provider.
*
* @return A button manager provider.
*/
@Exported
public FrameManagerProvider getButtonManager() {
return swingManager.getButtonProvider();
}
/**
* Retrieves the main frame to use.
*
* @return The main frame to use.
*
* @deprecated Should be injected where needed.
*/
@Deprecated
public MainFrame getMainFrame() {
return swingManager.getMainFrame();
}
/**
* Make swing not use Anti Aliasing if the user doesn't want it.
*/
private void setAntiAlias() {
// For this to work it *HAS* to be before anything else UI related.
final boolean aaSetting = globalConfig.getOptionBool("ui", "antialias");
System.setProperty("awt.useSystemAAFontSettings",
Boolean.toString(aaSetting));
System.setProperty("swing.aatext", Boolean.toString(aaSetting));
}
/**
* Initialises the global UI settings for the Swing UI.
*/
private void initUISettings() {
UIUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
// This will do nothing on non OS X Systems
if (Apple.isApple()) {
apple.setUISettings();
apple.setListener();
}
final Font defaultFont = new Font(Font.DIALOG, Font.TRUETYPE_FONT, 12);
if (UIManager.getFont("TextField.font") == null) {
UIManager.put("TextField.font", defaultFont);
}
if (UIManager.getFont("TextPane.font") == null) {
UIManager.put("TextPane.font", defaultFont);
}
try {
UIUtilities.initUISettings();
UIManager.setLookAndFeel(UIUtilities.getLookAndFeel(
globalConfig.getOption("ui", "lookandfeel")));
UIUtilities.setUIFont(new Font(globalConfig.getOption("ui", "textPaneFontName"),
Font.PLAIN, 12));
} catch (UnsupportedOperationException | UnsupportedLookAndFeelException |
IllegalAccessException | InstantiationException | ClassNotFoundException ex) {
Logger.userError(ErrorLevel.LOW, "Unable to set UI Settings");
}
if ("Metal".equals(UIManager.getLookAndFeel().getName())
|| Apple.isAppleUI()) {
PlatformDefaults.setPlatform(PlatformDefaults.WINDOWS_XP);
}
}
});
}
}
|
src/com/dmdirc/addons/ui_swing/SwingController.java
|
/*
* Copyright (c) 2006-2014 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.addons.ui_swing;
import com.dmdirc.ServerManager;
import com.dmdirc.addons.ui_swing.commands.ChannelSettings;
import com.dmdirc.addons.ui_swing.commands.Input;
import com.dmdirc.addons.ui_swing.commands.PopInCommand;
import com.dmdirc.addons.ui_swing.commands.PopOutCommand;
import com.dmdirc.addons.ui_swing.commands.ServerSettings;
import com.dmdirc.addons.ui_swing.framemanager.FrameManagerProvider;
import com.dmdirc.addons.ui_swing.injection.SwingModule;
import com.dmdirc.config.prefs.PreferencesDialogModel;
import com.dmdirc.events.FeedbackNagEvent;
import com.dmdirc.events.FirstRunEvent;
import com.dmdirc.events.UnknownURLEvent;
import com.dmdirc.interfaces.config.AggregateConfigProvider;
import com.dmdirc.interfaces.config.ConfigProvider;
import com.dmdirc.interfaces.config.IdentityController;
import com.dmdirc.interfaces.ui.UIController;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.plugins.Exported;
import com.dmdirc.plugins.PluginInfo;
import com.dmdirc.plugins.implementations.BaseCommandPlugin;
import com.dmdirc.ui.IconManager;
import com.dmdirc.updater.Version;
import com.dmdirc.util.URLBuilder;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import net.miginfocom.layout.PlatformDefaults;
import dagger.ObjectGraph;
/**
* Controls the main swing UI.
*/
public class SwingController extends BaseCommandPlugin implements UIController {
/** This plugin's plugin info object. */
private final PluginInfo pluginInfo;
/** Global config manager. */
private final AggregateConfigProvider globalConfig;
/** Global config identity. */
private final ConfigProvider globalIdentity;
/** Addon config identity. */
private final ConfigProvider addonIdentity;
/** Global Swing UI Icon manager. */
private final IconManager iconManager;
/** Apple handler, deals with Mac specific code. */
private final Apple apple;
/** The manager we're using for dependencies. */
private SwingManager swingManager;
/** This plugin's settings domain. */
private final String domain;
/** Event bus to subscribe to events with. */
private final EventBus eventBus;
/**
* Instantiates a new SwingController.
*
* @param pluginInfo Plugin info
* @param identityManager Identity Manager
* @param serverManager Server manager to use for server information.
* @param urlBuilder URL builder to use to resolve icons etc.
* @param eventBus The bus to publish and subscribe to events on.
*/
public SwingController(
final PluginInfo pluginInfo,
final IdentityController identityManager,
final ServerManager serverManager,
final URLBuilder urlBuilder,
final EventBus eventBus) {
this.pluginInfo = pluginInfo;
this.domain = pluginInfo.getDomain();
this.eventBus = eventBus;
globalConfig = identityManager.getGlobalConfiguration();
globalIdentity = identityManager.getUserSettings();
addonIdentity = identityManager.getAddonSettings();
apple = new Apple(globalConfig, serverManager, eventBus);
iconManager = new IconManager(globalConfig, urlBuilder);
setAntiAlias();
}
@Override
public void load(final PluginInfo pluginInfo, final ObjectGraph graph) {
super.load(pluginInfo, graph);
setObjectGraph(graph.plus(new SwingModule(this, pluginInfo.getDomain())));
getObjectGraph().validate();
swingManager = getObjectGraph().get(SwingManager.class);
registerCommand(ServerSettings.class, ServerSettings.INFO);
registerCommand(ChannelSettings.class, ChannelSettings.INFO);
registerCommand(Input.class, Input.INFO);
registerCommand(PopOutCommand.class, PopOutCommand.INFO);
registerCommand(PopInCommand.class, PopInCommand.INFO);
}
@Override
public void onLoad() {
if (GraphicsEnvironment.isHeadless()) {
throw new IllegalStateException(
"Swing UI can't be run in a headless environment");
}
// Init the UI settings before we start any DI, as we might create frames etc.
initUISettings();
swingManager.load();
UIUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
getMainFrame().setVisible(true);
}
});
addonIdentity.setOption("ui", "textPaneFontName",
UIManager.getFont("TextPane.font").getFamily());
addonIdentity.setOption("ui", "textPaneFontSize",
UIManager.getFont("TextPane.font").getSize());
eventBus.register(this);
super.onLoad();
}
@Override
public void onUnload() {
swingManager.unload();
eventBus.unregister(this);
super.onUnload();
}
@Override
public void showConfig(final PreferencesDialogModel manager) {
manager.getCategory("GUI").addSubCategory(
new SwingPreferencesModel(pluginInfo, domain, globalConfig, globalIdentity)
.getSwingUICategory());
}
@Subscribe
public void showFirstRunWizard(final FirstRunEvent event) {
if (!event.isHandled()) {
swingManager.getFirstRunExecutor().showWizardAndWait();
event.setHandled(true);
}
}
@Subscribe
public void showURLDialog(final UnknownURLEvent event) {
if (!event.isHandled()) {
event.setHandled(true);
UIUtilities.invokeLater(new Runnable() {
@Override
public void run() {
swingManager.getUrlDialogFactory().getURLDialog(event.getURI()).display();
}
});
}
}
@Subscribe
public void showFeedbackNag(final FeedbackNagEvent event) {
UIUtilities.invokeLater(new Runnable() {
@Override
public void run() {
swingManager.getFeedbackNagProvider().get();
}
});
}
/**
* Returns the version of this swing UI.
*
* @return Swing version
*/
public Version getVersion() {
return pluginInfo.getMetaData().getVersion();
}
/**
* Returns the current look and feel.
*
* @return Current look and feel
*/
public static String getLookAndFeel() {
return UIManager.getLookAndFeel().getName();
}
/**
* Returns an instance of SwingController. This method is exported for use in other plugins.
*
* @return A reference to this SwingController.
*/
@Exported
public UIController getController() {
return this;
}
/**
* Returns the exported tree manager provider.
*
* @return A tree manager provider.
*/
@Exported
public FrameManagerProvider getTreeManager() {
return swingManager.getTreeProvider();
}
/**
* Returns the exported button manager provider.
*
* @return A button manager provider.
*/
@Exported
public FrameManagerProvider getButtonManager() {
return swingManager.getButtonProvider();
}
/**
* Retrieves the main frame to use.
*
* @return The main frame to use.
*
* @deprecated Should be injected where needed.
*/
@Deprecated
public MainFrame getMainFrame() {
return swingManager.getMainFrame();
}
/**
* @return Global config object.
*
* @deprecated Should be injected.
*/
@Deprecated
public AggregateConfigProvider getGlobalConfig() {
return globalConfig;
}
/**
* @return Global icon manager object.
*
* @deprecated Should be injected.
*/
@Deprecated
public IconManager getIconManager() {
return iconManager;
}
/**
* Make swing not use Anti Aliasing if the user doesn't want it.
*/
private void setAntiAlias() {
// For this to work it *HAS* to be before anything else UI related.
final boolean aaSetting = globalConfig.getOptionBool("ui", "antialias");
System.setProperty("awt.useSystemAAFontSettings",
Boolean.toString(aaSetting));
System.setProperty("swing.aatext", Boolean.toString(aaSetting));
}
/**
* Initialises the global UI settings for the Swing UI.
*/
private void initUISettings() {
UIUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
// This will do nothing on non OS X Systems
if (Apple.isApple()) {
apple.setUISettings();
apple.setListener();
}
final Font defaultFont = new Font(Font.DIALOG, Font.TRUETYPE_FONT, 12);
if (UIManager.getFont("TextField.font") == null) {
UIManager.put("TextField.font", defaultFont);
}
if (UIManager.getFont("TextPane.font") == null) {
UIManager.put("TextPane.font", defaultFont);
}
try {
UIUtilities.initUISettings();
UIManager.setLookAndFeel(UIUtilities.getLookAndFeel(
globalConfig.getOption("ui", "lookandfeel")));
UIUtilities.setUIFont(new Font(globalConfig.getOption("ui", "textPaneFontName"),
Font.PLAIN, 12));
} catch (UnsupportedOperationException | UnsupportedLookAndFeelException |
IllegalAccessException | InstantiationException | ClassNotFoundException ex) {
Logger.userError(ErrorLevel.LOW, "Unable to set UI Settings");
}
if ("Metal".equals(UIManager.getLookAndFeel().getName())
|| Apple.isAppleUI()) {
PlatformDefaults.setPlatform(PlatformDefaults.WINDOWS_XP);
}
}
});
}
}
|
Remove unused deprecated methods.
and some useless fields.
Change-Id: I5a57109dc1b584e96654e4079bcdca1ede24eb2a
Reviewed-on: http://gerrit.dmdirc.com/3314
Automatic-Compile: DMDirc Build Manager
Reviewed-by: Chris Smith <711c73f64afdce07b7e38039a96d2224209e9a6c@dmdirc.com>
|
src/com/dmdirc/addons/ui_swing/SwingController.java
|
Remove unused deprecated methods.
|
|
Java
|
epl-1.0
|
ddd31e3e2d368a0f2abd204d74a58c68b818fc3e
| 0
|
spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4
|
/*******************************************************************************
* Copyright (c) 2017, 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.vscode.commons.boot.app.cli;
import java.io.IOException;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ide.vscode.commons.util.CollectorUtil;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
/**
* @author Martin Lippert
*/
public class LocalSpringBootApp extends AbstractSpringBootApp {
private static final Logger logger = LoggerFactory.getLogger(LocalSpringBootApp.class);
private VirtualMachine vm;
private VirtualMachineDescriptor vmd;
private static final String LOCAL_CONNECTOR_ADDRESS = "com.sun.management.jmxremote.localConnectorAddress";
private Boolean isSpringBootApp;
private static LocalSpringBootAppCache cache = new LocalSpringBootAppCache();
public static Collection<SpringBootApp> getAllRunningJavaApps() throws Exception {
return cache.getAllRunningJavaApps();
}
public static Collection<SpringBootApp> getAllRunningSpringApps() throws Exception {
return getAllRunningJavaApps().stream().filter(SpringBootApp::isSpringBootApp).collect(CollectorUtil.toImmutableList());
}
public LocalSpringBootApp(VirtualMachineDescriptor vmd) throws AttachNotSupportedException, IOException {
try {
this.vm = VirtualMachine.attach(vmd);
this.vmd = vmd;
} catch (IOException | AttachNotSupportedException e) {
// Dispose JMX connection before throwing exception
dispose();
throw e;
}
}
@Override
protected String getJmxUrl() {
String address = null;
try {
address = vm.getAgentProperties().getProperty(LOCAL_CONNECTOR_ADDRESS);
} catch (Exception e) {
//ignore
}
if (address==null) {
try {
address = vm.startLocalManagementAgent();
} catch (IOException e) {
logger.error("Error starting local management agent", e);
}
}
return address;
}
// Supplier<String> jmxConnectUrl = Suppliers.memoize(() -> {
// });
@Override
public String getProcessID() {
return vmd.id();
}
@Override
public String getProcessName() {
String rawName = vmd.displayName();
int firstSpace = rawName.indexOf(' ');
return firstSpace < 0 ? rawName : rawName.substring(0, firstSpace);
}
@Override
public boolean isSpringBootApp() {
if (isSpringBootApp==null) {
try {
isSpringBootApp = !containsSystemProperty("sts4.languageserver.name")
&& (
isSpringBootAppClasspath() ||
isSpringBootAppSysprops()
);
} catch (Exception e) {
//Couldn't determine if the VM is a spring boot app. Could be it already died. Or could be its not accessible (yet).
// We will ignore the exception, pretend its not a boot app (most likely isn't) but DO NOT CACHE this result
// so it will be retried again on the next polling loop.
return false;
}
}
return isSpringBootApp;
}
private boolean isSpringBootAppSysprops() throws IOException {
Properties sysprops = getSystemProperties();
return "org.springframework.boot.loader".equals(sysprops.getProperty("java.protocol.handler.pkgs"));
}
private boolean isSpringBootAppClasspath() throws Exception {
return contains(getClasspath(), "spring-boot");
}
@Override
public Properties getSystemProperties() throws IOException {
return this.vm.getSystemProperties();
}
public boolean containsSystemProperty(Object key) throws IOException {
Properties props = getSystemProperties();
return props.containsKey(key);
}
protected boolean contains(String[] cpElements, String element) {
for (String cpElement : cpElements) {
if (cpElement.contains(element)) {
return true;
}
}
return false;
}
@Override
public String toString() {
return "LocalSpringBootApp [id=" +getProcessID() + ", name=`"+getProcessName()+"`]";
}
/**
* For testing / investigation purposes. Dumps out as much information as possible
* that can be onbtained from the jvm, without accessing JMX.
*/
public void dumpJvmInfo() throws IOException {
System.out.println("--- vm infos ----");
System.out.println("id = "+vm.id());
System.out.println("displayName = "+vmd.displayName());
dump("agentProperties", vm.getAgentProperties());
dump("systemProps", vm.getSystemProperties());
System.out.println("-----------------");
}
private void dump(String name, Properties props) {
System.out.println(name + " = {");
for (Entry<Object, Object> prop : props.entrySet()) {
System.out.println(" "+prop.getKey()+" = "+prop.getValue());
}
System.out.println("}");
}
@Override
public void dispose() {
if (vm!=null) {
logger.info("SpringBootApp disposed: "+this);
try {
vm.detach();
} catch (Exception e) {
}
vm = null;
}
if (vmd!=null) {
vmd = null;
}
super.dispose();
}
}
|
headless-services/commons/commons-boot-app-cli/src/main/java/org/springframework/ide/vscode/commons/boot/app/cli/LocalSpringBootApp.java
|
/*******************************************************************************
* Copyright (c) 2017, 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.vscode.commons.boot.app.cli;
import java.io.IOException;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ide.vscode.commons.util.CollectorUtil;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
/**
* @author Martin Lippert
*/
public class LocalSpringBootApp extends AbstractSpringBootApp {
private static final Logger logger = LoggerFactory.getLogger(LocalSpringBootApp.class);
private VirtualMachine vm;
private VirtualMachineDescriptor vmd;
private static final String LOCAL_CONNECTOR_ADDRESS = "com.sun.management.jmxremote.localConnectorAddress";
private Boolean isSpringBootApp;
private static LocalSpringBootAppCache cache = new LocalSpringBootAppCache();
public static Collection<SpringBootApp> getAllRunningJavaApps() throws Exception {
return cache.getAllRunningJavaApps();
}
public static Collection<SpringBootApp> getAllRunningSpringApps() throws Exception {
return getAllRunningJavaApps().stream().filter(SpringBootApp::isSpringBootApp).collect(CollectorUtil.toImmutableList());
}
public LocalSpringBootApp(VirtualMachineDescriptor vmd) throws AttachNotSupportedException, IOException {
this.vm = VirtualMachine.attach(vmd);
this.vmd = vmd;
}
@Override
protected String getJmxUrl() {
String address = null;
try {
address = vm.getAgentProperties().getProperty(LOCAL_CONNECTOR_ADDRESS);
} catch (Exception e) {
//ignore
}
if (address==null) {
try {
address = vm.startLocalManagementAgent();
} catch (IOException e) {
logger.error("Error starting local management agent", e);
dispose();
}
}
return address;
}
// Supplier<String> jmxConnectUrl = Suppliers.memoize(() -> {
// });
@Override
public String getProcessID() {
return vmd.id();
}
@Override
public String getProcessName() {
String rawName = vmd.displayName();
int firstSpace = rawName.indexOf(' ');
return firstSpace < 0 ? rawName : rawName.substring(0, firstSpace);
}
@Override
public boolean isSpringBootApp() {
if (isSpringBootApp==null) {
try {
isSpringBootApp = !containsSystemProperty("sts4.languageserver.name")
&& (
isSpringBootAppClasspath() ||
isSpringBootAppSysprops()
);
} catch (Exception e) {
//Couldn't determine if the VM is a spring boot app. Could be it already died. Or could be its not accessible (yet).
// We will ignore the exception, pretend its not a boot app (most likely isn't) but DO NOT CACHE this result
// so it will be retried again on the next polling loop.
return false;
}
}
return isSpringBootApp;
}
private boolean isSpringBootAppSysprops() throws IOException {
Properties sysprops = getSystemProperties();
return "org.springframework.boot.loader".equals(sysprops.getProperty("java.protocol.handler.pkgs"));
}
private boolean isSpringBootAppClasspath() throws Exception {
return contains(getClasspath(), "spring-boot");
}
@Override
public Properties getSystemProperties() throws IOException {
return this.vm.getSystemProperties();
}
public boolean containsSystemProperty(Object key) throws IOException {
Properties props = getSystemProperties();
return props.containsKey(key);
}
protected boolean contains(String[] cpElements, String element) {
for (String cpElement : cpElements) {
if (cpElement.contains(element)) {
return true;
}
}
return false;
}
@Override
public String toString() {
return "LocalSpringBootApp [id=" +getProcessID() + ", name=`"+getProcessName()+"`]";
}
/**
* For testing / investigation purposes. Dumps out as much information as possible
* that can be onbtained from the jvm, without accessing JMX.
*/
public void dumpJvmInfo() throws IOException {
System.out.println("--- vm infos ----");
System.out.println("id = "+vm.id());
System.out.println("displayName = "+vmd.displayName());
dump("agentProperties", vm.getAgentProperties());
dump("systemProps", vm.getSystemProperties());
System.out.println("-----------------");
}
private void dump(String name, Properties props) {
System.out.println(name + " = {");
for (Entry<Object, Object> prop : props.entrySet()) {
System.out.println(" "+prop.getKey()+" = "+prop.getValue());
}
System.out.println("}");
}
@Override
public void dispose() {
if (vm!=null) {
logger.info("SpringBootApp disposed: "+this);
try {
vm.detach();
} catch (Exception e) {
}
vm = null;
}
if (vmd!=null) {
vmd = null;
}
super.dispose();
}
}
|
PT #159690556: Dispose JMX connection (proper fix)
|
headless-services/commons/commons-boot-app-cli/src/main/java/org/springframework/ide/vscode/commons/boot/app/cli/LocalSpringBootApp.java
|
PT #159690556: Dispose JMX connection (proper fix)
|
|
Java
|
epl-1.0
|
75f605f2cd53704b2e407d0f4fec2cb4fbe3c6ae
| 0
|
eclipse/packagedrone,ibh-systems/packagedrone,eclipse/packagedrone,ibh-systems/packagedrone,mschreiber/packagedrone,mschreiber/packagedrone,ibh-systems/packagedrone,mschreiber/packagedrone,ibh-systems/packagedrone,mschreiber/packagedrone,eclipse/packagedrone,eclipse/packagedrone
|
/*******************************************************************************
* Copyright (c) 2015, 2016 IBH SYSTEMS GmbH.
* 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:
* IBH SYSTEMS GmbH - initial API and implementation
* M-Ezzat - code cleanup - squid:S2131
*******************************************************************************/
package org.eclipse.packagedrone.utils.rpm.yum;
import java.io.IOException;
import java.io.OutputStream;
import java.time.Instant;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeSet;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.bouncycastle.bcpg.HashAlgorithmTags;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.eclipse.packagedrone.utils.io.IOConsumer;
import org.eclipse.packagedrone.utils.io.OutputSpooler;
import org.eclipse.packagedrone.utils.io.SpoolOutTarget;
import org.eclipse.packagedrone.utils.rpm.HashAlgorithm;
import org.eclipse.packagedrone.utils.rpm.RpmVersion;
import org.eclipse.packagedrone.utils.rpm.deps.RpmDependencyFlags;
import org.eclipse.packagedrone.utils.rpm.info.RpmInformation;
import org.eclipse.packagedrone.utils.rpm.info.RpmInformation.Changelog;
import org.eclipse.packagedrone.utils.rpm.info.RpmInformation.Dependency;
import org.eclipse.packagedrone.utils.security.pgp.SigningStream;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class RepositoryCreator
{
private static final String MD_NAME = "SHA-256";
private static final String MD_TAG = "sha256";
private final XmlContext xml;
private final OutputSpooler primaryStreamBuilder;
private final OutputSpooler filelistsStreamBuilder;
private final OutputSpooler otherStreamBuilder;
private final OutputSpooler mdStreamBuilder;
private final List<Pattern> primaryFiles;
private final List<Pattern> primaryDirs;
private final String primaryUniqueName;
private final String filelistsUniqueName;
private final String otherUniqueName;
public interface XmlContext
{
public void write ( Document primary, OutputStream primaryStream ) throws IOException;
public Document createDocument ();
}
public static class DefaultXmlContext implements XmlContext
{
private final DocumentBuilderFactory documentBuilderFactory;
private final TransformerFactory transformerFactory;
public DefaultXmlContext ()
{
this.documentBuilderFactory = DocumentBuilderFactory.newInstance ();
this.documentBuilderFactory.setNamespaceAware ( true );
this.transformerFactory = TransformerFactory.newInstance ();
}
public DefaultXmlContext ( final DocumentBuilderFactory documentBuilderFactory, final TransformerFactory transformerFactory )
{
Objects.requireNonNull ( documentBuilderFactory );
Objects.requireNonNull ( transformerFactory );
if ( !documentBuilderFactory.isNamespaceAware () )
{
throw new IllegalArgumentException ( "The provided DocumentBuilderFactory must be namespace aware" );
}
this.documentBuilderFactory = DocumentBuilderFactory.newInstance ();
this.documentBuilderFactory.setNamespaceAware ( true );
this.transformerFactory = TransformerFactory.newInstance ();
}
@Override
public Document createDocument ()
{
try
{
return this.documentBuilderFactory.newDocumentBuilder ().newDocument ();
}
catch ( final ParserConfigurationException e )
{
throw new RuntimeException ( e );
}
}
@Override
public void write ( final Document doc, final OutputStream outputStream ) throws IOException
{
try
{
final Transformer transformer = this.transformerFactory.newTransformer ();
final DOMSource source = new DOMSource ( doc );
final Result result = new StreamResult ( outputStream );
transformer.setOutputProperty ( OutputKeys.INDENT, "yes" );
transformer.setOutputProperty ( OutputKeys.ENCODING, "UTF-8" );
transformer.setOutputProperty ( "{http://xml.apache.org/xslt}indent-amount", "2" );
transformer.transform ( source, result );
}
catch ( final TransformerException e )
{
throw new IOException ( e );
}
}
}
public interface Context
{
public void addPackage ( FileInformation fileInformation, RpmInformation rpmInformation, Map<HashAlgorithm, String> checksums, HashAlgorithm idType );
}
public static class FileInformation
{
private final Instant timestamp;
private final long size;
private final String location;
public FileInformation ( final Instant timestamp, final long size, final String location )
{
this.timestamp = timestamp;
this.size = size;
this.location = location;
}
public Instant getTimestamp ()
{
return this.timestamp;
}
public long getSize ()
{
return this.size;
}
public String getLocation ()
{
return this.location;
}
}
private class ContextImpl implements Context
{
private final OutputStream primaryStream;
private final OutputStream filelistsStream;
private final OutputStream otherStream;
private final XmlContext xml;
private final Document primary;
private final Document filelists;
private final Document other;
private final Element primaryRoot;
private final Element filelistsRoot;
private final Element otherRoot;
private long count;
public ContextImpl ( final OutputStream primaryStream, final OutputStream filelistsStream, final OutputStream otherStream, final XmlContext xml )
{
this.primaryStream = primaryStream;
this.filelistsStream = filelistsStream;
this.otherStream = otherStream;
this.xml = xml;
this.primary = xml.createDocument ();
this.primaryRoot = this.primary.createElementNS ( "http://linux.duke.edu/metadata/common", "metadata" );
this.primaryRoot.setAttribute ( "xmlns:rpm", "http://linux.duke.edu/metadata/rpm" );
this.primary.appendChild ( this.primaryRoot );
this.filelists = xml.createDocument ();
this.filelistsRoot = this.filelists.createElementNS ( "http://linux.duke.edu/metadata/filelists", "filelists" );
this.filelists.appendChild ( this.filelistsRoot );
this.other = xml.createDocument ();
this.otherRoot = this.other.createElementNS ( "http://linux.duke.edu/metadata/other", "otherdata" );
this.other.appendChild ( this.otherRoot );
}
@Override
public void addPackage ( final FileInformation fileInformation, final RpmInformation info, final Map<HashAlgorithm, String> checksums, final HashAlgorithm idType )
{
Objects.requireNonNull ( fileInformation );
Objects.requireNonNull ( info );
Objects.requireNonNull ( checksums );
Objects.requireNonNull ( idType );
final String id = checksums.get ( idType );
if ( id == null || id.isEmpty () )
{
throw new IllegalArgumentException ( String.format ( "Checksums map did not contain a value for the ID type: %s", idType ) );
}
this.count++;
// insert to primary
insertToPrimary ( fileInformation, info, checksums, idType );
// insert to "filelists"
{
final Element pkg = createPackage ( this.filelistsRoot, id, info );
appendFiles ( info, pkg, null, null );
}
// insert to "other"
{
final Element pkg = createPackage ( this.otherRoot, id, info );
for ( final Changelog log : info.getChangelog () )
{
final Element cl = addElement ( pkg, "changelog", log.getText () );
cl.setAttribute ( "author", log.getAuthor () );
cl.setAttribute ( "date", "" + log.getTimestamp () );
}
}
}
private void appendFiles ( final RpmInformation info, final Element pkg, final Predicate<String> fileFilter, final Predicate<String> dirFilter )
{
for ( final String file : new TreeSet<> ( info.getFiles () ) )
{
if ( fileFilter == null || fileFilter.test ( file ) )
{
addElement ( pkg, "file", file );
}
}
for ( final String dir : new TreeSet<> ( info.getDirectories () ) )
{
if ( dirFilter == null || dirFilter.test ( dir ) )
{
final Element ele = addElement ( pkg, "file", dir );
ele.setAttribute ( "type", "dir" );
}
}
}
private void insertToPrimary ( final FileInformation fileInformation, final RpmInformation info, final Map<HashAlgorithm, String> checksums, final HashAlgorithm idType )
{
final Element pkg = addElement ( this.primaryRoot, "package" );
pkg.setAttribute ( "type", "rpm" );
addElement ( pkg, "name", info.getName () );
addElement ( pkg, "arch", info.getArchitecture () );
addVersion ( pkg, info.getVersion () );
for ( final Map.Entry<HashAlgorithm, String> entry : checksums.entrySet () )
{
final Element checksum = addElement ( pkg, "checksum", entry.getValue () );
checksum.setAttribute ( "type", entry.getKey ().getId () );
if ( entry.getKey () == idType )
{
checksum.setAttribute ( "pkgid", "YES" );
}
}
addElement ( pkg, "summary", info.getSummary () );
addElement ( pkg, "description", info.getDescription () );
addElement ( pkg, "packager", info.getPackager () );
addElement ( pkg, "url", info.getUrl () );
// time
final Element time = addElement ( pkg, "time" );
time.setAttribute ( "file", "" + fileInformation.getTimestamp ().getEpochSecond () );
if ( info.getBuildTimestamp () != null )
{
time.setAttribute ( "build", "" + info.getBuildTimestamp () );
}
// size
final Element size = addElement ( pkg, "size" );
size.setAttribute ( "package", "" + fileInformation.getSize () );
if ( info.getInstalledSize () != null )
{
size.setAttribute ( "installed", "" + info.getInstalledSize () );
}
if ( info.getArchiveSize () != null )
{
size.setAttribute ( "archive", "" + info.getArchiveSize () );
}
// location
final Element location = addElement ( pkg, "location" );
location.setAttribute ( "href", fileInformation.getLocation () );
// add format section
final Element fmt = addElement ( pkg, "format" );
addOptionalElement ( fmt, "rpm:license", info.getLicense () );
addOptionalElement ( fmt, "rpm:vendor", info.getVendor () );
addOptionalElement ( fmt, "rpm:group", info.getGroup () );
addOptionalElement ( fmt, "rpm:buildhost", info.getBuildHost () );
addOptionalElement ( fmt, "rpm:sourcerpm", info.getSourcePackage () );
// add header range
final Element rng = addElement ( fmt, "rpm:header-range" );
rng.setAttribute ( "start", "" + info.getHeaderStart () );
rng.setAttribute ( "end", "" + info.getHeaderEnd () );
addDependencies ( fmt, "rpm:provides", info.getProvides () );
addDependencies ( fmt, "rpm:requires", info.getRequires () );
addDependencies ( fmt, "rpm:conflicts", info.getConflicts () );
addDependencies ( fmt, "rpm:obsoletes", info.getObsoletes () );
// add primary files
appendFiles ( info, pkg, file -> matches ( file, RepositoryCreator.this.primaryFiles ), dir -> matches ( dir, RepositoryCreator.this.primaryDirs ) );
}
private void addDependencies ( final Element fmt, final String elementName, final List<Dependency> deps )
{
final Element ele = addElement ( fmt, elementName );
for ( final Dependency dep : deps )
{
final EnumSet<RpmDependencyFlags> flags = RpmDependencyFlags.parse ( dep.getFlags () );
if ( flags.contains ( RpmDependencyFlags.RPMLIB ) )
{
continue;
}
final Element entry = addElement ( ele, "rpm:entry" );
entry.setAttribute ( "name", dep.getName () );
if ( dep.getVersion () != null )
{
final RpmVersion version = RpmVersion.valueOf ( dep.getVersion () );
entry.setAttribute ( "epoch", "" + version.getEpoch ().orElse ( 0 ) );
entry.setAttribute ( "ver", version.getVersion () );
if ( version.getRelease ().isPresent () )
{
entry.setAttribute ( "rel", version.getRelease ().get () );
}
}
final boolean eq = flags.contains ( RpmDependencyFlags.EQUAL );
if ( flags.contains ( RpmDependencyFlags.GREATER ) )
{
entry.setAttribute ( "flags", eq ? "GE" : "GT" );
}
else if ( flags.contains ( RpmDependencyFlags.LESS ) )
{
entry.setAttribute ( "flags", eq ? "LE" : "LT" );
}
else if ( eq )
{
entry.setAttribute ( "flags", "EQ" );
}
final boolean pre = flags.contains ( RpmDependencyFlags.PREREQ ) || flags.contains ( RpmDependencyFlags.SCRIPT_PRE ) || flags.contains ( RpmDependencyFlags.SCRIPT_POST );
if ( pre )
{
entry.setAttribute ( "pre", "1" );
}
}
}
private Element createPackage ( final Element root, final String id, final RpmInformation info )
{
final Element pkg = addElement ( root, "package" );
pkg.setAttribute ( "pkgid", id );
pkg.setAttribute ( "name", info.getName () );
pkg.setAttribute ( "arch", info.getArchitecture () );
addVersion ( pkg, info.getVersion () );
return pkg;
}
private Element addVersion ( final Element pkg, final RpmInformation.Version version )
{
if ( version == null )
{
return null;
}
final Element ver = addElement ( pkg, "version" );
if ( version.getEpoch () == null || version.getEpoch ().isEmpty () )
{
ver.setAttribute ( "epoch", "0" );
}
else
{
ver.setAttribute ( "epoch", version.getEpoch () );
}
ver.setAttribute ( "ver", version.getVersion () );
ver.setAttribute ( "rel", version.getRelease () );
return ver;
}
public void close () throws IOException
{
this.primaryRoot.setAttribute ( "packages", Long.toString ( this.count ) );
this.filelistsRoot.setAttribute ( "packages", Long.toString ( this.count ) );
this.otherRoot.setAttribute ( "packages", Long.toString ( this.count ) );
try
{
this.xml.write ( this.primary, this.primaryStream );
this.xml.write ( this.filelists, this.filelistsStream );
this.xml.write ( this.other, this.otherStream );
}
catch ( final IOException e )
{
throw e;
}
catch ( final Exception e )
{
throw new IOException ( e );
}
}
}
public static class Builder
{
private SpoolOutTarget target;
private XmlContext xmlContext;
private Function<OutputStream, OutputStream> signingStreamCreator;
public Builder ()
{
}
public Builder setTarget ( final SpoolOutTarget target )
{
this.target = target;
return this;
}
public Builder setXmlContext ( final XmlContext xmlContext )
{
this.xmlContext = xmlContext;
return this;
}
public Builder setSigning ( final Function<OutputStream, OutputStream> signingStreamCreator )
{
this.signingStreamCreator = signingStreamCreator;
return this;
}
public Builder setSigning ( final PGPPrivateKey privateKey )
{
return setSigning ( privateKey, HashAlgorithmTags.SHA1 );
}
public Builder setSigning ( final PGPPrivateKey privateKey, final HashAlgorithm hashAlgorithm )
{
return setSigning ( privateKey, hashAlgorithm.getValue () );
}
public Builder setSigning ( final PGPPrivateKey privateKey, final int digestAlgorithm )
{
if ( privateKey != null )
{
this.signingStreamCreator = output -> new SigningStream ( output, privateKey, digestAlgorithm, false );
}
else
{
this.signingStreamCreator = null;
}
return this;
}
public RepositoryCreator build ()
{
return new RepositoryCreator ( this.target, this.xmlContext == null ? new DefaultXmlContext () : this.xmlContext, this.signingStreamCreator );
}
}
private RepositoryCreator ( final SpoolOutTarget target, final XmlContext xml, final Function<OutputStream, OutputStream> signingStreamCreator )
{
Objects.requireNonNull ( target );
Objects.requireNonNull ( xml );
// xml
this.xml = xml;
// filters
final String dirFilter = System.getProperty ( "drone.rpm.yum.primaryDirs", "bin/,^/etc/" );
final String fileFilter = System.getProperty ( "drone.rpm.yum.primaryFiles", dirFilter );
this.primaryFiles = Arrays.stream ( fileFilter.split ( "," ) ).map ( re -> Pattern.compile ( re ) ).collect ( Collectors.toList () );
this.primaryDirs = Arrays.stream ( dirFilter.split ( "," ) ).map ( re -> Pattern.compile ( re ) ).collect ( Collectors.toList () );
this.primaryUniqueName = UUID.randomUUID ().toString ().replace ( "-", "" );
this.filelistsUniqueName = UUID.randomUUID ().toString ().replace ( "-", "" );
this.otherUniqueName = UUID.randomUUID ().toString ().replace ( "-", "" );
// primary
this.primaryStreamBuilder = new OutputSpooler ( target );
this.primaryStreamBuilder.addDigest ( MD_NAME );
this.primaryStreamBuilder.addOutput ( String.format ( "repodata/%s-primary.xml", this.primaryUniqueName ), "application/xml" );
this.primaryStreamBuilder.addOutput ( String.format ( "repodata/%s-primary.xml.gz", this.primaryUniqueName ), "application/x-gzip", output -> new GZIPOutputStream ( output ) );
// filelists
this.filelistsStreamBuilder = new OutputSpooler ( target );
this.filelistsStreamBuilder.addDigest ( MD_NAME );
this.filelistsStreamBuilder.addOutput ( String.format ( "repodata/%s-filelists.xml", this.filelistsUniqueName ), "application/xml" );
this.filelistsStreamBuilder.addOutput ( String.format ( "repodata/%s-filelists.xml.gz", this.filelistsUniqueName ), "application/x-gzip", output -> new GZIPOutputStream ( output ) );
// other
this.otherStreamBuilder = new OutputSpooler ( target );
this.otherStreamBuilder.addDigest ( MD_NAME );
this.otherStreamBuilder.addOutput ( String.format ( "repodata/%s-other.xml", this.otherUniqueName ), "application/xml" );
this.otherStreamBuilder.addOutput ( String.format ( "repodata/%s-other.xml.gz", this.otherUniqueName ), "application/x-gzip", output -> new GZIPOutputStream ( output ) );
// md
this.mdStreamBuilder = new OutputSpooler ( target );
this.mdStreamBuilder.addOutput ( "repodata/repomd.xml", "application/xml" );
if ( signingStreamCreator != null )
{
this.mdStreamBuilder.addOutput ( "repodata/repomd.xml.asc", "text/plain", signingStreamCreator::apply );
}
}
private boolean matches ( final String pathName, final List<Pattern> filterList )
{
for ( final Pattern p : filterList )
{
if ( p.matcher ( pathName ).find () )
{
return true;
}
}
return false;
}
public void process ( final IOConsumer<Context> consumer ) throws IOException
{
final long now = System.currentTimeMillis ();
this.primaryStreamBuilder.open ( primaryStream -> {
this.filelistsStreamBuilder.open ( filelistsStream -> {
this.otherStreamBuilder.open ( otherStream -> {
final ContextImpl ctx = makeContext ( primaryStream, filelistsStream, otherStream );
consumer.accept ( ctx );
ctx.close ();
} );
} );
} );
this.mdStreamBuilder.open ( stream -> {
writeRepoMd ( stream, now );
} );
}
private ContextImpl makeContext ( final OutputStream primaryStream, final OutputStream filelistsStream, final OutputStream otherStream )
{
return new ContextImpl ( primaryStream, filelistsStream, otherStream, this.xml );
}
private void writeRepoMd ( final OutputStream stream, final long now ) throws IOException
{
final Document doc = this.xml.createDocument ();
final Element root = doc.createElementNS ( "http://linux.duke.edu/metadata/repo", "repomd" );
doc.appendChild ( root );
root.setAttribute ( "revision", Long.toString ( now / 1000 ) );
addDataFile ( root, this.primaryStreamBuilder, this.primaryUniqueName, "primary", now );
addDataFile ( root, this.filelistsStreamBuilder, this.filelistsUniqueName, "filelists", now );
addDataFile ( root, this.otherStreamBuilder, this.otherUniqueName, "other", now );
try
{
this.xml.write ( doc, stream );
}
catch ( final Exception e )
{
throw new IOException ( e );
}
}
private void addDataFile ( final Element root, final OutputSpooler spooler, final String unique, final String baseName, final long now )
{
final String filename = "repodata/" + unique + "-" + baseName + ".xml";
final Element data = addElement ( root, "data" );
data.setAttribute ( "type", baseName );
final Element checksum = addElement ( data, "checksum", spooler.getChecksum ( filename + ".gz", MD_NAME ) );
checksum.setAttribute ( "type", MD_TAG );
final Element openChecksum = addElement ( data, "open-checksum", spooler.getChecksum ( filename, MD_NAME ) );
openChecksum.setAttribute ( "type", MD_TAG );
final Element location = addElement ( data, "location" );
location.setAttribute ( "href", filename + ".gz" );
addElement ( data, "timestamp", now / 1000 );
addElement ( data, "size", "" + spooler.getSize ( filename + ".gz" ) );
addElement ( data, "open-size", "" + spooler.getSize ( filename ) );
}
private static void addOptionalElement ( final Element parent, final String name, final Object value )
{
if ( value == null )
{
return;
}
addElement ( parent, name, value );
}
private static Element addElement ( final Element parent, final String name )
{
return addElement ( parent, name, null );
}
private static Element addElement ( final Element parent, final String name, final Object value )
{
final Document doc = parent.getOwnerDocument ();
final Element result = doc.createElement ( name );
parent.appendChild ( result );
if ( value != null )
{
result.appendChild ( doc.createTextNode ( value.toString () ) );
}
return result;
}
}
|
bundles/org.eclipse.packagedrone.utils.rpm/src/org/eclipse/packagedrone/utils/rpm/yum/RepositoryCreator.java
|
/*******************************************************************************
* Copyright (c) 2015, 2016 IBH SYSTEMS GmbH.
* 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:
* IBH SYSTEMS GmbH - initial API and implementation
* M-Ezzat - code cleanup - squid:S2131
*******************************************************************************/
package org.eclipse.packagedrone.utils.rpm.yum;
import java.io.IOException;
import java.io.OutputStream;
import java.time.Instant;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeSet;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.bouncycastle.bcpg.HashAlgorithmTags;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.eclipse.packagedrone.utils.io.IOConsumer;
import org.eclipse.packagedrone.utils.io.OutputSpooler;
import org.eclipse.packagedrone.utils.io.SpoolOutTarget;
import org.eclipse.packagedrone.utils.rpm.HashAlgorithm;
import org.eclipse.packagedrone.utils.rpm.RpmVersion;
import org.eclipse.packagedrone.utils.rpm.deps.RpmDependencyFlags;
import org.eclipse.packagedrone.utils.rpm.info.RpmInformation;
import org.eclipse.packagedrone.utils.rpm.info.RpmInformation.Changelog;
import org.eclipse.packagedrone.utils.rpm.info.RpmInformation.Dependency;
import org.eclipse.packagedrone.utils.security.pgp.SigningStream;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class RepositoryCreator
{
private static final String MD_NAME = "SHA-256";
private static final String MD_TAG = "sha256";
private final XmlContext xml;
private final OutputSpooler primaryStreamBuilder;
private final OutputSpooler filelistsStreamBuilder;
private final OutputSpooler otherStreamBuilder;
private final OutputSpooler mdStreamBuilder;
private final List<Pattern> primaryFiles;
private final List<Pattern> primaryDirs;
private final String primaryUniqueName;
private final String filelistsUniqueName;
private final String otherUniqueName;
public interface XmlContext
{
public void write ( Document primary, OutputStream primaryStream ) throws IOException;
public Document createDocument ();
}
public static class DefaultXmlContext implements XmlContext
{
private final DocumentBuilderFactory documentBuilderFactory;
private final TransformerFactory transformerFactory;
public DefaultXmlContext ()
{
this.documentBuilderFactory = DocumentBuilderFactory.newInstance ();
this.documentBuilderFactory.setNamespaceAware ( true );
this.transformerFactory = TransformerFactory.newInstance ();
}
public DefaultXmlContext ( final DocumentBuilderFactory documentBuilderFactory, final TransformerFactory transformerFactory )
{
Objects.requireNonNull ( documentBuilderFactory );
Objects.requireNonNull ( transformerFactory );
if ( !documentBuilderFactory.isNamespaceAware () )
{
throw new IllegalArgumentException ( "The provided DocumentBuilderFactory must be namespace aware" );
}
this.documentBuilderFactory = DocumentBuilderFactory.newInstance ();
this.documentBuilderFactory.setNamespaceAware ( true );
this.transformerFactory = TransformerFactory.newInstance ();
}
@Override
public Document createDocument ()
{
try
{
return this.documentBuilderFactory.newDocumentBuilder ().newDocument ();
}
catch ( final ParserConfigurationException e )
{
throw new RuntimeException ( e );
}
}
@Override
public void write ( final Document doc, final OutputStream outputStream ) throws IOException
{
try
{
final Transformer transformer = this.transformerFactory.newTransformer ();
final DOMSource source = new DOMSource ( doc );
final Result result = new StreamResult ( outputStream );
transformer.setOutputProperty ( OutputKeys.INDENT, "yes" );
transformer.setOutputProperty ( OutputKeys.ENCODING, "UTF-8" );
transformer.setOutputProperty ( "{http://xml.apache.org/xslt}indent-amount", "2" );
transformer.transform ( source, result );
}
catch ( final TransformerException e )
{
throw new IOException ( e );
}
}
}
public interface Context
{
public void addPackage ( FileInformation fileInformation, RpmInformation rpmInformation, Map<HashAlgorithm, String> checksums, HashAlgorithm idType );
}
public static class FileInformation
{
private final Instant timestamp;
private final long size;
private final String location;
public FileInformation ( final Instant timestamp, final long size, final String location )
{
this.timestamp = timestamp;
this.size = size;
this.location = location;
}
public Instant getTimestamp ()
{
return this.timestamp;
}
public long getSize ()
{
return this.size;
}
public String getLocation ()
{
return this.location;
}
}
private class ContextImpl implements Context
{
private final OutputStream primaryStream;
private final OutputStream filelistsStream;
private final OutputStream otherStream;
private final XmlContext xml;
private final Document primary;
private final Document filelists;
private final Document other;
private final Element primaryRoot;
private final Element filelistsRoot;
private final Element otherRoot;
private long count;
public ContextImpl ( final OutputStream primaryStream, final OutputStream filelistsStream, final OutputStream otherStream, final XmlContext xml )
{
this.primaryStream = primaryStream;
this.filelistsStream = filelistsStream;
this.otherStream = otherStream;
this.xml = xml;
this.primary = xml.createDocument ();
this.primaryRoot = this.primary.createElementNS ( "http://linux.duke.edu/metadata/common", "metadata" );
this.primaryRoot.setAttribute ( "xmlns:rpm", "http://linux.duke.edu/metadata/rpm" );
this.primary.appendChild ( this.primaryRoot );
this.filelists = xml.createDocument ();
this.filelistsRoot = this.filelists.createElementNS ( "http://linux.duke.edu/metadata/filelists", "filelists" );
this.filelists.appendChild ( this.filelistsRoot );
this.other = xml.createDocument ();
this.otherRoot = this.other.createElementNS ( "http://linux.duke.edu/metadata/other", "otherdata" );
this.other.appendChild ( this.otherRoot );
}
@Override
public void addPackage ( final FileInformation fileInformation, final RpmInformation info, final Map<HashAlgorithm, String> checksums, final HashAlgorithm idType )
{
Objects.requireNonNull ( fileInformation );
Objects.requireNonNull ( info );
Objects.requireNonNull ( checksums );
Objects.requireNonNull ( idType );
final String id = checksums.get ( idType );
if ( id == null || id.isEmpty () )
{
throw new IllegalArgumentException ( String.format ( "Checksums map did not contain a value for the ID type: %s", idType ) );
}
this.count++;
// insert to primary
insertToPrimary ( fileInformation, info, checksums, idType );
// insert to "filelists"
{
final Element pkg = createPackage ( this.filelistsRoot, id, info );
appendFiles ( info, pkg, null, null );
}
// insert to "other"
{
final Element pkg = createPackage ( this.otherRoot, id, info );
for ( final Changelog log : info.getChangelog () )
{
final Element cl = addElement ( pkg, "changelog", log.getText () );
cl.setAttribute ( "author", log.getAuthor () );
cl.setAttribute ( "date", "" + log.getTimestamp () );
}
}
}
private void appendFiles ( final RpmInformation info, final Element pkg, final Predicate<String> fileFilter, final Predicate<String> dirFilter )
{
for ( final String file : new TreeSet<> ( info.getFiles () ) )
{
if ( fileFilter == null || fileFilter.test ( file ) )
{
addElement ( pkg, "file", file );
}
}
for ( final String dir : new TreeSet<> ( info.getDirectories () ) )
{
if ( dirFilter == null || dirFilter.test ( dir ) )
{
final Element ele = addElement ( pkg, "file", dir );
ele.setAttribute ( "type", "dir" );
}
}
}
private void insertToPrimary ( final FileInformation fileInformation, final RpmInformation info, final Map<HashAlgorithm, String> checksums, final HashAlgorithm idType )
{
final Element pkg = addElement ( this.primaryRoot, "package" );
pkg.setAttribute ( "type", "rpm" );
addElement ( pkg, "name", info.getName () );
addElement ( pkg, "arch", info.getArchitecture () );
addVersion ( pkg, info.getVersion () );
for ( final Map.Entry<HashAlgorithm, String> entry : checksums.entrySet () )
{
final Element checksum = addElement ( pkg, "checksum", entry.getValue () );
checksum.setAttribute ( "type", entry.getKey ().getId () );
if ( entry.getKey () == idType )
{
checksum.setAttribute ( "pkgid", "YES" );
}
}
addElement ( pkg, "summary", info.getSummary () );
addElement ( pkg, "description", info.getDescription () );
addElement ( pkg, "packager", info.getPackager () );
addElement ( pkg, "url", info.getUrl () );
// time
final Element time = addElement ( pkg, "time" );
time.setAttribute ( "file", "" + fileInformation.getTimestamp ().getEpochSecond () );
if ( info.getBuildTimestamp () != null )
{
time.setAttribute ( "build", "" + info.getBuildTimestamp () );
}
// size
final Element size = addElement ( pkg, "size" );
size.setAttribute ( "package", "" + fileInformation.getSize () );
if ( info.getInstalledSize () != null )
{
size.setAttribute ( "installed", "" + info.getInstalledSize () );
}
if ( info.getArchiveSize () != null )
{
size.setAttribute ( "archive", "" + info.getArchiveSize () );
}
// location
final Element location = addElement ( pkg, "location" );
location.setAttribute ( "href", fileInformation.getLocation () );
// add format section
final Element fmt = addElement ( pkg, "format" );
addOptionalElement ( fmt, "rpm:license", info.getLicense () );
addOptionalElement ( fmt, "rpm:vendor", info.getVendor () );
addOptionalElement ( fmt, "rpm:group", info.getGroup () );
addOptionalElement ( fmt, "rpm:buildhost", info.getBuildHost () );
addOptionalElement ( fmt, "rpm:sourcerpm", info.getSourcePackage () );
// add header range
final Element rng = addElement ( fmt, "rpm:header-range" );
rng.setAttribute ( "start", "" + info.getHeaderStart () );
rng.setAttribute ( "end", "" + info.getHeaderEnd () );
addDependencies ( fmt, "rpm:provides", info.getProvides () );
addDependencies ( fmt, "rpm:requires", info.getRequires () );
addDependencies ( fmt, "rpm:conflicts", info.getConflicts () );
addDependencies ( fmt, "rpm:obsoletes", info.getObsoletes () );
// add primary files
appendFiles ( info, pkg, file -> matches ( file, RepositoryCreator.this.primaryFiles ), dir -> matches ( dir, RepositoryCreator.this.primaryDirs ) );
}
private void addDependencies ( final Element fmt, final String elementName, final List<Dependency> deps )
{
final Element ele = addElement ( fmt, elementName );
for ( final Dependency dep : deps )
{
final EnumSet<RpmDependencyFlags> flags = RpmDependencyFlags.parse ( dep.getFlags () );
if ( flags.contains ( RpmDependencyFlags.RPMLIB ) )
{
continue;
}
final Element entry = addElement ( ele, "rpm:entry" );
entry.setAttribute ( "name", dep.getName () );
if ( dep.getVersion () != null )
{
final RpmVersion version = RpmVersion.valueOf ( dep.getVersion () );
entry.setAttribute ( "epoch", "" + version.getEpoch ().orElse ( 0 ) );
entry.setAttribute ( "ver", version.getVersion () );
if ( version.getRelease ().isPresent () )
{
entry.setAttribute ( "rel", version.getRelease ().get () );
}
}
final boolean eq = flags.contains ( RpmDependencyFlags.EQUAL );
if ( flags.contains ( RpmDependencyFlags.GREATER ) )
{
entry.setAttribute ( "flags", eq ? "GE" : "GT" );
}
else if ( flags.contains ( RpmDependencyFlags.LESS ) )
{
entry.setAttribute ( "flags", eq ? "LE" : "LT" );
}
else if ( eq )
{
entry.setAttribute ( "flags", "EQ" );
}
final boolean pre = flags.contains ( RpmDependencyFlags.PREREQ ) || flags.contains ( RpmDependencyFlags.SCRIPT_PRE ) || flags.contains ( RpmDependencyFlags.SCRIPT_POST );
if ( pre )
{
entry.setAttribute ( "pre", "1" );
}
}
}
private Element createPackage ( final Element root, final String id, final RpmInformation info )
{
final Element pkg = addElement ( root, "package" );
pkg.setAttribute ( "pkgid", id );
pkg.setAttribute ( "name", info.getName () );
pkg.setAttribute ( "arch", info.getArchitecture () );
addVersion ( pkg, info.getVersion () );
return pkg;
}
private Element addVersion ( final Element pkg, final RpmInformation.Version version )
{
if ( version == null )
{
return null;
}
final Element ver = addElement ( pkg, "version" );
if ( version.getEpoch () == null || version.getEpoch ().isEmpty () )
{
ver.setAttribute ( "epoch", "0" );
}
else
{
ver.setAttribute ( "epoch", version.getEpoch () );
}
ver.setAttribute ( "ver", version.getVersion () );
ver.setAttribute ( "rel", version.getRelease () );
return ver;
}
public void close () throws IOException
{
this.primaryRoot.setAttribute ( "packages", Long.toString ( this.count ) );
this.filelistsRoot.setAttribute ( "packages", Long.toString ( this.count ) );
this.otherRoot.setAttribute ( "packages", Long.toString ( this.count ) );
try
{
this.xml.write ( this.primary, this.primaryStream );
this.xml.write ( this.filelists, this.filelistsStream );
this.xml.write ( this.other, this.otherStream );
}
catch ( final IOException e )
{
throw e;
}
catch ( final Exception e )
{
throw new IOException ( e );
}
}
}
public static class Builder
{
private SpoolOutTarget target;
private XmlContext xmlContext;
private Function<OutputStream, OutputStream> signingStreamCreator;
public Builder ()
{
}
public Builder setTarget ( final SpoolOutTarget target )
{
this.target = target;
return this;
}
public Builder setXmlContext ( final XmlContext xmlContext )
{
this.xmlContext = xmlContext;
return this;
}
public Builder setSigning ( final Function<OutputStream, OutputStream> signingStreamCreator )
{
this.signingStreamCreator = signingStreamCreator;
return this;
}
public Builder setSigning ( final PGPPrivateKey privateKey )
{
return setSigning ( privateKey, HashAlgorithmTags.SHA1 );
}
public Builder setSigning ( final PGPPrivateKey privateKey, final int digestAlgorithm )
{
if ( privateKey != null )
{
this.signingStreamCreator = output -> new SigningStream ( output, privateKey, digestAlgorithm, false );
}
else
{
this.signingStreamCreator = null;
}
return this;
}
public RepositoryCreator build ()
{
return new RepositoryCreator ( this.target, this.xmlContext == null ? new DefaultXmlContext () : this.xmlContext, this.signingStreamCreator );
}
}
private RepositoryCreator ( final SpoolOutTarget target, final XmlContext xml, final Function<OutputStream, OutputStream> signingStreamCreator )
{
Objects.requireNonNull ( target );
Objects.requireNonNull ( xml );
// xml
this.xml = xml;
// filters
final String dirFilter = System.getProperty ( "drone.rpm.yum.primaryDirs", "bin/,^/etc/" );
final String fileFilter = System.getProperty ( "drone.rpm.yum.primaryFiles", dirFilter );
this.primaryFiles = Arrays.stream ( fileFilter.split ( "," ) ).map ( re -> Pattern.compile ( re ) ).collect ( Collectors.toList () );
this.primaryDirs = Arrays.stream ( dirFilter.split ( "," ) ).map ( re -> Pattern.compile ( re ) ).collect ( Collectors.toList () );
this.primaryUniqueName = UUID.randomUUID ().toString ().replace ( "-", "" );
this.filelistsUniqueName = UUID.randomUUID ().toString ().replace ( "-", "" );
this.otherUniqueName = UUID.randomUUID ().toString ().replace ( "-", "" );
// primary
this.primaryStreamBuilder = new OutputSpooler ( target );
this.primaryStreamBuilder.addDigest ( MD_NAME );
this.primaryStreamBuilder.addOutput ( String.format ( "repodata/%s-primary.xml", this.primaryUniqueName ), "application/xml" );
this.primaryStreamBuilder.addOutput ( String.format ( "repodata/%s-primary.xml.gz", this.primaryUniqueName ), "application/x-gzip", output -> new GZIPOutputStream ( output ) );
// filelists
this.filelistsStreamBuilder = new OutputSpooler ( target );
this.filelistsStreamBuilder.addDigest ( MD_NAME );
this.filelistsStreamBuilder.addOutput ( String.format ( "repodata/%s-filelists.xml", this.filelistsUniqueName ), "application/xml" );
this.filelistsStreamBuilder.addOutput ( String.format ( "repodata/%s-filelists.xml.gz", this.filelistsUniqueName ), "application/x-gzip", output -> new GZIPOutputStream ( output ) );
// other
this.otherStreamBuilder = new OutputSpooler ( target );
this.otherStreamBuilder.addDigest ( MD_NAME );
this.otherStreamBuilder.addOutput ( String.format ( "repodata/%s-other.xml", this.otherUniqueName ), "application/xml" );
this.otherStreamBuilder.addOutput ( String.format ( "repodata/%s-other.xml.gz", this.otherUniqueName ), "application/x-gzip", output -> new GZIPOutputStream ( output ) );
// md
this.mdStreamBuilder = new OutputSpooler ( target );
this.mdStreamBuilder.addOutput ( "repodata/repomd.xml", "application/xml" );
if ( signingStreamCreator != null )
{
this.mdStreamBuilder.addOutput ( "repodata/repomd.xml.asc", "text/plain", signingStreamCreator::apply );
}
}
private boolean matches ( final String pathName, final List<Pattern> filterList )
{
for ( final Pattern p : filterList )
{
if ( p.matcher ( pathName ).find () )
{
return true;
}
}
return false;
}
public void process ( final IOConsumer<Context> consumer ) throws IOException
{
final long now = System.currentTimeMillis ();
this.primaryStreamBuilder.open ( primaryStream -> {
this.filelistsStreamBuilder.open ( filelistsStream -> {
this.otherStreamBuilder.open ( otherStream -> {
final ContextImpl ctx = makeContext ( primaryStream, filelistsStream, otherStream );
consumer.accept ( ctx );
ctx.close ();
} );
} );
} );
this.mdStreamBuilder.open ( stream -> {
writeRepoMd ( stream, now );
} );
}
private ContextImpl makeContext ( final OutputStream primaryStream, final OutputStream filelistsStream, final OutputStream otherStream )
{
return new ContextImpl ( primaryStream, filelistsStream, otherStream, this.xml );
}
private void writeRepoMd ( final OutputStream stream, final long now ) throws IOException
{
final Document doc = this.xml.createDocument ();
final Element root = doc.createElementNS ( "http://linux.duke.edu/metadata/repo", "repomd" );
doc.appendChild ( root );
root.setAttribute ( "revision", Long.toString ( now / 1000 ) );
addDataFile ( root, this.primaryStreamBuilder, this.primaryUniqueName, "primary", now );
addDataFile ( root, this.filelistsStreamBuilder, this.filelistsUniqueName, "filelists", now );
addDataFile ( root, this.otherStreamBuilder, this.otherUniqueName, "other", now );
try
{
this.xml.write ( doc, stream );
}
catch ( final Exception e )
{
throw new IOException ( e );
}
}
private void addDataFile ( final Element root, final OutputSpooler spooler, final String unique, final String baseName, final long now )
{
final String filename = "repodata/" + unique + "-" + baseName + ".xml";
final Element data = addElement ( root, "data" );
data.setAttribute ( "type", baseName );
final Element checksum = addElement ( data, "checksum", spooler.getChecksum ( filename + ".gz", MD_NAME ) );
checksum.setAttribute ( "type", MD_TAG );
final Element openChecksum = addElement ( data, "open-checksum", spooler.getChecksum ( filename, MD_NAME ) );
openChecksum.setAttribute ( "type", MD_TAG );
final Element location = addElement ( data, "location" );
location.setAttribute ( "href", filename + ".gz" );
addElement ( data, "timestamp", now / 1000 );
addElement ( data, "size", "" + spooler.getSize ( filename + ".gz" ) );
addElement ( data, "open-size", "" + spooler.getSize ( filename ) );
}
private static void addOptionalElement ( final Element parent, final String name, final Object value )
{
if ( value == null )
{
return;
}
addElement ( parent, name, value );
}
private static Element addElement ( final Element parent, final String name )
{
return addElement ( parent, name, null );
}
private static Element addElement ( final Element parent, final String name, final Object value )
{
final Document doc = parent.getOwnerDocument ();
final Element result = doc.createElement ( name );
parent.appendChild ( result );
if ( value != null )
{
result.appendChild ( doc.createTextNode ( value.toString () ) );
}
return result;
}
}
|
use new hash type
|
bundles/org.eclipse.packagedrone.utils.rpm/src/org/eclipse/packagedrone/utils/rpm/yum/RepositoryCreator.java
|
use new hash type
|
|
Java
|
epl-1.0
|
5b427d87abc5e8c8990eb4889b980ee0a976725a
| 0
|
ctron/kura,nicolatimeus/kura,ctron/kura,nicolatimeus/kura,nicolatimeus/kura,ctron/kura,nicolatimeus/kura,nicolatimeus/kura,nicolatimeus/kura,ctron/kura,ctron/kura,ctron/kura
|
/**
* Copyright (c) 2017, 2020 Eurotech and/or its affiliates and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eurotech
*/
package org.eclipse.kura.internal.driver.opcua;
import java.util.Arrays;
import org.eclipse.kura.type.DataType;
import org.eclipse.kura.type.TypedValue;
import org.eclipse.kura.type.TypedValues;
import org.eclipse.milo.opcua.stack.core.types.builtin.ByteString;
import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText;
import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;
import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UByte;
import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger;
import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.ULong;
import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UShort;
public final class DataTypeMapper {
private DataTypeMapper() {
}
private static Variant mapByteArray(final byte[] javaValue, final VariableType opcuaType) {
if (opcuaType == VariableType.BYTE_STRING) {
return new Variant(ByteString.of(javaValue));
} else if (opcuaType == VariableType.BYTE_ARRAY) {
final UByte[] array = new UByte[javaValue.length];
for (int i = 0; i < javaValue.length; i++) {
array[i] = UByte.valueOf(javaValue[i]);
}
return new Variant(array);
} else if (opcuaType == VariableType.SBYTE_ARRAY) {
final Byte[] array = new Byte[javaValue.length];
for (int i = 0; i < javaValue.length; i++) {
array[i] = javaValue[i];
}
return new Variant(array);
}
throw new IllegalArgumentException("Error while converting the retrieved value to the defined typed "
+ javaValue.getClass() + " " + opcuaType.name());
}
public static Variant map(final Object value, final VariableType targetType) {
if (targetType == VariableType.DEFINED_BY_JAVA_TYPE
|| value instanceof Boolean && targetType == VariableType.BOOLEAN) {
return new Variant(value);
}
if (value instanceof byte[]) {
return mapByteArray((byte[]) value, targetType);
}
if (value instanceof Number) {
final Number numberValue = (Number) value;
if (targetType == VariableType.SBYTE) {
return new Variant(numberValue.byteValue());
} else if (targetType == VariableType.INT16) {
return new Variant(numberValue.shortValue());
} else if (targetType == VariableType.INT32) {
return new Variant(numberValue.intValue());
} else if (targetType == VariableType.INT64) {
return new Variant(numberValue.longValue());
} else if (targetType == VariableType.BYTE) {
return new Variant(UByte.valueOf(numberValue.longValue()));
} else if (targetType == VariableType.UINT16) {
return new Variant(UShort.valueOf(numberValue.intValue()));
} else if (targetType == VariableType.UINT32) {
return new Variant(UInteger.valueOf(numberValue.longValue()));
} else if (targetType == VariableType.UINT64) {
return new Variant(ULong.valueOf(numberValue.longValue()));
} else if (targetType == VariableType.FLOAT) {
return new Variant(numberValue.floatValue());
} else if (targetType == VariableType.DOUBLE) {
return new Variant(numberValue.doubleValue());
} else if (targetType == VariableType.STRING) {
return new Variant(numberValue.toString());
}
}
if (value instanceof String) {
final String stringValue = (String) value;
if (targetType == VariableType.SBYTE) {
return new Variant(Byte.parseByte(stringValue));
} else if (targetType == VariableType.INT16) {
return new Variant(Short.parseShort(stringValue));
} else if (targetType == VariableType.INT32) {
return new Variant(Integer.parseInt(stringValue));
} else if (targetType == VariableType.INT64) {
return new Variant(Long.parseLong(stringValue));
} else if (targetType == VariableType.BYTE) {
return new Variant(UByte.valueOf(stringValue));
} else if (targetType == VariableType.UINT16) {
return new Variant(UShort.valueOf(stringValue));
} else if (targetType == VariableType.UINT32) {
return new Variant(UInteger.valueOf(stringValue));
} else if (targetType == VariableType.UINT64) {
return new Variant(ULong.valueOf(stringValue));
} else if (targetType == VariableType.FLOAT) {
return new Variant(Float.parseFloat(stringValue));
} else if (targetType == VariableType.DOUBLE) {
return new Variant(Double.parseDouble(stringValue));
} else if (targetType == VariableType.STRING) {
return new Variant(stringValue);
}
}
throw new IllegalArgumentException("Error while converting the retrieved value to the defined typed "
+ value.getClass() + " " + targetType.name());
}
private static byte[] toByteArray(Object objectValue) {
if (objectValue instanceof byte[]) {
return (byte[]) objectValue;
} else if (objectValue instanceof ByteString) {
return ((ByteString) objectValue).bytesOrEmpty();
} else if (objectValue instanceof Byte[]) {
final Byte[] value = (Byte[]) objectValue;
final byte[] result = new byte[value.length];
for (int i = 0; i < value.length; i++) {
result[i] = value[i];
}
return result;
} else if (objectValue instanceof UByte[]) {
final UByte[] value = (UByte[]) objectValue;
final byte[] result = new byte[value.length];
for (int i = 0; i < value.length; i++) {
result[i] = (byte) (value[i].intValue() & 0xff);
}
return result;
}
throw new IllegalArgumentException();
}
public static TypedValue<?> map(final Object value, final DataType targetType) {
switch (targetType) {
case LONG:
return TypedValues.newLongValue(Long.parseLong(value.toString()));
case FLOAT:
return TypedValues.newFloatValue(Float.parseFloat(value.toString()));
case DOUBLE:
return TypedValues.newDoubleValue(Double.parseDouble(value.toString()));
case INTEGER:
return TypedValues.newIntegerValue(Integer.parseInt(value.toString()));
case BOOLEAN:
return TypedValues.newBooleanValue(Boolean.parseBoolean(value.toString()));
case STRING:
if (value instanceof LocalizedText) {
final LocalizedText text = (LocalizedText) value;
return TypedValues.newStringValue(text.getText());
} else {
if (value.getClass().isArray()) {
return TypedValues.newStringValue(Arrays.deepToString((Object[]) value));
} else {
return TypedValues.newStringValue(value.toString());
}
}
case BYTE_ARRAY:
return TypedValues.newByteArrayValue(toByteArray(value));
default:
throw new IllegalArgumentException();
}
}
}
|
kura/org.eclipse.kura.driver.opcua.provider/src/main/java/org/eclipse/kura/internal/driver/opcua/DataTypeMapper.java
|
/**
* Copyright (c) 2017, 2018 Eurotech and/or its affiliates and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eurotech
*/
package org.eclipse.kura.internal.driver.opcua;
import java.util.Arrays;
import org.eclipse.kura.type.DataType;
import org.eclipse.kura.type.TypedValue;
import org.eclipse.kura.type.TypedValues;
import org.eclipse.milo.opcua.stack.core.types.builtin.ByteString;
import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText;
import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;
import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UByte;
import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger;
import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.ULong;
import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UShort;
public final class DataTypeMapper {
private DataTypeMapper() {
}
private static Variant mapByteArray(final byte[] javaValue, final VariableType opcuaType) {
if (opcuaType == VariableType.BYTE_STRING) {
return new Variant(ByteString.of(javaValue));
} else if (opcuaType == VariableType.BYTE_ARRAY) {
final UByte[] array = new UByte[javaValue.length];
for (int i = 0; i < javaValue.length; i++) {
array[i] = UByte.valueOf(javaValue[i]);
}
return new Variant(array);
} else if (opcuaType == VariableType.SBYTE_ARRAY) {
final Byte[] array = new Byte[javaValue.length];
for (int i = 0; i < javaValue.length; i++) {
array[i] = javaValue[i];
}
return new Variant(array);
}
throw new IllegalArgumentException("Error while converting the retrieved value to the defined typed "
+ javaValue.getClass() + " " + opcuaType.name());
}
public static Variant map(final Object value, final VariableType targetType) {
if (targetType == VariableType.DEFINED_BY_JAVA_TYPE
|| value instanceof Boolean && targetType == VariableType.BOOLEAN) {
return new Variant(value);
}
if (value instanceof byte[]) {
return mapByteArray((byte[]) value, targetType);
}
if (value instanceof Number) {
final Number numberValue = (Number) value;
if (targetType == VariableType.SBYTE) {
return new Variant(numberValue.byteValue());
} else if (targetType == VariableType.INT16) {
return new Variant(numberValue.shortValue());
} else if (targetType == VariableType.INT32) {
return new Variant(numberValue.intValue());
} else if (targetType == VariableType.INT64) {
return new Variant(numberValue.longValue());
} else if (targetType == VariableType.BYTE) {
return new Variant(UByte.valueOf(numberValue.longValue()));
} else if (targetType == VariableType.UINT16) {
return new Variant(UShort.valueOf(numberValue.intValue()));
} else if (targetType == VariableType.UINT32) {
return new Variant(UInteger.valueOf(numberValue.longValue()));
} else if (targetType == VariableType.UINT64) {
return new Variant(ULong.valueOf(numberValue.longValue()));
} else if (targetType == VariableType.FLOAT) {
return new Variant(numberValue.floatValue());
} else if (targetType == VariableType.DOUBLE) {
return new Variant(numberValue.doubleValue());
} else if (targetType == VariableType.STRING) {
return new Variant(numberValue.toString());
}
}
if (value instanceof String) {
final String stringValue = (String) value;
if (targetType == VariableType.SBYTE) {
return new Variant(Byte.parseByte(stringValue));
} else if (targetType == VariableType.INT16) {
return new Variant(Short.parseShort(stringValue));
} else if (targetType == VariableType.INT32) {
return new Variant(Integer.parseInt(stringValue));
} else if (targetType == VariableType.INT64) {
return new Variant(Long.parseLong(stringValue));
} else if (targetType == VariableType.BYTE) {
return new Variant(UByte.valueOf(stringValue));
} else if (targetType == VariableType.UINT16) {
return new Variant(UShort.valueOf(stringValue));
} else if (targetType == VariableType.UINT32) {
return new Variant(UInteger.valueOf(stringValue));
} else if (targetType == VariableType.UINT64) {
return new Variant(ULong.valueOf(stringValue));
} else if (targetType == VariableType.FLOAT) {
return new Variant(Float.parseFloat(stringValue));
} else if (targetType == VariableType.DOUBLE) {
return new Variant(Double.parseDouble(stringValue));
} else if (targetType == VariableType.STRING) {
return new Variant(stringValue);
}
}
throw new IllegalArgumentException("Error while converting the retrieved value to the defined typed "
+ value.getClass() + " " + targetType.name());
}
private static byte[] toByteArray(Object objectValue) {
if (objectValue instanceof byte[]) {
return (byte[]) objectValue;
} else if (objectValue instanceof ByteString) {
return ((ByteString) objectValue).bytesOrEmpty();
} else if (objectValue instanceof Byte[]) {
final Byte[] value = (Byte[]) objectValue;
final byte[] result = new byte[value.length];
for (int i = 0; i < value.length; i++) {
result[i] = value[i];
}
return result;
} else if (objectValue instanceof UByte[]) {
final UByte[] value = (UByte[]) objectValue;
final byte[] result = new byte[value.length];
for (int i = 0; i < value.length; i++) {
result[i] = (byte) (value[i].intValue() & 0xff);
}
return result;
}
throw new IllegalArgumentException();
}
public static TypedValue<?> map(final Object value, final DataType targetType) {
switch (targetType) {
case LONG:
return TypedValues.newLongValue(Long.parseLong(value.toString()));
case FLOAT:
return TypedValues.newFloatValue(Float.parseFloat(value.toString()));
case DOUBLE:
return TypedValues.newDoubleValue(Double.parseDouble(value.toString()));
case INTEGER:
return TypedValues.newIntegerValue(Integer.parseInt(value.toString()));
case BOOLEAN:
return TypedValues.newBooleanValue(Boolean.parseBoolean(value.toString()));
case STRING:
if (value instanceof LocalizedText) {
final LocalizedText text = (LocalizedText) value;
return TypedValues.newStringValue(text.getText());
} else {
if (value.getClass().isArray()) {
return TypedValues.newStringValue(Arrays.deepToString((Object[]) value));
} else {
return TypedValues.newStringValue(value.toString());
}
}
case BYTE_ARRAY:
return TypedValues.newByteArrayValue(toByteArray(value));
default:
throw new IllegalArgumentException();
}
}
}
|
Updated copyright year
Signed-off-by: alebianchin <da5f0dd3f5f3ad825b16559c928b1c0d2dd3e8ba@gmail.com>
|
kura/org.eclipse.kura.driver.opcua.provider/src/main/java/org/eclipse/kura/internal/driver/opcua/DataTypeMapper.java
|
Updated copyright year
|
|
Java
|
agpl-3.0
|
d4e04e092f1c576de9e85aa5882e21ea711a983b
| 0
|
PeterWithers/temp-to-delete1,PeterWithers/temp-to-delete1,KinshipSoftware/KinOathKinshipArchiver,KinshipSoftware/KinOathKinshipArchiver
|
package nl.mpi.kinnate.svg;
import nl.mpi.kinnate.ui.GraphPanelContextMenu;
import nl.mpi.kinnate.ui.KinTypeEgoSelectionTestPanel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import javax.swing.JPanel;
import nl.mpi.arbil.GuiHelper;
import nl.mpi.arbil.ImdiTableModel;
import nl.mpi.arbil.clarin.CmdiComponentBuilder;
import nl.mpi.kinnate.entityindexer.IndexerParameters;
import nl.mpi.kinnate.SavePanel;
import nl.mpi.kinnate.kintypestrings.KinTerms;
import org.apache.batik.bridge.UpdateManager;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.JSVGScrollPane;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.svg.SVGDocument;
import org.w3c.dom.svg.SVGLocatable;
import org.w3c.dom.svg.SVGRect;
/**
* Document : GraphPanel
* Created on : Aug 16, 2010, 5:31:33 PM
* Author : Peter Withers
*/
public class GraphPanel extends JPanel implements SavePanel {
private JSVGScrollPane jSVGScrollPane;
protected JSVGCanvas svgCanvas;
private SVGDocument doc;
private KinTerms kinTerms;
protected ImdiTableModel imdiTableModel;
private GraphData graphData;
private boolean requiresSave = false;
private File svgFile = null;
private GraphPanelSize graphPanelSize;
protected ArrayList<String> selectedGroupElement;
private String svgNameSpace = SVGDOMImplementation.SVG_NAMESPACE_URI;
private DataStoreSvg dataStoreSvg;
public GraphPanel(KinTypeEgoSelectionTestPanel egoSelectionPanel) {
dataStoreSvg = new DataStoreSvg();
selectedGroupElement = new ArrayList<String>();
graphPanelSize = new GraphPanelSize();
kinTerms = new KinTerms();
this.setLayout(new BorderLayout());
svgCanvas = new JSVGCanvas();
// svgCanvas.setMySize(new Dimension(600, 400));
svgCanvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
// drawNodes();
svgCanvas.setEnableImageZoomInteractor(false);
svgCanvas.setEnablePanInteractor(false);
svgCanvas.setEnableRotateInteractor(false);
svgCanvas.setEnableZoomInteractor(false);
svgCanvas.addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
AffineTransform at = new AffineTransform();
// System.out.println("R: " + e.getWheelRotation());
// System.out.println("A: " + e.getScrollAmount());
// System.out.println("U: " + e.getUnitsToScroll());
at.scale(1 + e.getUnitsToScroll() / 10.0, 1 + e.getUnitsToScroll() / 10.0);
// at.translate(e.getX()/10.0, e.getY()/10.0);
// System.out.println("x: " + e.getX());
// System.out.println("y: " + e.getY());
at.concatenate(svgCanvas.getRenderingTransform());
svgCanvas.setRenderingTransform(at);
}
});
// svgCanvas.setEnableResetTransformInteractor(true);
// svgCanvas.setDoubleBufferedRendering(true); // todo: look into reducing the noticable aliasing on the canvas
MouseListenerSvg mouseListenerSvg = new MouseListenerSvg(this);
svgCanvas.addMouseListener(mouseListenerSvg);
svgCanvas.addMouseMotionListener(mouseListenerSvg);
jSVGScrollPane = new JSVGScrollPane(svgCanvas);
this.add(BorderLayout.CENTER, jSVGScrollPane);
svgCanvas.setComponentPopupMenu(new GraphPanelContextMenu(egoSelectionPanel, this, graphPanelSize));
}
public void setImdiTableModel(ImdiTableModel imdiTableModelLocal) {
imdiTableModel = imdiTableModelLocal;
}
public void readSvg(File svgFilePath) {
svgFile = svgFilePath;
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser);
try {
doc = (SVGDocument) documentFactory.createDocument(svgFilePath.toURI().toString());
svgCanvas.setDocument(doc);
requiresSave = false;
} catch (IOException ioe) {
GuiHelper.linorgBugCatcher.logError(ioe);
}
// svgCanvas.setURI(svgFilePath.toURI().toString());
dataStoreSvg.loadDataFromSvg(doc);
}
private void saveSvg(File svgFilePath) {
svgFile = svgFilePath;
new CmdiComponentBuilder().savePrettyFormatting(doc, svgFilePath);
requiresSave = false;
}
private void printNodeNames(Node nodeElement) {
System.out.println(nodeElement.getLocalName());
System.out.println(nodeElement.getNamespaceURI());
Node childNode = nodeElement.getFirstChild();
while (childNode != null) {
printNodeNames(childNode);
childNode = childNode.getNextSibling();
}
}
public String[] getKinTypeStrigs() {
return dataStoreSvg.kinTypeStrings;
}
public void setKinTypeStrigs(String[] kinTypeStringArray) {
// strip out any white space, blank lines and remove duplicates
HashSet<String> kinTypeStringSet = new HashSet<String>();
for (String kinTypeString : kinTypeStringArray) {
if (kinTypeString != null && kinTypeString.trim().length() > 0) {
kinTypeStringSet.add(kinTypeString.trim());
}
}
dataStoreSvg.kinTypeStrings = kinTypeStringSet.toArray(new String[]{});
}
public IndexerParameters getIndexParameters() {
return dataStoreSvg.indexParameters;
}
public KinTerms getkinTerms() {
return kinTerms;
}
public URI[] getEgoList() {
return dataStoreSvg.egoSet.toArray(new URI[]{});
}
public void setEgoList(URI[] egoListArray) {
dataStoreSvg.egoSet = new HashSet<URI>(Arrays.asList(egoListArray));
}
public String[] getSelectedPaths() {
return selectedGroupElement.toArray(new String[]{});
}
public void resetZoom() {
AffineTransform at = new AffineTransform();
at.scale(1, 1);
at.setToTranslation(1, 1);
svgCanvas.setRenderingTransform(at);
}
public void drawNodes() {
drawNodes(graphData);
}
protected void updateDragNode(final int updateDragNodeX, final int updateDragNodeY) {
UpdateManager updateManager = svgCanvas.getUpdateManager();
updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() {
public void run() {
System.out.println("updateDragNodeX: " + updateDragNodeX);
System.out.println("updateDragNodeY: " + updateDragNodeY);
if (doc != null) {
Element svgRoot = doc.getDocumentElement();
for (Node currentChild = svgRoot.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) {
if ("g".equals(currentChild.getLocalName())) {
Node idAttrubite = currentChild.getAttributes().getNamedItem("id");
if (idAttrubite != null) {
String entityPath = idAttrubite.getTextContent();
if (selectedGroupElement.contains(entityPath)) {
SVGRect bbox = ((SVGLocatable) currentChild).getBBox();
// ((SVGLocatable) currentDraggedElement).g
((Element) currentChild).setAttribute("transform", "translate(" + String.valueOf(updateDragNodeX * svgCanvas.getRenderingTransform().getScaleX() - bbox.getX()) + ", " + String.valueOf(updateDragNodeY - bbox.getY()) + ")");
// updateDragNodeElement.setAttribute("x", String.valueOf(updateDragNodeX));
// updateDragNodeElement.setAttribute("y", String.valueOf(updateDragNodeY));
// SVGRect bbox = ((SVGLocatable) currentDraggedElement).getBBox();
// System.out.println("bbox X: " + bbox.getX());
// System.out.println("bbox Y: " + bbox.getY());
// System.out.println("bbox W: " + bbox.getWidth());
// System.out.println("bbox H: " + bbox.getHeight());
// todo: look into transform issues when dragging ellements eg when the canvas is scaled or panned
// SVGLocatable.getTransformToElement()
// SVGPoint.matrixTransform()
}
}
}
}
}
svgCanvas.revalidate();
}
});
}
protected void addHighlightToGroup() {
UpdateManager updateManager = svgCanvas.getUpdateManager();
updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() {
public void run() {
if (doc != null) {
Element svgRoot = doc.getDocumentElement();
for (Node currentChild = svgRoot.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) {
if ("g".equals(currentChild.getLocalName())) {
Node idAttrubite = currentChild.getAttributes().getNamedItem("id");
if (idAttrubite != null) {
String entityPath = idAttrubite.getTextContent();
System.out.println("group id (entityPath): " + entityPath);
Node existingHighlight = null;
// find any existing highlight
for (Node subGoupNode = currentChild.getFirstChild(); subGoupNode != null; subGoupNode = subGoupNode.getNextSibling()) {
if ("rect".equals(subGoupNode.getLocalName())) {
Node subGroupIdAttrubite = subGoupNode.getAttributes().getNamedItem("id");
if (subGroupIdAttrubite != null) {
if ("highlight".equals(subGroupIdAttrubite.getTextContent())) {
existingHighlight = subGoupNode;
}
}
}
}
if (!selectedGroupElement.contains(entityPath)) {
// remove all old highlights
if (existingHighlight != null) {
currentChild.removeChild(existingHighlight);
}
// add the current highlights
} else {
if (existingHighlight == null) {
// svgCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
SVGRect bbox = ((SVGLocatable) currentChild).getBBox();
// System.out.println("bbox X: " + bbox.getX());
// System.out.println("bbox Y: " + bbox.getY());
// System.out.println("bbox W: " + bbox.getWidth());
// System.out.println("bbox H: " + bbox.getHeight());
Element symbolNode = doc.createElementNS(svgNameSpace, "rect");
int paddingDistance = 20;
symbolNode.setAttribute("id", "highlight");
symbolNode.setAttribute("x", Float.toString(bbox.getX() - paddingDistance));
symbolNode.setAttribute("y", Float.toString(bbox.getY() - paddingDistance));
symbolNode.setAttribute("width", Float.toString(bbox.getWidth() + paddingDistance * 2));
symbolNode.setAttribute("height", Float.toString(bbox.getHeight() + paddingDistance * 2));
symbolNode.setAttribute("fill", "none");
symbolNode.setAttribute("stroke-width", "1");
symbolNode.setAttribute("stroke", "blue");
symbolNode.setAttribute("stroke-dasharray", "3");
symbolNode.setAttribute("stroke-dashoffset", "0");
// symbolNode.setAttribute("id", "Highlight");
// symbolNode.setAttribute("id", "Highlight");
// symbolNode.setAttribute("id", "Highlight");
// symbolNode.setAttribute("style", ":none;fill-opacity:1;fill-rule:nonzero;stroke:#6674ff;stroke-opacity:1;stroke-width:1;stroke-miterlimit:4;"
// + "stroke-dasharray:1, 1;stroke-dashoffset:0");
currentChild.appendChild(symbolNode);
}
}
}
}
}
}
}
});
}
private Element createEntitySymbol(GraphDataNode currentNode, int hSpacing, int vSpacing, int symbolSize) {
Element groupNode = doc.createElementNS(svgNameSpace, "g");
groupNode.setAttribute("id", currentNode.getEntityPath());
// counterTest++;
Element symbolNode;
String symbolType = currentNode.getSymbolType();
if (symbolType == null) {
symbolType = "cross";
}
symbolNode = doc.createElementNS(svgNameSpace, "use");
symbolNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + symbolType); // the xlink: of "xlink:href" is required for some svg viewers to render correctly
groupNode.setAttribute("transform", "translate(" + Integer.toString(currentNode.xPos * hSpacing + hSpacing - symbolSize / 2) + ", " + Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2) + ")");
if (currentNode.isEgo) {
symbolNode.setAttribute("fill", "black");
} else {
symbolNode.setAttribute("fill", "white");
}
symbolNode.setAttribute("stroke", "black");
symbolNode.setAttribute("stroke-width", "2");
groupNode.appendChild(symbolNode);
////////////////////////////// tspan method appears to fail in batik rendering process unless saved and reloaded ////////////////////////////////////////////////
// Element labelText = doc.createElementNS(svgNS, "text");
//// labelText.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing + symbolSize / 2));
//// labelText.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2));
// labelText.setAttribute("fill", "black");
// labelText.setAttribute("fill-opacity", "1");
// labelText.setAttribute("stroke-width", "0");
// labelText.setAttribute("font-size", "14px");
//// labelText.setAttribute("text-anchor", "end");
//// labelText.setAttribute("style", "font-size:14px;text-anchor:end;fill:black;fill-opacity:1");
// //labelText.setNodeValue(currentChild.toString());
//
// //String textWithUni = "\u0041";
// int textSpanCounter = 0;
// int lineSpacing = 10;
// for (String currentTextLable : currentNode.getLabel()) {
// Text textNode = doc.createTextNode(currentTextLable);
// Element tspanElement = doc.createElement("tspan");
// tspanElement.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing + symbolSize / 2));
// tspanElement.setAttribute("y", Integer.toString((currentNode.yPos * vSpacing + vSpacing - symbolSize / 2) + textSpanCounter));
//// tspanElement.setAttribute("y", Integer.toString(textSpanCounter * lineSpacing));
// tspanElement.appendChild(textNode);
// labelText.appendChild(tspanElement);
// textSpanCounter += lineSpacing;
// }
// groupNode.appendChild(labelText);
////////////////////////////// end tspan method appears to fail in batik rendering process ////////////////////////////////////////////////
////////////////////////////// alternate method ////////////////////////////////////////////////
// todo: this method has the draw back that the text is not selectable as a block
int textSpanCounter = 0;
int lineSpacing = 15;
for (String currentTextLable : currentNode.getLabel()) {
Element labelText = doc.createElementNS(svgNameSpace, "text");
labelText.setAttribute("x", Double.toString(symbolSize * 1.5));
labelText.setAttribute("y", Integer.toString(textSpanCounter));
labelText.setAttribute("fill", "black");
labelText.setAttribute("stroke-width", "0");
labelText.setAttribute("font-size", "14");
Text textNode = doc.createTextNode(currentTextLable);
labelText.appendChild(textNode);
textSpanCounter += lineSpacing;
groupNode.appendChild(labelText);
}
////////////////////////////// end alternate method ////////////////////////////////////////////////
((EventTarget) groupNode).addEventListener("mousedown", new MouseListenerSvg(this), false);
return groupNode;
}
public void drawNodes(GraphData graphDataLocal) {
requiresSave = true;
graphData = graphDataLocal;
DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
doc = (SVGDocument) impl.createDocument(svgNameSpace, "svg", null);
new EntitySvg().insertSymbols(doc, svgNameSpace);
// Document doc = impl.createDocument(svgNS, "svg", null);
// SVGDocument doc = svgCanvas.getSVGDocument();
// Get the root element (the 'svg' element).
Element svgRoot = doc.getDocumentElement();
// todo: set up a kinnate namespace so that the ego list and kin type strings can have more permanent storage places
// int maxTextLength = 0;
// for (GraphDataNode currentNode : graphData.getDataNodes()) {
// if (currentNode.getLabel()[0].length() > maxTextLength) {
// maxTextLength = currentNode.getLabel()[0].length();
// }
// }
int vSpacing = graphPanelSize.getVerticalSpacing(graphData.gridHeight);
// todo: find the real text size from batik
// todo: get the user selected canvas size and adjust the hSpacing and vSpacing to fit
// int hSpacing = maxTextLength * 10 + 100;
int hSpacing = graphPanelSize.getHorizontalSpacing(graphData.gridWidth);
int symbolSize = 15;
int strokeWidth = 2;
// int preferedWidth = graphData.gridWidth * hSpacing + hSpacing * 2;
// int preferedHeight = graphData.gridHeight * vSpacing + vSpacing * 2;
// Set the width and height attributes on the root 'svg' element.
svgRoot.setAttribute("width", Integer.toString(graphPanelSize.getWidth(graphData.gridWidth, hSpacing)));
svgRoot.setAttribute("height", Integer.toString(graphPanelSize.getHeight(graphData.gridHeight, vSpacing)));
this.setPreferredSize(new Dimension(graphPanelSize.getHeight(graphData.gridHeight, vSpacing), graphPanelSize.getWidth(graphData.gridWidth, hSpacing)));
// store the selected kin type strings and other data in the dom
dataStoreSvg.storeAllData(doc);
svgCanvas.setSVGDocument(doc);
// svgCanvas.setDocument(doc);
// int counterTest = 0;
// add the relation symbols in a group below the relation lines
Element relationGroupNode = doc.createElementNS(svgNameSpace, "g");
relationGroupNode.setAttribute("id", "RelationGroup");
for (GraphDataNode currentNode : graphData.getDataNodes()) {
// set up the mouse listners on the group node
// ((EventTarget) groupNode).addEventListener("mouseover", new EventListener() {
//
// public void handleEvent(Event evt) {
// System.out.println("OnMouseOverCircleAction: " + evt.getCurrentTarget());
// if (currentDraggedElement == null) {
// ((Element) evt.getCurrentTarget()).setAttribute("fill", "green");
// }
// }
// }, false);
// ((EventTarget) groupNode).addEventListener("mouseout", new EventListener() {
//
// public void handleEvent(Event evt) {
// System.out.println("mouseout: " + evt.getCurrentTarget());
// if (currentDraggedElement == null) {
// ((Element) evt.getCurrentTarget()).setAttribute("fill", "none");
// }
// }
// }, false);
for (GraphDataNode.NodeRelation graphLinkNode : currentNode.getNodeRelations()) {
if (graphLinkNode.sourceNode.equals(currentNode)) {
Element groupNode = doc.createElementNS(svgNameSpace, "g");
Element defsNode = doc.createElementNS(svgNameSpace, "defs");
String lineIdString = currentNode.getEntityPath() + "-" + graphLinkNode.linkedNode.getEntityPath();
// todo: groupNode.setAttribute("id", currentNode.getEntityPath()+ ";"+and the other end);
// set the line end points
int fromX = (currentNode.xPos * hSpacing + hSpacing);
int fromY = (currentNode.yPos * vSpacing + vSpacing);
int toX = (graphLinkNode.linkedNode.xPos * hSpacing + hSpacing);
int toY = (graphLinkNode.linkedNode.yPos * vSpacing + vSpacing);
// set the label position
int labelX = (fromX + toX) / 2;
int labelY = (fromY + toY) / 2;
switch (graphLinkNode.relationLineType) {
case horizontalCurve:
// this case uses the following case
case verticalCurve:
// todo: groupNode.setAttribute("id", );
// System.out.println("link: " + graphLinkNode.linkedNode.xPos + ":" + graphLinkNode.linkedNode.yPos);
//
//// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/>
// Element linkLine = doc.createElementNS(svgNS, "line");
// linkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
// linkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
//
// linkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing));
// linkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing));
// linkLine.setAttribute("stroke", "black");
// linkLine.setAttribute("stroke-width", "1");
// // Attach the rectangle to the root 'svg' element.
// svgRoot.appendChild(linkLine);
System.out.println("link: " + graphLinkNode.linkedNode.xPos + ":" + graphLinkNode.linkedNode.yPos);
// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/>
Element linkLine = doc.createElementNS(svgNameSpace, "path");
int fromBezX;
int fromBezY;
int toBezX;
int toBezY;
if (graphLinkNode.relationLineType == GraphDataNode.RelationLineType.verticalCurve) {
fromBezX = fromX;
fromBezY = toY;
toBezX = toX;
toBezY = fromY;
if (currentNode.yPos == graphLinkNode.linkedNode.yPos) {
fromBezX = fromX;
fromBezY = toY - vSpacing / 2;
toBezX = toX;
toBezY = fromY - vSpacing / 2;
// set the label postion and lower it a bit
labelY = toBezY + vSpacing / 3;
;
}
} else {
fromBezX = toX;
fromBezY = fromY;
toBezX = fromX;
toBezY = toY;
if (currentNode.xPos == graphLinkNode.linkedNode.xPos) {
fromBezY = fromY;
fromBezX = toX - hSpacing / 2;
toBezY = toY;
toBezX = fromX - hSpacing / 2;
// set the label postion
labelX = toBezX;
}
}
linkLine.setAttribute("d", "M " + fromX + "," + fromY + " C " + fromBezX + "," + fromBezY + " " + toBezX + "," + toBezY + " " + toX + "," + toY);
// linkLine.setAttribute("x1", );
// linkLine.setAttribute("y1", );
//
// linkLine.setAttribute("x2", );
linkLine.setAttribute("fill", "none");
linkLine.setAttribute("stroke", "blue");
linkLine.setAttribute("stroke-width", Integer.toString(strokeWidth));
linkLine.setAttribute("id", lineIdString);
defsNode.appendChild(linkLine);
break;
case square:
// Element squareLinkLine = doc.createElement("line");
// squareLinkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
// squareLinkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
//
// squareLinkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing));
// squareLinkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing));
// squareLinkLine.setAttribute("stroke", "grey");
// squareLinkLine.setAttribute("stroke-width", Integer.toString(strokeWidth));
Element squareLinkLine = doc.createElementNS(svgNameSpace, "polyline");
int midY = (fromY + toY) / 2;
if (toY == fromY) {
// make sure that union lines go below the entities and sibling lines go above
if (graphLinkNode.relationType == GraphDataNode.RelationType.sibling) {
midY = toY - vSpacing / 2;
} else if (graphLinkNode.relationType == GraphDataNode.RelationType.union) {
midY = toY + vSpacing / 2;
}
}
squareLinkLine.setAttribute("points",
fromX + "," + fromY + " "
+ fromX + "," + midY + " "
+ toX + "," + midY + " "
+ toX + "," + toY);
squareLinkLine.setAttribute("fill", "none");
squareLinkLine.setAttribute("stroke", "grey");
squareLinkLine.setAttribute("stroke-width", Integer.toString(strokeWidth));
squareLinkLine.setAttribute("id", lineIdString);
defsNode.appendChild(squareLinkLine);
break;
}
groupNode.appendChild(defsNode);
Element useNode = doc.createElementNS(svgNameSpace, "use");
useNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly
// useNode.setAttribute("href", "#" + lineIdString);
groupNode.appendChild(useNode);
// add the relation label
if (graphLinkNode.labelString != null) {
Element labelText = doc.createElementNS(svgNameSpace, "text");
labelText.setAttribute("text-anchor", "middle");
// labelText.setAttribute("x", Integer.toString(labelX));
// labelText.setAttribute("y", Integer.toString(labelY));
labelText.setAttribute("fill", "blue");
labelText.setAttribute("stroke-width", "0");
labelText.setAttribute("font-size", "14");
// labelText.setAttribute("transform", "rotate(45)");
Element textPath = doc.createElementNS(svgNameSpace, "textPath");
textPath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly
textPath.setAttribute("startOffset", "50%");
// textPath.setAttribute("text-anchor", "middle");
Text textNode = doc.createTextNode(graphLinkNode.labelString);
textPath.appendChild(textNode);
labelText.appendChild(textPath);
groupNode.appendChild(labelText);
}
relationGroupNode.appendChild(groupNode);
}
}
}
svgRoot.appendChild(relationGroupNode);
// add the entity symbols in a group on top of the relation lines
Element entityGroupNode = doc.createElementNS(svgNameSpace, "g");
entityGroupNode.setAttribute("id", "EntityGroup");
for (GraphDataNode currentNode : graphData.getDataNodes()) {
entityGroupNode.appendChild(createEntitySymbol(currentNode, hSpacing, vSpacing, symbolSize));
}
svgRoot.appendChild(entityGroupNode);
//new CmdiComponentBuilder().savePrettyFormatting(doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/src/main/resources/output.svg"));
svgCanvas.revalidate();
// todo: populate this correctly with the available symbols
dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(new EntitySvg().listSymbolNames(doc));
}
public boolean hasSaveFileName() {
return svgFile != null;
}
public boolean requiresSave() {
return requiresSave;
}
public void saveToFile() {
saveSvg(svgFile);
}
public void saveToFile(File saveAsFile) {
saveSvg(saveAsFile);
}
public void updateGraph() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
src/main/java/nl/mpi/kinnate/svg/GraphPanel.java
|
package nl.mpi.kinnate.svg;
import nl.mpi.kinnate.ui.GraphPanelContextMenu;
import nl.mpi.kinnate.ui.KinTypeEgoSelectionTestPanel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import javax.swing.JPanel;
import nl.mpi.arbil.GuiHelper;
import nl.mpi.arbil.ImdiTableModel;
import nl.mpi.arbil.clarin.CmdiComponentBuilder;
import nl.mpi.kinnate.entityindexer.IndexerParameters;
import nl.mpi.kinnate.SavePanel;
import nl.mpi.kinnate.kintypestrings.KinTerms;
import org.apache.batik.bridge.UpdateManager;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.JSVGScrollPane;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.svg.SVGDocument;
import org.w3c.dom.svg.SVGLocatable;
import org.w3c.dom.svg.SVGRect;
/**
* Document : GraphPanel
* Created on : Aug 16, 2010, 5:31:33 PM
* Author : Peter Withers
*/
public class GraphPanel extends JPanel implements SavePanel {
private JSVGScrollPane jSVGScrollPane;
protected JSVGCanvas svgCanvas;
private SVGDocument doc;
private KinTerms kinTerms;
protected ImdiTableModel imdiTableModel;
private GraphData graphData;
private boolean requiresSave = false;
private File svgFile = null;
private GraphPanelSize graphPanelSize;
protected ArrayList<String> selectedGroupElement;
private String svgNameSpace = SVGDOMImplementation.SVG_NAMESPACE_URI;
private DataStoreSvg dataStoreSvg;
public GraphPanel(KinTypeEgoSelectionTestPanel egoSelectionPanel) {
dataStoreSvg = new DataStoreSvg();
selectedGroupElement = new ArrayList<String>();
graphPanelSize = new GraphPanelSize();
kinTerms = new KinTerms();
this.setLayout(new BorderLayout());
svgCanvas = new JSVGCanvas();
// svgCanvas.setMySize(new Dimension(600, 400));
svgCanvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
// drawNodes();
svgCanvas.setEnableImageZoomInteractor(false);
svgCanvas.setEnablePanInteractor(false);
svgCanvas.setEnableRotateInteractor(false);
svgCanvas.setEnableZoomInteractor(false);
svgCanvas.addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
AffineTransform at = new AffineTransform();
// System.out.println("R: " + e.getWheelRotation());
// System.out.println("A: " + e.getScrollAmount());
// System.out.println("U: " + e.getUnitsToScroll());
at.scale(1 + e.getUnitsToScroll() / 10.0, 1 + e.getUnitsToScroll() / 10.0);
// at.translate(e.getX()/10.0, e.getY()/10.0);
// System.out.println("x: " + e.getX());
// System.out.println("y: " + e.getY());
at.concatenate(svgCanvas.getRenderingTransform());
svgCanvas.setRenderingTransform(at);
}
});
// svgCanvas.setEnableResetTransformInteractor(true);
// svgCanvas.setDoubleBufferedRendering(true); // todo: look into reducing the noticable aliasing on the canvas
MouseListenerSvg mouseListenerSvg = new MouseListenerSvg(this);
svgCanvas.addMouseListener(mouseListenerSvg);
svgCanvas.addMouseMotionListener(mouseListenerSvg);
jSVGScrollPane = new JSVGScrollPane(svgCanvas);
this.add(BorderLayout.CENTER, jSVGScrollPane);
svgCanvas.setComponentPopupMenu(new GraphPanelContextMenu(egoSelectionPanel, this, graphPanelSize));
}
public void setImdiTableModel(ImdiTableModel imdiTableModelLocal) {
imdiTableModel = imdiTableModelLocal;
}
public void readSvg(File svgFilePath) {
svgFile = svgFilePath;
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser);
try {
doc = (SVGDocument) documentFactory.createDocument(svgFilePath.toURI().toString());
svgCanvas.setDocument(doc);
requiresSave = false;
} catch (IOException ioe) {
GuiHelper.linorgBugCatcher.logError(ioe);
}
// svgCanvas.setURI(svgFilePath.toURI().toString());
dataStoreSvg.loadDataFromSvg(doc);
}
private void saveSvg(File svgFilePath) {
svgFile = svgFilePath;
new CmdiComponentBuilder().savePrettyFormatting(doc, svgFilePath);
requiresSave = false;
}
private void printNodeNames(Node nodeElement) {
System.out.println(nodeElement.getLocalName());
System.out.println(nodeElement.getNamespaceURI());
Node childNode = nodeElement.getFirstChild();
while (childNode != null) {
printNodeNames(childNode);
childNode = childNode.getNextSibling();
}
}
public String[] getKinTypeStrigs() {
return dataStoreSvg.kinTypeStrings;
}
public void setKinTypeStrigs(String[] kinTypeStringArray) {
// strip out any white space, blank lines and remove duplicates
HashSet<String> kinTypeStringSet = new HashSet<String>();
for (String kinTypeString : kinTypeStringArray) {
if (kinTypeString != null && kinTypeString.trim().length() > 0) {
kinTypeStringSet.add(kinTypeString.trim());
}
}
dataStoreSvg.kinTypeStrings = kinTypeStringSet.toArray(new String[]{});
}
public IndexerParameters getIndexParameters() {
return dataStoreSvg.indexParameters;
}
public KinTerms getkinTerms() {
return kinTerms;
}
public URI[] getEgoList() {
return dataStoreSvg.egoSet.toArray(new URI[]{});
}
public void setEgoList(URI[] egoListArray) {
dataStoreSvg.egoSet = new HashSet<URI>(Arrays.asList(egoListArray));
}
public String[] getSelectedPaths() {
return selectedGroupElement.toArray(new String[]{});
}
public void resetZoom() {
AffineTransform at = new AffineTransform();
at.scale(1, 1);
at.setToTranslation(1, 1);
svgCanvas.setRenderingTransform(at);
}
public void drawNodes() {
drawNodes(graphData);
}
protected void updateDragNode(final int updateDragNodeX, final int updateDragNodeY) {
UpdateManager updateManager = svgCanvas.getUpdateManager();
updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() {
public void run() {
System.out.println("updateDragNodeX: " + updateDragNodeX);
System.out.println("updateDragNodeY: " + updateDragNodeY);
if (doc != null) {
Element svgRoot = doc.getDocumentElement();
for (Node currentChild = svgRoot.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) {
if ("g".equals(currentChild.getLocalName())) {
Node idAttrubite = currentChild.getAttributes().getNamedItem("id");
if (idAttrubite != null) {
String entityPath = idAttrubite.getTextContent();
if (selectedGroupElement.contains(entityPath)) {
SVGRect bbox = ((SVGLocatable) currentChild).getBBox();
// ((SVGLocatable) currentDraggedElement).g
((Element) currentChild).setAttribute("transform", "translate(" + String.valueOf(updateDragNodeX * svgCanvas.getRenderingTransform().getScaleX() - bbox.getX()) + ", " + String.valueOf(updateDragNodeY - bbox.getY()) + ")");
// updateDragNodeElement.setAttribute("x", String.valueOf(updateDragNodeX));
// updateDragNodeElement.setAttribute("y", String.valueOf(updateDragNodeY));
// SVGRect bbox = ((SVGLocatable) currentDraggedElement).getBBox();
// System.out.println("bbox X: " + bbox.getX());
// System.out.println("bbox Y: " + bbox.getY());
// System.out.println("bbox W: " + bbox.getWidth());
// System.out.println("bbox H: " + bbox.getHeight());
// todo: look into transform issues when dragging ellements eg when the canvas is scaled or panned
// SVGLocatable.getTransformToElement()
// SVGPoint.matrixTransform()
}
}
}
}
}
svgCanvas.revalidate();
}
});
}
protected void addHighlightToGroup() {
UpdateManager updateManager = svgCanvas.getUpdateManager();
updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() {
public void run() {
if (doc != null) {
Element svgRoot = doc.getDocumentElement();
for (Node currentChild = svgRoot.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) {
if ("g".equals(currentChild.getLocalName())) {
Node idAttrubite = currentChild.getAttributes().getNamedItem("id");
if (idAttrubite != null) {
String entityPath = idAttrubite.getTextContent();
System.out.println("group id (entityPath): " + entityPath);
Node existingHighlight = null;
// find any existing highlight
for (Node subGoupNode = currentChild.getFirstChild(); subGoupNode != null; subGoupNode = subGoupNode.getNextSibling()) {
if ("rect".equals(subGoupNode.getLocalName())) {
Node subGroupIdAttrubite = subGoupNode.getAttributes().getNamedItem("id");
if (subGroupIdAttrubite != null) {
if ("highlight".equals(subGroupIdAttrubite.getTextContent())) {
existingHighlight = subGoupNode;
}
}
}
}
if (!selectedGroupElement.contains(entityPath)) {
// remove all old highlights
if (existingHighlight != null) {
currentChild.removeChild(existingHighlight);
}
// add the current highlights
} else {
if (existingHighlight == null) {
// svgCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
SVGRect bbox = ((SVGLocatable) currentChild).getBBox();
// System.out.println("bbox X: " + bbox.getX());
// System.out.println("bbox Y: " + bbox.getY());
// System.out.println("bbox W: " + bbox.getWidth());
// System.out.println("bbox H: " + bbox.getHeight());
Element symbolNode = doc.createElementNS(svgNameSpace, "rect");
int paddingDistance = 20;
symbolNode.setAttribute("id", "highlight");
symbolNode.setAttribute("x", Float.toString(bbox.getX() - paddingDistance));
symbolNode.setAttribute("y", Float.toString(bbox.getY() - paddingDistance));
symbolNode.setAttribute("width", Float.toString(bbox.getWidth() + paddingDistance * 2));
symbolNode.setAttribute("height", Float.toString(bbox.getHeight() + paddingDistance * 2));
symbolNode.setAttribute("fill", "none");
symbolNode.setAttribute("stroke-width", "1");
symbolNode.setAttribute("stroke", "blue");
symbolNode.setAttribute("stroke-dasharray", "3");
symbolNode.setAttribute("stroke-dashoffset", "0");
// symbolNode.setAttribute("id", "Highlight");
// symbolNode.setAttribute("id", "Highlight");
// symbolNode.setAttribute("id", "Highlight");
// symbolNode.setAttribute("style", ":none;fill-opacity:1;fill-rule:nonzero;stroke:#6674ff;stroke-opacity:1;stroke-width:1;stroke-miterlimit:4;"
// + "stroke-dasharray:1, 1;stroke-dashoffset:0");
currentChild.appendChild(symbolNode);
}
}
}
}
}
}
}
});
}
private Element createEntitySymbol(GraphDataNode currentNode, int hSpacing, int vSpacing, int symbolSize) {
Element groupNode = doc.createElementNS(svgNameSpace, "g");
groupNode.setAttribute("id", currentNode.getEntityPath());
// counterTest++;
Element symbolNode;
String symbolType = currentNode.getSymbolType();
if (symbolType == null) {
symbolType = "cross";
}
symbolNode = doc.createElementNS(svgNameSpace, "use");
symbolNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + symbolType); // the xlink: of "xlink:href" is required for some svg viewers to render correctly
groupNode.setAttribute("transform", "translate(" + Integer.toString(currentNode.xPos * hSpacing + hSpacing - symbolSize / 2) + ", " + Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2) + ")");
if (currentNode.isEgo) {
symbolNode.setAttribute("fill", "black");
} else {
symbolNode.setAttribute("fill", "white");
}
symbolNode.setAttribute("stroke", "black");
symbolNode.setAttribute("stroke-width", "2");
groupNode.appendChild(symbolNode);
////////////////////////////// tspan method appears to fail in batik rendering process unless saved and reloaded ////////////////////////////////////////////////
// Element labelText = doc.createElementNS(svgNS, "text");
//// labelText.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing + symbolSize / 2));
//// labelText.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2));
// labelText.setAttribute("fill", "black");
// labelText.setAttribute("fill-opacity", "1");
// labelText.setAttribute("stroke-width", "0");
// labelText.setAttribute("font-size", "14px");
//// labelText.setAttribute("text-anchor", "end");
//// labelText.setAttribute("style", "font-size:14px;text-anchor:end;fill:black;fill-opacity:1");
// //labelText.setNodeValue(currentChild.toString());
//
// //String textWithUni = "\u0041";
// int textSpanCounter = 0;
// int lineSpacing = 10;
// for (String currentTextLable : currentNode.getLabel()) {
// Text textNode = doc.createTextNode(currentTextLable);
// Element tspanElement = doc.createElement("tspan");
// tspanElement.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing + symbolSize / 2));
// tspanElement.setAttribute("y", Integer.toString((currentNode.yPos * vSpacing + vSpacing - symbolSize / 2) + textSpanCounter));
//// tspanElement.setAttribute("y", Integer.toString(textSpanCounter * lineSpacing));
// tspanElement.appendChild(textNode);
// labelText.appendChild(tspanElement);
// textSpanCounter += lineSpacing;
// }
// groupNode.appendChild(labelText);
////////////////////////////// end tspan method appears to fail in batik rendering process ////////////////////////////////////////////////
////////////////////////////// alternate method ////////////////////////////////////////////////
// todo: this method has the draw back that the text is not selectable as a block
int textSpanCounter = 0;
int lineSpacing = 15;
for (String currentTextLable : currentNode.getLabel()) {
Element labelText = doc.createElementNS(svgNameSpace, "text");
labelText.setAttribute("x", Double.toString(symbolSize * 1.5));
labelText.setAttribute("y", Integer.toString(textSpanCounter));
labelText.setAttribute("fill", "black");
labelText.setAttribute("stroke-width", "0");
labelText.setAttribute("font-size", "14");
Text textNode = doc.createTextNode(currentTextLable);
labelText.appendChild(textNode);
textSpanCounter += lineSpacing;
groupNode.appendChild(labelText);
}
////////////////////////////// end alternate method ////////////////////////////////////////////////
((EventTarget) groupNode).addEventListener("mousedown", new MouseListenerSvg(this), false);
return groupNode;
}
public void drawNodes(GraphData graphDataLocal) {
requiresSave = true;
graphData = graphDataLocal;
DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
doc = (SVGDocument) impl.createDocument(svgNameSpace, "svg", null);
new EntitySvg().insertSymbols(doc, svgNameSpace);
// Document doc = impl.createDocument(svgNS, "svg", null);
// SVGDocument doc = svgCanvas.getSVGDocument();
// Get the root element (the 'svg' element).
Element svgRoot = doc.getDocumentElement();
// todo: set up a kinnate namespace so that the ego list and kin type strings can have more permanent storage places
// int maxTextLength = 0;
// for (GraphDataNode currentNode : graphData.getDataNodes()) {
// if (currentNode.getLabel()[0].length() > maxTextLength) {
// maxTextLength = currentNode.getLabel()[0].length();
// }
// }
int vSpacing = graphPanelSize.getVerticalSpacing(graphData.gridHeight);
// todo: find the real text size from batik
// todo: get the user selected canvas size and adjust the hSpacing and vSpacing to fit
// int hSpacing = maxTextLength * 10 + 100;
int hSpacing = graphPanelSize.getHorizontalSpacing(graphData.gridWidth);
int symbolSize = 15;
int strokeWidth = 2;
// int preferedWidth = graphData.gridWidth * hSpacing + hSpacing * 2;
// int preferedHeight = graphData.gridHeight * vSpacing + vSpacing * 2;
// Set the width and height attributes on the root 'svg' element.
svgRoot.setAttribute("width", Integer.toString(graphPanelSize.getWidth(graphData.gridWidth, hSpacing)));
svgRoot.setAttribute("height", Integer.toString(graphPanelSize.getHeight(graphData.gridHeight, vSpacing)));
this.setPreferredSize(new Dimension(graphPanelSize.getHeight(graphData.gridHeight, vSpacing), graphPanelSize.getWidth(graphData.gridWidth, hSpacing)));
// store the selected kin type strings and other data in the dom
dataStoreSvg.storeAllData(doc);
svgCanvas.setSVGDocument(doc);
// svgCanvas.setDocument(doc);
// int counterTest = 0;
for (GraphDataNode currentNode : graphData.getDataNodes()) {
// set up the mouse listners on the group node
// ((EventTarget) groupNode).addEventListener("mouseover", new EventListener() {
//
// public void handleEvent(Event evt) {
// System.out.println("OnMouseOverCircleAction: " + evt.getCurrentTarget());
// if (currentDraggedElement == null) {
// ((Element) evt.getCurrentTarget()).setAttribute("fill", "green");
// }
// }
// }, false);
// ((EventTarget) groupNode).addEventListener("mouseout", new EventListener() {
//
// public void handleEvent(Event evt) {
// System.out.println("mouseout: " + evt.getCurrentTarget());
// if (currentDraggedElement == null) {
// ((Element) evt.getCurrentTarget()).setAttribute("fill", "none");
// }
// }
// }, false);
// draw links
for (GraphDataNode.NodeRelation graphLinkNode : currentNode.getNodeRelations()) {
if (graphLinkNode.sourceNode.equals(currentNode)) {
Element groupNode = doc.createElementNS(svgNameSpace, "g");
Element defsNode = doc.createElementNS(svgNameSpace, "defs");
String lineIdString = currentNode.getEntityPath() + "-" + graphLinkNode.linkedNode.getEntityPath();
// todo: groupNode.setAttribute("id", currentNode.getEntityPath()+ ";"+and the other end);
// set the line end points
int fromX = (currentNode.xPos * hSpacing + hSpacing);
int fromY = (currentNode.yPos * vSpacing + vSpacing);
int toX = (graphLinkNode.linkedNode.xPos * hSpacing + hSpacing);
int toY = (graphLinkNode.linkedNode.yPos * vSpacing + vSpacing);
// set the label position
int labelX = (fromX + toX) / 2;
int labelY = (fromY + toY) / 2;
switch (graphLinkNode.relationLineType) {
case horizontalCurve:
// this case uses the following case
case verticalCurve:
// todo: groupNode.setAttribute("id", );
// System.out.println("link: " + graphLinkNode.linkedNode.xPos + ":" + graphLinkNode.linkedNode.yPos);
//
//// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/>
// Element linkLine = doc.createElementNS(svgNS, "line");
// linkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
// linkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
//
// linkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing));
// linkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing));
// linkLine.setAttribute("stroke", "black");
// linkLine.setAttribute("stroke-width", "1");
// // Attach the rectangle to the root 'svg' element.
// svgRoot.appendChild(linkLine);
System.out.println("link: " + graphLinkNode.linkedNode.xPos + ":" + graphLinkNode.linkedNode.yPos);
// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/>
Element linkLine = doc.createElementNS(svgNameSpace, "path");
int fromBezX;
int fromBezY;
int toBezX;
int toBezY;
if (graphLinkNode.relationLineType == GraphDataNode.RelationLineType.verticalCurve) {
fromBezX = fromX;
fromBezY = toY;
toBezX = toX;
toBezY = fromY;
if (currentNode.yPos == graphLinkNode.linkedNode.yPos) {
fromBezX = fromX;
fromBezY = toY - vSpacing / 2;
toBezX = toX;
toBezY = fromY - vSpacing / 2;
// set the label postion and lower it a bit
labelY = toBezY + vSpacing / 3;
;
}
} else {
fromBezX = toX;
fromBezY = fromY;
toBezX = fromX;
toBezY = toY;
if (currentNode.xPos == graphLinkNode.linkedNode.xPos) {
fromBezY = fromY;
fromBezX = toX - hSpacing / 2;
toBezY = toY;
toBezX = fromX - hSpacing / 2;
// set the label postion
labelX = toBezX;
}
}
linkLine.setAttribute("d", "M " + fromX + "," + fromY + " C " + fromBezX + "," + fromBezY + " " + toBezX + "," + toBezY + " " + toX + "," + toY);
// linkLine.setAttribute("x1", );
// linkLine.setAttribute("y1", );
//
// linkLine.setAttribute("x2", );
linkLine.setAttribute("fill", "none");
linkLine.setAttribute("stroke", "blue");
linkLine.setAttribute("stroke-width", Integer.toString(strokeWidth));
linkLine.setAttribute("id", lineIdString);
defsNode.appendChild(linkLine);
break;
case square:
// Element squareLinkLine = doc.createElement("line");
// squareLinkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
// squareLinkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
//
// squareLinkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing));
// squareLinkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing));
// squareLinkLine.setAttribute("stroke", "grey");
// squareLinkLine.setAttribute("stroke-width", Integer.toString(strokeWidth));
Element squareLinkLine = doc.createElementNS(svgNameSpace, "polyline");
int midY = (fromY + toY) / 2;
if (toY == fromY) {
// make sure that union lines go below the entities and sibling lines go above
if (graphLinkNode.relationType == GraphDataNode.RelationType.sibling) {
midY = toY - vSpacing / 2;
} else if (graphLinkNode.relationType == GraphDataNode.RelationType.union) {
midY = toY + vSpacing / 2;
}
}
squareLinkLine.setAttribute("points",
fromX + "," + fromY + " "
+ fromX + "," + midY + " "
+ toX + "," + midY + " "
+ toX + "," + toY);
squareLinkLine.setAttribute("fill", "none");
squareLinkLine.setAttribute("stroke", "grey");
squareLinkLine.setAttribute("stroke-width", Integer.toString(strokeWidth));
squareLinkLine.setAttribute("id", lineIdString);
defsNode.appendChild(squareLinkLine);
break;
}
groupNode.appendChild(defsNode);
Element useNode = doc.createElementNS(svgNameSpace, "use");
useNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly
// useNode.setAttribute("href", "#" + lineIdString);
groupNode.appendChild(useNode);
// add the relation label
if (graphLinkNode.labelString != null) {
Element labelText = doc.createElementNS(svgNameSpace, "text");
labelText.setAttribute("text-anchor", "middle");
// labelText.setAttribute("x", Integer.toString(labelX));
// labelText.setAttribute("y", Integer.toString(labelY));
labelText.setAttribute("fill", "blue");
labelText.setAttribute("stroke-width", "0");
labelText.setAttribute("font-size", "14");
// labelText.setAttribute("transform", "rotate(45)");
Element textPath = doc.createElementNS(svgNameSpace, "textPath");
textPath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly
textPath.setAttribute("startOffset", "50%");
// textPath.setAttribute("text-anchor", "middle");
Text textNode = doc.createTextNode(graphLinkNode.labelString);
textPath.appendChild(textNode);
labelText.appendChild(textPath);
groupNode.appendChild(labelText);
}
svgRoot.appendChild(groupNode);
}
}
}
// add the entity symbols on top of the links
for (GraphDataNode currentNode : graphData.getDataNodes()) {
svgRoot.appendChild(createEntitySymbol(currentNode, hSpacing, vSpacing, symbolSize));
}
//new CmdiComponentBuilder().savePrettyFormatting(doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/src/main/resources/output.svg"));
svgCanvas.revalidate();
// todo: populate this correctly with the available symbols
dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(new EntitySvg().listSymbolNames(doc));
}
public boolean hasSaveFileName() {
return svgFile != null;
}
public boolean requiresSave() {
return requiresSave;
}
public void saveToFile() {
saveSvg(svgFile);
}
public void saveToFile(File saveAsFile) {
saveSvg(saveAsFile);
}
public void updateGraph() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
Separated the relation svg rendering into a separate class.
|
src/main/java/nl/mpi/kinnate/svg/GraphPanel.java
|
Separated the relation svg rendering into a separate class.
|
|
Java
|
agpl-3.0
|
364343a4cb705def18bad8726c5deaa1bd23ca00
| 0
|
teoincontatto/engine,jerolba/torodb,jerolba/torodb,torodb/engine,torodb/stampede,torodb/server,torodb/engine,ahachete/torodb,torodb/server,torodb/stampede
|
package com.torodb.torod.mongodb.commands.admin;
import com.eightkdata.mongowp.mongoserver.api.safe.Command;
import com.eightkdata.mongowp.mongoserver.api.safe.CommandRequest;
import com.eightkdata.mongowp.mongoserver.api.safe.CommandResult;
import com.eightkdata.mongowp.mongoserver.api.safe.impl.NonWriteCommandResult;
import com.eightkdata.mongowp.mongoserver.api.safe.library.v3m0.commands.admin.ListCollectionsCommand.ListCollectionsArgument;
import com.eightkdata.mongowp.mongoserver.api.safe.library.v3m0.commands.admin.ListCollectionsCommand.ListCollectionsResult;
import com.eightkdata.mongowp.mongoserver.api.safe.library.v3m0.commands.admin.ListCollectionsCommand.ListCollectionsResult.Entry;
import com.eightkdata.mongowp.mongoserver.api.safe.library.v3m0.pojos.CollectionOptions;
import com.eightkdata.mongowp.mongoserver.api.safe.library.v3m0.tools.CursorMarshaller.FirstBatchOnlyCursor;
import com.eightkdata.mongowp.mongoserver.api.safe.pojos.MongoCursor;
import com.eightkdata.mongowp.mongoserver.protocol.exceptions.CommandFailed;
import com.eightkdata.mongowp.mongoserver.protocol.exceptions.MongoException;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.torodb.kvdocument.values.DocValue;
import com.torodb.torod.core.connection.ToroConnection;
import com.torodb.torod.core.cursors.UserCursor;
import com.torodb.torod.core.exceptions.ClosedToroCursorException;
import com.torodb.torod.core.language.querycriteria.QueryCriteria;
import com.torodb.torod.core.pojos.CollectionMetainfo;
import com.torodb.torod.core.subdocument.ToroDocument;
import com.torodb.torod.core.utils.DocValueQueryCriteriaEvaluator;
import com.torodb.torod.mongodb.commands.AbstractToroCommandImplementation;
import com.torodb.torod.mongodb.translator.BsonToToroTranslatorFunction;
import com.torodb.torod.mongodb.translator.QueryCriteriaTranslator;
import com.torodb.torod.mongodb.utils.JsonToBson;
import com.torodb.torod.mongodb.utils.NamespaceUtil;
import java.util.EnumSet;
import java.util.List;
import javax.inject.Inject;
import javax.json.JsonObject;
import org.bson.BsonDocument;
/**
*
*/
public class ListCollectionsImplementation extends
AbstractToroCommandImplementation<ListCollectionsArgument, ListCollectionsResult> {
private final QueryCriteriaTranslator queryCriteriaTranslator;
private final Function<CollectionMetainfo, ListCollectionsResult.Entry> transformation
= new ToListCollectionsReplyEntryFunction();
@Inject
public ListCollectionsImplementation(
QueryCriteriaTranslator queryCriteriaTranslator) {
this.queryCriteriaTranslator = queryCriteriaTranslator;
}
@Override
public CommandResult<ListCollectionsResult> apply(
Command<? super ListCollectionsArgument, ? super ListCollectionsResult> command,
CommandRequest<ListCollectionsArgument> req)
throws MongoException {
try {
ListCollectionsArgument arg = req.getCommandArgument();
ToroConnection connection = getToroConnection(req);
Predicate<ListCollectionsResult.Entry> entryPredicate;
if (arg.getFilter() == null || arg.getFilter().isEmpty()) {
entryPredicate = Predicates.alwaysTrue();
}
else {
/*
* The used way to implement the filter is very ineficient
* because it creates a lot of objects of different types that
* contais the same information. TODO: Improve performance. For
* example, we can evaluate the query on the mongowp objects
*/
QueryCriteria filter = queryCriteriaTranslator.translate(arg.getFilter());
Predicate<DocValue> docValuePredicate =
DocValueQueryCriteriaEvaluator.createPredicate(filter);
entryPredicate = new EntryPredicate(docValuePredicate);
}
UserCursor<CollectionMetainfo> cursor
= connection.openCollectionsMetainfoCursor();
ImmutableList<ListCollectionsResult.Entry> firstBatch = ImmutableList.copyOf(
Iterables.filter(
Iterables.transform(
cursor.readAll(),
transformation
),
entryPredicate
)
);
MongoCursor<ListCollectionsResult.Entry> resultCursor = new FirstBatchOnlyCursor<Entry>(
0,
req.getDatabase(),
NamespaceUtil.LIST_COLLECTIONS_GET_MORE_COLLECTION,
firstBatch,
System.currentTimeMillis()
);
ListCollectionsResult result = new ListCollectionsResult(resultCursor);
return new NonWriteCommandResult<ListCollectionsResult>(result);
} catch (ClosedToroCursorException ex) {
throw new CommandFailed(
command.getCommandName(),
"The cursor that iterates over the collections has been "
+ "suddenly closed "
);
}
}
private static class ToListCollectionsReplyEntryFunction implements Function<CollectionMetainfo, ListCollectionsResult.Entry> {
@Override
public ListCollectionsResult.Entry apply(CollectionMetainfo input) {
if (input == null) {
return null;
}
ListCollectionsResult.Entry result = new Entry(
input.getName(),
new MyCollectionOptions(input)
);
return result;
}
}
private static class MyCollectionOptions extends CollectionOptions {
private final CollectionMetainfo metainfo;
public MyCollectionOptions(CollectionMetainfo metainfo) {
this.metainfo = metainfo;
}
@Override
public boolean isCapped() {
return metainfo.isCapped();
}
@Override
public long getCappedSize() {
return metainfo.getMaxSize();
}
@Override
public long getCappedMaxDocs() {
return metainfo.getMaxElements();
}
@Override
public Long getInitialNumExtents() {
return 1l;
}
@Override
public List<Long> getInitialExtentSizes() {
return null;
}
@Override
public AutoIndexMode getAutoIndexMode() {
return AutoIndexMode.DEFAULT;
}
@Override
public EnumSet<Flag> getFlags() {
return EnumSet.noneOf(Flag.class);
}
@Override
public BsonDocument getStorageEngine() {
if (metainfo.getJson() == null) {
return new BsonDocument();
}
Preconditions.checkState(metainfo.getJson() instanceof JsonObject,
"Expected a json object as extra info from collection "
+ metainfo.getName() + " but a "
+ metainfo.getJson().getClass() + " was found");
return JsonToBson.transform((JsonObject) metainfo.getJson());
}
@Override
public boolean isTemp() {
return false;
}
}
private static class EntryPredicate implements Predicate<ListCollectionsResult.Entry> {
private final Predicate<DocValue> docValuePredicate;
public EntryPredicate(Predicate<DocValue> docValuePredicate) {
this.docValuePredicate = docValuePredicate;
}
@Override
public boolean apply(ListCollectionsResult.Entry input) {
Function<Entry, BsonDocument> transformer = ListCollectionsResult.Entry.FROM_ENTRY;
BsonDocument bson = transformer.apply(input);
ToroDocument toroDoc = BsonToToroTranslatorFunction.INSTANCE.apply(bson);
return docValuePredicate.apply(toroDoc.getRoot());
}
}
}
|
torod/mongodb-layer/src/main/java/com/torodb/torod/mongodb/commands/admin/ListCollectionsImplementation.java
|
package com.torodb.torod.mongodb.commands.admin;
import com.eightkdata.mongowp.mongoserver.api.safe.Command;
import com.eightkdata.mongowp.mongoserver.api.safe.CommandRequest;
import com.eightkdata.mongowp.mongoserver.api.safe.CommandResult;
import com.eightkdata.mongowp.mongoserver.api.safe.impl.NonWriteCommandResult;
import com.eightkdata.mongowp.mongoserver.api.safe.library.v3m0.commands.admin.ListCollectionsCommand.ListCollectionsArgument;
import com.eightkdata.mongowp.mongoserver.api.safe.library.v3m0.commands.admin.ListCollectionsCommand.ListCollectionsResult;
import com.eightkdata.mongowp.mongoserver.api.safe.library.v3m0.commands.admin.ListCollectionsCommand.ListCollectionsResult.Entry;
import com.eightkdata.mongowp.mongoserver.api.safe.library.v3m0.pojos.CollectionOptions;
import com.eightkdata.mongowp.mongoserver.api.safe.library.v3m0.tools.CursorMarshaller.FirstBatchOnlyCursor;
import com.eightkdata.mongowp.mongoserver.api.safe.pojos.MongoCursor;
import com.eightkdata.mongowp.mongoserver.protocol.exceptions.CommandFailed;
import com.eightkdata.mongowp.mongoserver.protocol.exceptions.MongoException;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.torodb.kvdocument.values.DocValue;
import com.torodb.torod.core.connection.ToroConnection;
import com.torodb.torod.core.cursors.UserCursor;
import com.torodb.torod.core.exceptions.ClosedToroCursorException;
import com.torodb.torod.core.language.querycriteria.QueryCriteria;
import com.torodb.torod.core.pojos.CollectionMetainfo;
import com.torodb.torod.core.subdocument.ToroDocument;
import com.torodb.torod.core.utils.DocValueQueryCriteriaEvaluator;
import com.torodb.torod.mongodb.commands.AbstractToroCommandImplementation;
import com.torodb.torod.mongodb.translator.BsonToToroTranslatorFunction;
import com.torodb.torod.mongodb.translator.QueryCriteriaTranslator;
import com.torodb.torod.mongodb.utils.JsonToBson;
import com.torodb.torod.mongodb.utils.NamespaceUtil;
import java.util.EnumSet;
import java.util.List;
import javax.inject.Inject;
import javax.json.JsonObject;
import org.bson.BsonDocument;
/**
*
*/
public class ListCollectionsImplementation extends
AbstractToroCommandImplementation<ListCollectionsArgument, ListCollectionsResult> {
private final QueryCriteriaTranslator queryCriteriaTranslator;
private final Function<CollectionMetainfo, ListCollectionsResult.Entry> transformation
= new ToListCollectionsReplyEntryFunction();
@Inject
public ListCollectionsImplementation(
QueryCriteriaTranslator queryCriteriaTranslator) {
this.queryCriteriaTranslator = queryCriteriaTranslator;
}
@Override
public CommandResult<ListCollectionsResult> apply(
Command<? super ListCollectionsArgument, ? super ListCollectionsResult> command,
CommandRequest<ListCollectionsArgument> req)
throws MongoException {
try {
ListCollectionsArgument arg = req.getCommandArgument();
ToroConnection connection = getToroConnection(req);
Predicate<ListCollectionsResult.Entry> entryPredicate;
if (arg.getFilter() == null || arg.getFilter().isEmpty()) {
entryPredicate = Predicates.alwaysTrue();
}
else {
/*
* The used way to implement the filter is very ineficient
* because it creates a lot of objects of different types that
* contais the same information. TODO: Improve performance. For
* example, we can evaluate the query on the mongowp objects
*/
QueryCriteria filter = queryCriteriaTranslator.translate(arg.getFilter());
Predicate<DocValue> docValuePredicate =
DocValueQueryCriteriaEvaluator.createPredicate(filter);
entryPredicate = new EntryPredicate(docValuePredicate);
}
UserCursor<CollectionMetainfo> cursor
= connection.openCollectionsMetainfoCursor();
ImmutableList<ListCollectionsResult.Entry> firstBatch = ImmutableList.copyOf(
Iterables.filter(
Iterables.transform(
cursor.readAll(),
transformation
),
entryPredicate
)
);
MongoCursor<ListCollectionsResult.Entry> resultCursor = new FirstBatchOnlyCursor<Entry>(
0,
req.getDatabase(),
NamespaceUtil.LIST_COLLECTIONS_GET_MORE_COLLECTION,
firstBatch,
System.currentTimeMillis()
);
ListCollectionsResult result = new ListCollectionsResult(resultCursor);
return new NonWriteCommandResult<ListCollectionsResult>(result);
} catch (ClosedToroCursorException ex) {
throw new CommandFailed(
command.getCommandName(),
"The cursor that iterates over the collections has been "
+ "suddenly closed "
);
}
}
private static class ToListCollectionsReplyEntryFunction implements Function<CollectionMetainfo, ListCollectionsResult.Entry> {
@Override
public ListCollectionsResult.Entry apply(CollectionMetainfo input) {
if (input == null) {
return null;
}
ListCollectionsResult.Entry result = new Entry(
input.getName(),
new MyCollectionOptions(input)
);
return result;
}
}
private static class MyCollectionOptions extends CollectionOptions {
private final CollectionMetainfo metainfo;
public MyCollectionOptions(CollectionMetainfo metainfo) {
this.metainfo = metainfo;
}
@Override
public boolean isCapped() {
return metainfo.isCapped();
}
@Override
public long getCappedSize() {
return metainfo.getMaxSize();
}
@Override
public long getCappedMaxDocs() {
return metainfo.getMaxElements();
}
@Override
public Long getInitialNumExtents() {
return 1l;
}
@Override
public List<Long> getInitialExtentSizes() {
return null;
}
@Override
public AutoIndexMode getAutoIndexMode() {
return AutoIndexMode.DEFAULT;
}
@Override
public EnumSet<Flag> getFlags() {
return EnumSet.noneOf(Flag.class);
}
@Override
public BsonDocument getStorageEngine() {
Preconditions.checkState(metainfo.getJson() instanceof JsonObject,
"Expected a json object as extra info from collection "
+ metainfo.getName() + " but a "
+ metainfo.getJson().getClass() + " was found");
return JsonToBson.transform((JsonObject) metainfo.getJson());
}
@Override
public boolean isTemp() {
return false;
}
}
private static class EntryPredicate implements Predicate<ListCollectionsResult.Entry> {
private final Predicate<DocValue> docValuePredicate;
public EntryPredicate(Predicate<DocValue> docValuePredicate) {
this.docValuePredicate = docValuePredicate;
}
@Override
public boolean apply(ListCollectionsResult.Entry input) {
Function<Entry, BsonDocument> transformer = ListCollectionsResult.Entry.FROM_ENTRY;
BsonDocument bson = transformer.apply(input);
ToroDocument toroDoc = BsonToToroTranslatorFunction.INSTANCE.apply(bson);
return docValuePredicate.apply(toroDoc.getRoot());
}
}
}
|
Fixed NullPointerException on ListCollectionsImplementation
|
torod/mongodb-layer/src/main/java/com/torodb/torod/mongodb/commands/admin/ListCollectionsImplementation.java
|
Fixed NullPointerException on ListCollectionsImplementation
|
|
Java
|
agpl-3.0
|
df623089fc8dd6219a62323ee08794996017b0bb
| 0
|
dirkriehle/wahlzeit,dirkriehle/wahlzeit,dirkriehle/wahlzeit
|
/*
* Copyright (c) 2006-2009 by Dirk Riehle, http://dirkriehle.com
*
* This file is part of the Wahlzeit photo rating application.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package org.wahlzeit.handlers;
import java.util.*;
import org.wahlzeit.model.*;
import org.wahlzeit.utils.*;
import org.wahlzeit.webparts.*;
/**
* A handler class for a specific web form.
*/
public class ShowUserPhotoFormHandler extends AbstractWebFormHandler {
/**
*
*/
public ShowUserPhotoFormHandler() {
initialize(PartUtil.SHOW_USER_PHOTO_FORM_FILE, AccessRights.USER);
}
/**
*
*/
protected void doMakeWebPart(UserSession us, WebPart part) {
Photo photo = us.getPhoto();
String id = photo.getId().asString();
part.addString(Photo.ID, id);
part.addString(Photo.THUMB, getPhotoThumb(us, photo));
part.addString(Photo.PRAISE, photo.getPraiseAsString(us.cfg()));
String tags = photo.getTags().asString();
tags = !StringUtil.isNullOrEmptyString(tags) ? tags : us.cfg().getNoTags();
part.maskAndAddString(Photo.TAGS, tags);
String photoStatus = us.cfg().asValueString(photo.getStatus());
part.addString(Photo.STATUS, photoStatus);
part.addString(Photo.UPLOADED_ON, us.cfg().asDateString(photo.getCreationTime()));
part.addString(Photo.LINK, HtmlUtil.asHref(getResourceAsRelativeHtmlPathString(id)));
}
/**
*
*/
protected boolean isWellFormedPost(UserSession us, Map args) {
String id = us.getAsString(args, Photo.ID);
Photo photo = PhotoManager.getPhoto(id);
return (photo != null) && us.isPhotoOwner(photo);
}
/**
*
*/
protected String doHandlePost(UserSession us, Map args) {
String result = PartUtil.SHOW_USER_HOME_PAGE_NAME;
String id = us.getAndSaveAsString(args, Photo.ID);
Photo photo = PhotoManager.getPhoto(id);
UserManager userManager = UserManager.getInstance();
User user = userManager.getUserByName(photo.getOwnerName());
if (us.isFormType(args, "edit")) {
us.setPhoto(photo);
result = PartUtil.EDIT_USER_PHOTO_PAGE_NAME;
} else if (us.isFormType(args, "tell")) {
us.setPhoto(photo);
result = PartUtil.TELL_FRIEND_PAGE_NAME;
} else if (us.isFormType(args, "select")) {
user.setUserPhoto(photo);
userManager.saveUser(user);
UserLog.logPerformedAction("SelectUserPhoto");
} else if (us.isFormType(args, "delete")) {
photo.setStatus(photo.getStatus().asDeleted(true));
PhotoManager.getInstance().savePhoto(photo);
if (user.getUserPhoto() == photo) {
user.setUserPhoto(null);
}
userManager.saveUser(user);
UserLog.logPerformedAction("DeleteUserPhoto");
}
return result;
}
}
|
src/main/java/org/wahlzeit/handlers/ShowUserPhotoFormHandler.java
|
/*
* Copyright (c) 2006-2009 by Dirk Riehle, http://dirkriehle.com
*
* This file is part of the Wahlzeit photo rating application.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package org.wahlzeit.handlers;
import java.util.*;
import org.wahlzeit.model.*;
import org.wahlzeit.utils.*;
import org.wahlzeit.webparts.*;
/**
* A handler class for a specific web form.
*/
public class ShowUserPhotoFormHandler extends AbstractWebFormHandler {
/**
*
*/
public ShowUserPhotoFormHandler() {
initialize(PartUtil.SHOW_USER_PHOTO_FORM_FILE, AccessRights.USER);
}
/**
*
*/
protected void doMakeWebPart(UserSession us, WebPart part) {
Photo photo = us.getPhoto();
String id = photo.getId().asString();
part.addString(Photo.ID, id);
part.addString(Photo.THUMB, getPhotoThumb(us, photo));
part.addString(Photo.PRAISE, photo.getPraiseAsString(us.cfg()));
String tags = photo.getTags().asString();
tags = !StringUtil.isNullOrEmptyString(tags) ? tags : us.cfg().getNoTags();
part.maskAndAddString(Photo.TAGS, tags);
String photoStatus = us.cfg().asValueString(photo.getStatus());
part.addString(Photo.STATUS, photoStatus);
part.addString(Photo.UPLOADED_ON, us.cfg().asDateString(photo.getCreationTime()));
part.addString(Photo.LINK, HtmlUtil.asHref(getResourceAsRelativeHtmlPathString(id)));
}
/**
*
*/
protected boolean isWellFormedPost(UserSession us, Map args) {
String id = us.getAsString(args, Photo.ID);
Photo photo = PhotoManager.getPhoto(id);
return (photo != null) && us.isPhotoOwner(photo);
}
/**
*
*/
protected String doHandlePost(UserSession us, Map args) {
String result = PartUtil.SHOW_USER_HOME_PAGE_NAME;
String id = us.getAndSaveAsString(args, Photo.ID);
Photo photo = PhotoManager.getPhoto(id);
UserManager userManager = UserManager.getInstance();
User user = userManager.getUserByName(photo.getOwnerName());
if (us.isFormType(args, "edit")) {
us.setPhoto(photo);
result = PartUtil.EDIT_USER_PHOTO_PAGE_NAME;
} else if (us.isFormType(args, "tell")) {
us.setPhoto(photo);
result = PartUtil.TELL_FRIEND_PAGE_NAME;
} else if (us.isFormType(args, "select")) {
user.setUserPhoto(photo);
userManager.saveUser(user);
UserLog.logPerformedAction("SelectUserPhoto");
} else if (us.isFormType(args, "delete")) {
photo.setStatus(photo.getStatus().asDeleted(true));
if (user.getUserPhoto() == photo) {
user.setUserPhoto(null);
}
userManager.saveUser(user);
UserLog.logPerformedAction("DeleteUserPhoto");
}
return result;
}
}
|
Fix issue with photos not being deleted
|
src/main/java/org/wahlzeit/handlers/ShowUserPhotoFormHandler.java
|
Fix issue with photos not being deleted
|
|
Java
|
lgpl-2.1
|
440b4d6cdd8a6c981b143837e97c7bd8c4dc6187
| 0
|
petalslink/petals-bc-jbi-gateway
|
/**
* Copyright (c) 2015-2016 Linagora
*
* This program/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 program/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 program/library; If not, see <http://www.gnu.org/licenses/>
* for the GNU Lesser General Public License version 2.1.
*/
package org.ow2.petals.bc.gateway;
import java.util.Collection;
import org.ow2.petals.bc.gateway.utils.JbiGatewayJBIHelper;
import org.ow2.petals.component.framework.DefaultBootstrap;
import org.ow2.petals.component.framework.api.exception.PEtALSCDKException;
import org.ow2.petals.component.framework.jbidescriptor.generated.Component;
/**
* There is one instance of this class for the whole component. The class is declared in the jbi.xml.
*
* @author vnoel
*
*/
public class JbiGatewayBootstrap extends DefaultBootstrap {
private static final String METHOD_NAME_ADD_TRANSPORT = "addTransportListener";
@Override
public Collection<String> getMBeanOperationsNames() {
final Collection<String> methods = super.getMBeanOperationsNames();
methods.add(METHOD_NAME_ADD_TRANSPORT);
return methods;
}
/**
* TODO could we infer all of this from the jbi without bothering? Like it is the case with the runtimeint and co?
*/
public void addTransportListener(final String id, final int port) throws PEtALSCDKException {
final Component component = getJbiComponentConfiguration().getComponent();
JbiGatewayJBIHelper.addTransportListener(id, port, component);
}
}
|
src/main/java/org/ow2/petals/bc/gateway/JbiGatewayBootstrap.java
|
/**
* Copyright (c) 2015-2016 Linagora
*
* This program/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 program/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 program/library; If not, see <http://www.gnu.org/licenses/>
* for the GNU Lesser General Public License version 2.1.
*/
package org.ow2.petals.bc.gateway;
import java.util.List;
import org.ow2.petals.bc.gateway.utils.JbiGatewayJBIHelper;
import org.ow2.petals.component.framework.DefaultBootstrap;
import org.ow2.petals.component.framework.api.exception.PEtALSCDKException;
import org.ow2.petals.component.framework.jbidescriptor.generated.Component;
/**
* There is one instance of this class for the whole component. The class is declared in the jbi.xml.
*
* @author vnoel
*
*/
public class JbiGatewayBootstrap extends DefaultBootstrap {
private static final String METHOD_NAME_ADD_TRANSPORT = "addTransportListener";
@Override
public List<String> getMethodList() {
final List<String> methods = super.getMethodList();
methods.add(METHOD_NAME_ADD_TRANSPORT);
return methods;
}
/**
* TODO could we infer all of this from the jbi without bothering? Like it is the case with the runtimeint and co?
*/
public void addTransportListener(final String id, final int port) throws PEtALSCDKException {
final Component component = getJbiComponentConfiguration().getComponent();
JbiGatewayJBIHelper.addTransportListener(id, port, component);
}
}
|
Align with trunk
|
src/main/java/org/ow2/petals/bc/gateway/JbiGatewayBootstrap.java
|
Align with trunk
|
|
Java
|
lgpl-2.1
|
31d394c2309cc6cb446b40accbd76ababb30dc5f
| 0
|
tmyroadctfig/swingx,trejkaz/swingx,krichter722/swingx,trejkaz/swingx,krichter722/swingx
|
/*
* $Id$
*
* Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*/
package org.jdesktop.swingx.table;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import javax.swing.table.TableColumn;
import junit.framework.TestCase;
import org.jdesktop.test.PropertyChangeReport;
import org.jdesktop.test.SerializableSupport;
import org.jdesktop.test.TestUtils;
/**
* Test to exposed known issues of <code>TableColumnExt</code>.
*
* Ideally, there would be at least one failing test method per open
* Issue in the issue tracker. Plus additional failing test methods for
* not fully specified or not yet decided upon features/behaviour.
*
* @author Jeanette Winzenburg
*/
public class TableColumnExtIssues extends TestCase {
/**
* Issue #815-swingx: Listeners must not be cloned.
* Sanity: test that listeners registered with the clone are not
* notified when changing the original.
*/
public void testListenerNotificationOrigChanged() {
TableColumnCloneable column = new TableColumnCloneable();
column.setPreferredWidth(column.getMinWidth());
TableColumnCloneable clone = (TableColumnCloneable) column.clone();
PropertyChangeReport report = new PropertyChangeReport();
clone.addPropertyChangeListener(report);
column.setPreferredWidth(column.getPreferredWidth() + 10);
assertEquals(0, report.getEventCount());
}
/**
* Issue #815-swingx: Listeners must not be cloned.
* test that listeners registered with the original are not notified
* when changing the clone.
*/
public void testListenerNotificationCloneChanged() {
TableColumnCloneable column = new TableColumnCloneable();
column.setPreferredWidth(column.getMinWidth());
PropertyChangeReport report = new PropertyChangeReport();
column.addPropertyChangeListener(report);
TableColumnCloneable clone = (TableColumnCloneable) column.clone();
clone.setPreferredWidth(column.getPreferredWidth() + 10);
assertEquals(0, report.getEventCount());
}
/**
* TableColumn sub with a better-behaved clone - removes the cloned listeners
*/
public static class TableColumnCloneable extends TableColumn implements Cloneable {
@Override
public Object clone() {
try {
TableColumn column = (TableColumn) super.clone();
for (int i = 0; i < getPropertyChangeListeners().length; i++) {
column.removePropertyChangeListener(getPropertyChangeListeners()[i]);
}
return column;
} catch (CloneNotSupportedException e) { // don't expect
}
return null;
}
}
/**
* Issue #815-swingx: Listeners must not be cloned.
*/
public void testChangeNofification() {
TableColumnExt column = new TableColumnExt(0);
column.setMaxWidth(1000);
PropertyChangeReport r = new PropertyChangeReport();
column.addPropertyChangeListener(r);
TableColumnExt clone = (TableColumnExt) column.clone();
// change the clone
clone.setMinWidth(44);
assertEquals("listener must not be notified on changes of the clone",
0, r.getEventCount());
}
/**
* Issue #??-swingx: tableColumnExt does not fire propertyChange on resizable.
*
* Happens, if property is changed indirectly by changing min/max value
* to be the same.
*
*/
public void testResizableBoundProperty() {
TableColumnExt columnExt = new TableColumnExt();
// sanity: assert expected defaults of resizable, minWidth
assertTrue(columnExt.getResizable());
assertTrue(columnExt.getMinWidth() > 0);
PropertyChangeReport report = new PropertyChangeReport();
columnExt.addPropertyChangeListener(report);
columnExt.setMaxWidth(columnExt.getMinWidth());
if (!columnExt.getResizable()) {
assertEquals("fixing column widths must fire resizable ",
1, report.getEventCount("resizable"));
} else {
fail("resizable must respect fixed column width");
}
}
/**
* Sanity test Serializable: Listeners? Report not serializable?
*
* @throws ClassNotFoundException
* @throws IOException
*
*/
public void testSerializable() throws IOException, ClassNotFoundException {
TableColumnExt columnExt = new TableColumnExt();
PropertyChangeReport report = new PropertyChangeReport();
columnExt.addPropertyChangeListener(report);
TableColumnExt serialized = SerializableSupport.serialize(columnExt);
PropertyChangeListener[] listeners = serialized
.getPropertyChangeListeners();
assertTrue(listeners.length > 0);
}
/**
* Issue #??-swingx: must handle non-serializable client properties
* gracefully.
*
* @throws ClassNotFoundException
* @throws IOException
*
*
*/
public void testNonSerializableClientProperties() throws IOException, ClassNotFoundException {
TableColumnExt columnExt = new TableColumnExt();
Object value = new Object();
columnExt.putClientProperty("date", value );
SerializableSupport.serialize(columnExt);
}
/**
* Dummy stand-in test method, does nothing.
* without, the test would fail if there are no open issues.
*
*/
public void testDummy() {
}
}
|
src/test/org/jdesktop/swingx/table/TableColumnExtIssues.java
|
/*
* $Id$
*
* Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*/
package org.jdesktop.swingx.table;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import junit.framework.TestCase;
import org.jdesktop.test.PropertyChangeReport;
import org.jdesktop.test.SerializableSupport;
/**
* Test to exposed known issues of <code>TableColumnExt</code>.
*
* Ideally, there would be at least one failing test method per open
* Issue in the issue tracker. Plus additional failing test methods for
* not fully specified or not yet decided upon features/behaviour.
*
* @author Jeanette Winzenburg
*/
public class TableColumnExtIssues extends TestCase {
/**
* Issue #815-swingx: Listeners must not be cloned.
*/
public void testChangeNofification() {
TableColumnExt column = new TableColumnExt(0);
column.setMaxWidth(1000);
PropertyChangeReport r = new PropertyChangeReport();
column.addPropertyChangeListener(r);
TableColumnExt clone = (TableColumnExt) column.clone();
// change the clone
clone.setMinWidth(44);
assertEquals("listener must not be notified on changes of the clone",
0, r.getEventCount());
}
/**
* Issue #??-swingx: tableColumnExt does not fire propertyChange on resizable.
*
* Happens, if property is changed indirectly by changing min/max value
* to be the same.
*
*/
public void testResizableBoundProperty() {
TableColumnExt columnExt = new TableColumnExt();
// sanity: assert expected defaults of resizable, minWidth
assertTrue(columnExt.getResizable());
assertTrue(columnExt.getMinWidth() > 0);
PropertyChangeReport report = new PropertyChangeReport();
columnExt.addPropertyChangeListener(report);
columnExt.setMaxWidth(columnExt.getMinWidth());
if (!columnExt.getResizable()) {
assertEquals("fixing column widths must fire resizable ",
1, report.getEventCount("resizable"));
} else {
fail("resizable must respect fixed column width");
}
}
/**
* Sanity test Serializable: Listeners? Report not serializable?
*
* @throws ClassNotFoundException
* @throws IOException
*
*/
public void testSerializable() throws IOException, ClassNotFoundException {
TableColumnExt columnExt = new TableColumnExt();
PropertyChangeReport report = new PropertyChangeReport();
columnExt.addPropertyChangeListener(report);
TableColumnExt serialized = SerializableSupport.serialize(columnExt);
PropertyChangeListener[] listeners = serialized
.getPropertyChangeListeners();
assertTrue(listeners.length > 0);
}
/**
* Issue #??-swingx: must handle non-serializable client properties
* gracefully.
*
* @throws ClassNotFoundException
* @throws IOException
*
*
*/
public void testNonSerializableClientProperties() throws IOException, ClassNotFoundException {
TableColumnExt columnExt = new TableColumnExt();
Object value = new Object();
columnExt.putClientProperty("date", value );
SerializableSupport.serialize(columnExt);
}
/**
* Dummy stand-in test method, does nothing.
* without, the test would fail if there are no open issues.
*
*/
public void testDummy() {
}
}
|
Issue #815-swingx: TableColumnExt must not clone listeners
- added example
git-svn-id: 9c6ef37dfd7eaa5a3748af7ba0f8d9e7b67c2a4c@2834 1312f61e-266d-0410-97fa-c3b71232c9ac
|
src/test/org/jdesktop/swingx/table/TableColumnExtIssues.java
| ||
Java
|
apache-2.0
|
d14a846032dff404a13e10f081e7bd311bfdd001
| 0
|
h2oai/h2o-dev,mathemage/h2o-3,YzPaul3/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,mathemage/h2o-3,mathemage/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,jangorecki/h2o-3,mathemage/h2o-3,jangorecki/h2o-3,michalkurka/h2o-3,YzPaul3/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,spennihana/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,spennihana/h2o-3,h2oai/h2o-3,mathemage/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,YzPaul3/h2o-3,mathemage/h2o-3,jangorecki/h2o-3,h2oai/h2o-3,mathemage/h2o-3,h2oai/h2o-dev,jangorecki/h2o-3,michalkurka/h2o-3,jangorecki/h2o-3,YzPaul3/h2o-3,YzPaul3/h2o-3,spennihana/h2o-3,spennihana/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,h2oai/h2o-dev,jangorecki/h2o-3,YzPaul3/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,spennihana/h2o-3,YzPaul3/h2o-3
|
package water.util;
import water.*;
import water.H2O.H2OCallback;
import water.H2O.H2OCountedCompleter;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.NewChunk;
import water.fvec.Vec;
import water.nbhm.NonBlockingHashMap;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import static water.util.RandomUtils.getRNG;
public class MRUtils {
/**
* Sample rows from a frame.
* Can be unlucky for small sampling fractions - will continue calling itself until at least 1 row is returned.
* @param fr Input frame
* @param rows Approximate number of rows to sample (across all chunks)
* @param seed Seed for RNG
* @return Sampled frame
*/
public static Frame sampleFrame(Frame fr, final long rows, final long seed) {
if (fr == null) return null;
final float fraction = rows > 0 ? (float)rows / fr.numRows() : 1.f;
if (fraction >= 1.f) return fr;
Key newKey = fr._key != null ? Key.make(fr._key.toString() + (fr._key.toString().contains("temporary") ? ".sample." : ".temporary.sample.") + PrettyPrint.formatPct(fraction).replace(" ","")) : null;
Frame r = new MRTask() {
@Override
public void map(Chunk[] cs, NewChunk[] ncs) {
final Random rng = getRNG(0);
int count = 0;
for (int r = 0; r < cs[0]._len; r++) {
rng.setSeed(seed+r+cs[0].start());
if (rng.nextFloat() < fraction || (count == 0 && r == cs[0]._len-1) ) {
count++;
for (int i = 0; i < ncs.length; i++) {
ncs[i].addNum(cs[i].atd(r));
}
}
}
}
}.doAll(fr.types(), fr).outputFrame(newKey, fr.names(), fr.domains());
if (r.numRows() == 0) {
Log.warn("You asked for " + rows + " rows (out of " + fr.numRows() + "), but you got none (seed=" + seed + ").");
Log.warn("Let's try again. You've gotta ask yourself a question: \"Do I feel lucky?\"");
return sampleFrame(fr, rows, seed+1);
}
return r;
}
/**
* Row-wise shuffle of a frame (only shuffles rows inside of each chunk)
* @param fr Input frame
* @return Shuffled frame
*/
public static Frame shuffleFramePerChunk(Frame fr, final long seed) {
return new MRTask() {
@Override
public void map(Chunk[] cs, NewChunk[] ncs) {
int[] idx = new int[cs[0]._len];
for (int r=0; r<idx.length; ++r) idx[r] = r;
ArrayUtils.shuffleArray(idx, getRNG(seed));
for (long anIdx : idx) {
for (int i = 0; i < ncs.length; i++) {
ncs[i].addNum(cs[i].atd((int) anIdx));
}
}
}
}.doAll(fr.numCols(), Vec.T_NUM, fr).outputFrame(fr.names(), fr.domains());
}
/**
* Compute the class distribution from a class label vector
* (not counting missing values)
*
* Usage 1: Label vector is categorical
* ------------------------------------
* Vec label = ...;
* assert(label.isCategorical());
* double[] dist = new ClassDist(label).doAll(label).dist();
*
* Usage 2: Label vector is numerical
* ----------------------------------
* Vec label = ...;
* int num_classes = ...;
* assert(label.isInt());
* double[] dist = new ClassDist(num_classes).doAll(label).dist();
*
*/
public static class ClassDist extends MRTask<ClassDist> {
final int _nclass;
protected double[] _ys;
public ClassDist(final Vec label) { _nclass = label.domain().length; }
public ClassDist(int n) { _nclass = n; }
public final double[] dist() { return _ys; }
public final double[] rel_dist() {
final double sum = ArrayUtils.sum(_ys);
return ArrayUtils.div(Arrays.copyOf(_ys, _ys.length), sum);
}
@Override public void map(Chunk ys) {
_ys = new double[_nclass];
for( int i=0; i<ys._len; i++ )
if (!ys.isNA(i))
_ys[(int) ys.at8(i)]++;
}
@Override public void map(Chunk ys, Chunk ws) {
_ys = new double[_nclass];
for( int i=0; i<ys._len; i++ )
if (!ys.isNA(i))
_ys[(int) ys.at8(i)] += ws.atd(i);
}
@Override public void reduce( ClassDist that ) { ArrayUtils.add(_ys,that._ys); }
}
public static class Dist extends MRTask<Dist> {
private IcedHashMap<Double,Integer> _dist;
@Override public void map(Chunk ys) {
_dist = new IcedHashMap<>();
for( int row=0; row< ys._len; row++ )
if( !ys.isNA(row) ) {
double v = ys.atd(row);
Integer oldV = _dist.putIfAbsent(v,1);
if( oldV!=null ) _dist.put(v,oldV+1);
}
}
@Override public void reduce(Dist mrt) {
if( _dist != mrt._dist ) {
IcedHashMap<Double,Integer> l = _dist;
IcedHashMap<Double,Integer> r = mrt._dist;
if( l.size() < r.size() ) { l=r; r=_dist; }
for( Double v: r.keySet() ) {
Integer oldVal = l.putIfAbsent(v, r.get(v));
if( oldVal!=null ) l.put(v, oldVal+r.get(v));
}
_dist=l;
mrt._dist=null;
}
}
public double[] dist() {
int i=0;
double[] dist = new double[_dist.size()];
for( int v: _dist.values() ) dist[i++] = v;
return dist;
}
public double[] keys() {
int i=0;
double[] keys = new double[_dist.size()];
for( double v: _dist.keySet() ) keys[i++] = v;
return keys;
}
}
/**
* Stratified sampling for classifiers - FIXME: For weights, this is not accurate, as the sampling is done with uniform weights
* @param fr Input frame
* @param label Label vector (must be categorical)
* @param weights Weights vector, can be null
* @param sampling_ratios Optional: array containing the requested sampling ratios per class (in order of domains), will be overwritten if it contains all 0s
* @param maxrows Maximum number of rows in the returned frame
* @param seed RNG seed for sampling
* @param allowOversampling Allow oversampling of minority classes
* @param verbose Whether to print verbose info
* @return Sampled frame, with approximately the same number of samples from each class (or given by the requested sampling ratios)
*/
public static Frame sampleFrameStratified(final Frame fr, Vec label, Vec weights, float[] sampling_ratios, long maxrows, final long seed, final boolean allowOversampling, final boolean verbose) {
if (fr == null) return null;
assert(label.isCategorical());
if (maxrows < label.domain().length) {
Log.warn("Attempting to do stratified sampling to fewer samples than there are class labels - automatically increasing to #rows == #labels (" + label.domain().length + ").");
maxrows = label.domain().length;
}
ClassDist cd = new ClassDist(label);
double[] dist = weights != null ? cd.doAll(label, weights).dist() : cd.doAll(label).dist();
assert(dist.length > 0);
Log.info("Doing stratified sampling for data set containing " + fr.numRows() + " rows from " + dist.length + " classes. Oversampling: " + (allowOversampling ? "on" : "off"));
if (verbose)
for (int i=0; i<dist.length;++i)
Log.info("Class " + label.factor(i) + ": count: " + dist[i] + " prior: " + (float)dist[i]/fr.numRows());
// create sampling_ratios for class balance with max. maxrows rows (fill
// existing array if not null). Make a defensive copy.
sampling_ratios = sampling_ratios == null ? new float[dist.length] : sampling_ratios.clone();
assert sampling_ratios.length == dist.length;
if( ArrayUtils.minValue(sampling_ratios) == 0 && ArrayUtils.maxValue(sampling_ratios) == 0 ) {
// compute sampling ratios to achieve class balance
for (int i=0; i<dist.length;++i)
sampling_ratios[i] = ((float)fr.numRows() / label.domain().length) / (float)dist[i]; // prior^-1 / num_classes
final float inv_scale = ArrayUtils.minValue(sampling_ratios); //majority class has lowest required oversampling factor to achieve balance
if (!Float.isNaN(inv_scale) && !Float.isInfinite(inv_scale))
ArrayUtils.div(sampling_ratios, inv_scale); //want sampling_ratio 1.0 for majority class (no downsampling)
}
if (!allowOversampling)
for (int i=0; i<sampling_ratios.length; ++i)
sampling_ratios[i] = Math.min(1.0f, sampling_ratios[i]);
// given these sampling ratios, and the original class distribution, this is the expected number of resulting rows
float numrows = 0;
for (int i=0; i<sampling_ratios.length; ++i) {
numrows += sampling_ratios[i] * dist[i];
}
if (Float.isNaN(numrows)) {
throw new IllegalArgumentException("Error during sampling - too few points?");
}
final long actualnumrows = Math.min(maxrows, Math.round(numrows)); //cap #rows at maxrows
assert(actualnumrows >= 0); //can have no matching rows in case of sparse data where we had to fill in a makeZero() vector
Log.info("Stratified sampling to a total of " + String.format("%,d", actualnumrows) + " rows" + (actualnumrows < numrows ? " (limited by max_after_balance_size).":"."));
if (actualnumrows != numrows) {
ArrayUtils.mult(sampling_ratios, (float)actualnumrows/numrows); //adjust the sampling_ratios by the global rescaling factor
if (verbose)
Log.info("Downsampling majority class by " + (float)actualnumrows/numrows
+ " to limit number of rows to " + String.format("%,d", maxrows));
}
for (int i=0;i<label.domain().length;++i) {
Log.info("Class '" + label.domain()[i] + "' sampling ratio: " + sampling_ratios[i]);
}
return sampleFrameStratified(fr, label, weights, sampling_ratios, seed, verbose);
}
/**
* Stratified sampling
* @param fr Input frame
* @param label Label vector (from the input frame)
* @param weights Weight vector (from the input frame), can be null
* @param sampling_ratios Given sampling ratios for each class, in order of domains
* @param seed RNG seed
* @param debug Whether to print debug info
* @return Stratified frame
*/
public static Frame sampleFrameStratified(final Frame fr, Vec label, Vec weights, final float[] sampling_ratios, final long seed, final boolean debug) {
return sampleFrameStratified(fr, label, weights, sampling_ratios, seed, debug, 0);
}
// internal version with repeat counter
// currently hardcoded to do up to 10 tries to get a row from each class, which can be impossible for certain wrong sampling ratios
private static Frame sampleFrameStratified(final Frame fr, Vec label, Vec weights, final float[] sampling_ratios, final long seed, final boolean debug, int count) {
if (fr == null) return null;
assert(label.isCategorical());
assert(sampling_ratios != null && sampling_ratios.length == label.domain().length);
final int labelidx = fr.find(label); //which column is the label?
assert(labelidx >= 0);
final int weightsidx = fr.find(weights); //which column is the weight?
final boolean poisson = false; //beta feature
//FIXME - this is doing uniform sampling, even if the weights are given
Frame r = new MRTask() {
@Override
public void map(Chunk[] cs, NewChunk[] ncs) {
final Random rng = getRNG(seed);
for (int r = 0; r < cs[0]._len; r++) {
if (cs[labelidx].isNA(r)) continue; //skip missing labels
rng.setSeed(cs[0].start()+r+seed);
final int label = (int)cs[labelidx].at8(r);
assert(sampling_ratios.length > label && label >= 0);
int sampling_reps;
if (poisson) {
throw H2O.unimpl();
// sampling_reps = ArrayUtils.getPoisson(sampling_ratios[label], rng);
} else {
final float remainder = sampling_ratios[label] - (int)sampling_ratios[label];
sampling_reps = (int)sampling_ratios[label] + (rng.nextFloat() < remainder ? 1 : 0);
}
for (int i = 0; i < ncs.length; i++) {
for (int j = 0; j < sampling_reps; ++j) {
ncs[i].addNum(cs[i].atd(r));
}
}
}
}
}.doAll(fr.types(), fr).outputFrame(fr.names(), fr.domains());
// Confirm the validity of the distribution
Vec lab = r.vecs()[labelidx];
Vec wei = weightsidx != -1 ? r.vecs()[weightsidx] : null;
double[] dist = wei != null ? new ClassDist(lab).doAll(lab, wei).dist() : new ClassDist(lab).doAll(lab).dist();
// if there are no training labels in the test set, then there is no point in sampling the test set
if (dist == null) return fr;
if (debug) {
double sumdist = ArrayUtils.sum(dist);
Log.info("After stratified sampling: " + sumdist + " rows.");
for (int i=0; i<dist.length;++i) {
Log.info("Class " + r.vecs()[labelidx].factor(i) + ": count: " + dist[i]
+ " sampling ratio: " + sampling_ratios[i] + " actual relative frequency: " + (float)dist[i] / sumdist * dist.length);
}
}
// Re-try if we didn't get at least one example from each class
if (ArrayUtils.minValue(dist) == 0 && count < 10) {
Log.info("Re-doing stratified sampling because not all classes were represented (unlucky draw).");
r.delete();
return sampleFrameStratified(fr, label, weights, sampling_ratios, seed+1, debug, ++count);
}
// shuffle intra-chunk
Frame shuffled = shuffleFramePerChunk(r, seed+0x580FF13);
r.delete();
return shuffled;
}
}
|
h2o-core/src/main/java/water/util/MRUtils.java
|
package water.util;
import water.*;
import water.H2O.H2OCallback;
import water.H2O.H2OCountedCompleter;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.NewChunk;
import water.fvec.Vec;
import water.nbhm.NonBlockingHashMap;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import static water.util.RandomUtils.getRNG;
public class MRUtils {
/**
* Sample rows from a frame.
* Can be unlucky for small sampling fractions - will continue calling itself until at least 1 row is returned.
* @param fr Input frame
* @param rows Approximate number of rows to sample (across all chunks)
* @param seed Seed for RNG
* @return Sampled frame
*/
public static Frame sampleFrame(Frame fr, final long rows, final long seed) {
if (fr == null) return null;
final float fraction = rows > 0 ? (float)rows / fr.numRows() : 1.f;
if (fraction >= 1.f) return fr;
Key newKey = fr._key != null ? Key.make(fr._key.toString() + (fr._key.toString().contains("temporary") ? ".sample." : ".temporary.sample.") + PrettyPrint.formatPct(fraction).replace(" ","")) : null;
Frame r = new MRTask() {
@Override
public void map(Chunk[] cs, NewChunk[] ncs) {
final Random rng = getRNG(0);
int count = 0;
for (int r = 0; r < cs[0]._len; r++) {
rng.setSeed(seed+r+cs[0].start());
if (rng.nextFloat() < fraction || (count == 0 && r == cs[0]._len-1) ) {
count++;
for (int i = 0; i < ncs.length; i++) {
ncs[i].addNum(cs[i].atd(r));
}
}
}
}
}.doAll(fr.types(), fr).outputFrame(newKey, fr.names(), fr.domains());
if (r.numRows() == 0) {
Log.warn("You asked for " + rows + " rows (out of " + fr.numRows() + "), but you got none (seed=" + seed + ").");
Log.warn("Let's try again. You've gotta ask yourself a question: \"Do I feel lucky?\"");
return sampleFrame(fr, rows, seed+1);
}
return r;
}
/**
* Row-wise shuffle of a frame (only shuffles rows inside of each chunk)
* @param fr Input frame
* @return Shuffled frame
*/
public static Frame shuffleFramePerChunk(Frame fr, final long seed) {
return new MRTask() {
@Override
public void map(Chunk[] cs, NewChunk[] ncs) {
int[] idx = new int[cs[0]._len];
for (int r=0; r<idx.length; ++r) idx[r] = r;
ArrayUtils.shuffleArray(idx, getRNG(seed));
for (long anIdx : idx) {
for (int i = 0; i < ncs.length; i++) {
ncs[i].addNum(cs[i].atd((int) anIdx));
}
}
}
}.doAll(fr.numCols(), Vec.T_NUM, fr).outputFrame(fr.names(), fr.domains());
}
/**
* Compute the class distribution from a class label vector
* (not counting missing values)
*
* Usage 1: Label vector is categorical
* ------------------------------------
* Vec label = ...;
* assert(label.isCategorical());
* double[] dist = new ClassDist(label).doAll(label).dist();
*
* Usage 2: Label vector is numerical
* ----------------------------------
* Vec label = ...;
* int num_classes = ...;
* assert(label.isInt());
* double[] dist = new ClassDist(num_classes).doAll(label).dist();
*
*/
public static class ClassDist extends MRTask<ClassDist> {
final int _nclass;
protected double[] _ys;
public ClassDist(final Vec label) { _nclass = label.domain().length; }
public ClassDist(int n) { _nclass = n; }
public final double[] dist() { return _ys; }
public final double[] rel_dist() {
final double sum = ArrayUtils.sum(_ys);
return ArrayUtils.div(Arrays.copyOf(_ys, _ys.length), sum);
}
@Override public void map(Chunk ys) {
_ys = new double[_nclass];
for( int i=0; i<ys._len; i++ )
if (!ys.isNA(i))
_ys[(int) ys.at8(i)]++;
}
@Override public void map(Chunk ys, Chunk ws) {
_ys = new double[_nclass];
for( int i=0; i<ys._len; i++ )
if (!ys.isNA(i))
_ys[(int) ys.at8(i)] += ws.atd(i);
}
@Override public void reduce( ClassDist that ) { ArrayUtils.add(_ys,that._ys); }
}
public static class Dist extends MRTask<Dist> {
private transient NonBlockingHashMap<Double,Integer> _dist;
@Override public void map(Chunk ys) {
_dist = new NonBlockingHashMap<>();
for( int row=0; row< ys._len; row++ )
if( !ys.isNA(row) ) {
double v = ys.atd(row);
Integer oldV = _dist.putIfAbsent(v,1);
if( oldV!=null ) _dist.put(v,oldV+1);
}
}
@Override public void reduce(Dist mrt) {
if( _dist != mrt._dist ) {
NonBlockingHashMap<Double,Integer> l = _dist;
NonBlockingHashMap<Double,Integer> r = mrt._dist;
if( l.size() < r.size() ) { l=r; r=_dist; }
for( Double v: r.keySet() ) {
Integer oldVal = l.putIfAbsent(v, r.get(v));
if( oldVal!=null ) l.put(v, oldVal+r.get(v));
}
_dist=l;
mrt._dist=null;
}
}
public double[] dist() {
int i=0;
double[] dist = new double[_dist.size()];
for( int v: _dist.values() ) dist[i++] = v;
return dist;
}
public double[] keys() {
int i=0;
double[] keys = new double[_dist.size()];
for( double v: _dist.keySet() ) keys[i++] = v;
return keys;
}
}
/**
* Stratified sampling for classifiers - FIXME: For weights, this is not accurate, as the sampling is done with uniform weights
* @param fr Input frame
* @param label Label vector (must be categorical)
* @param weights Weights vector, can be null
* @param sampling_ratios Optional: array containing the requested sampling ratios per class (in order of domains), will be overwritten if it contains all 0s
* @param maxrows Maximum number of rows in the returned frame
* @param seed RNG seed for sampling
* @param allowOversampling Allow oversampling of minority classes
* @param verbose Whether to print verbose info
* @return Sampled frame, with approximately the same number of samples from each class (or given by the requested sampling ratios)
*/
public static Frame sampleFrameStratified(final Frame fr, Vec label, Vec weights, float[] sampling_ratios, long maxrows, final long seed, final boolean allowOversampling, final boolean verbose) {
if (fr == null) return null;
assert(label.isCategorical());
if (maxrows < label.domain().length) {
Log.warn("Attempting to do stratified sampling to fewer samples than there are class labels - automatically increasing to #rows == #labels (" + label.domain().length + ").");
maxrows = label.domain().length;
}
ClassDist cd = new ClassDist(label);
double[] dist = weights != null ? cd.doAll(label, weights).dist() : cd.doAll(label).dist();
assert(dist.length > 0);
Log.info("Doing stratified sampling for data set containing " + fr.numRows() + " rows from " + dist.length + " classes. Oversampling: " + (allowOversampling ? "on" : "off"));
if (verbose)
for (int i=0; i<dist.length;++i)
Log.info("Class " + label.factor(i) + ": count: " + dist[i] + " prior: " + (float)dist[i]/fr.numRows());
// create sampling_ratios for class balance with max. maxrows rows (fill
// existing array if not null). Make a defensive copy.
sampling_ratios = sampling_ratios == null ? new float[dist.length] : sampling_ratios.clone();
assert sampling_ratios.length == dist.length;
if( ArrayUtils.minValue(sampling_ratios) == 0 && ArrayUtils.maxValue(sampling_ratios) == 0 ) {
// compute sampling ratios to achieve class balance
for (int i=0; i<dist.length;++i)
sampling_ratios[i] = ((float)fr.numRows() / label.domain().length) / (float)dist[i]; // prior^-1 / num_classes
final float inv_scale = ArrayUtils.minValue(sampling_ratios); //majority class has lowest required oversampling factor to achieve balance
if (!Float.isNaN(inv_scale) && !Float.isInfinite(inv_scale))
ArrayUtils.div(sampling_ratios, inv_scale); //want sampling_ratio 1.0 for majority class (no downsampling)
}
if (!allowOversampling)
for (int i=0; i<sampling_ratios.length; ++i)
sampling_ratios[i] = Math.min(1.0f, sampling_ratios[i]);
// given these sampling ratios, and the original class distribution, this is the expected number of resulting rows
float numrows = 0;
for (int i=0; i<sampling_ratios.length; ++i) {
numrows += sampling_ratios[i] * dist[i];
}
if (Float.isNaN(numrows)) {
throw new IllegalArgumentException("Error during sampling - too few points?");
}
final long actualnumrows = Math.min(maxrows, Math.round(numrows)); //cap #rows at maxrows
assert(actualnumrows >= 0); //can have no matching rows in case of sparse data where we had to fill in a makeZero() vector
Log.info("Stratified sampling to a total of " + String.format("%,d", actualnumrows) + " rows" + (actualnumrows < numrows ? " (limited by max_after_balance_size).":"."));
if (actualnumrows != numrows) {
ArrayUtils.mult(sampling_ratios, (float)actualnumrows/numrows); //adjust the sampling_ratios by the global rescaling factor
if (verbose)
Log.info("Downsampling majority class by " + (float)actualnumrows/numrows
+ " to limit number of rows to " + String.format("%,d", maxrows));
}
for (int i=0;i<label.domain().length;++i) {
Log.info("Class '" + label.domain()[i] + "' sampling ratio: " + sampling_ratios[i]);
}
return sampleFrameStratified(fr, label, weights, sampling_ratios, seed, verbose);
}
/**
* Stratified sampling
* @param fr Input frame
* @param label Label vector (from the input frame)
* @param weights Weight vector (from the input frame), can be null
* @param sampling_ratios Given sampling ratios for each class, in order of domains
* @param seed RNG seed
* @param debug Whether to print debug info
* @return Stratified frame
*/
public static Frame sampleFrameStratified(final Frame fr, Vec label, Vec weights, final float[] sampling_ratios, final long seed, final boolean debug) {
return sampleFrameStratified(fr, label, weights, sampling_ratios, seed, debug, 0);
}
// internal version with repeat counter
// currently hardcoded to do up to 10 tries to get a row from each class, which can be impossible for certain wrong sampling ratios
private static Frame sampleFrameStratified(final Frame fr, Vec label, Vec weights, final float[] sampling_ratios, final long seed, final boolean debug, int count) {
if (fr == null) return null;
assert(label.isCategorical());
assert(sampling_ratios != null && sampling_ratios.length == label.domain().length);
final int labelidx = fr.find(label); //which column is the label?
assert(labelidx >= 0);
final int weightsidx = fr.find(weights); //which column is the weight?
final boolean poisson = false; //beta feature
//FIXME - this is doing uniform sampling, even if the weights are given
Frame r = new MRTask() {
@Override
public void map(Chunk[] cs, NewChunk[] ncs) {
final Random rng = getRNG(seed);
for (int r = 0; r < cs[0]._len; r++) {
if (cs[labelidx].isNA(r)) continue; //skip missing labels
rng.setSeed(cs[0].start()+r+seed);
final int label = (int)cs[labelidx].at8(r);
assert(sampling_ratios.length > label && label >= 0);
int sampling_reps;
if (poisson) {
throw H2O.unimpl();
// sampling_reps = ArrayUtils.getPoisson(sampling_ratios[label], rng);
} else {
final float remainder = sampling_ratios[label] - (int)sampling_ratios[label];
sampling_reps = (int)sampling_ratios[label] + (rng.nextFloat() < remainder ? 1 : 0);
}
for (int i = 0; i < ncs.length; i++) {
for (int j = 0; j < sampling_reps; ++j) {
ncs[i].addNum(cs[i].atd(r));
}
}
}
}
}.doAll(fr.types(), fr).outputFrame(fr.names(), fr.domains());
// Confirm the validity of the distribution
Vec lab = r.vecs()[labelidx];
Vec wei = weightsidx != -1 ? r.vecs()[weightsidx] : null;
double[] dist = wei != null ? new ClassDist(lab).doAll(lab, wei).dist() : new ClassDist(lab).doAll(lab).dist();
// if there are no training labels in the test set, then there is no point in sampling the test set
if (dist == null) return fr;
if (debug) {
double sumdist = ArrayUtils.sum(dist);
Log.info("After stratified sampling: " + sumdist + " rows.");
for (int i=0; i<dist.length;++i) {
Log.info("Class " + r.vecs()[labelidx].factor(i) + ": count: " + dist[i]
+ " sampling ratio: " + sampling_ratios[i] + " actual relative frequency: " + (float)dist[i] / sumdist * dist.length);
}
}
// Re-try if we didn't get at least one example from each class
if (ArrayUtils.minValue(dist) == 0 && count < 10) {
Log.info("Re-doing stratified sampling because not all classes were represented (unlucky draw).");
r.delete();
return sampleFrameStratified(fr, label, weights, sampling_ratios, seed+1, debug, ++count);
}
// shuffle intra-chunk
Frame shuffled = shuffleFramePerChunk(r, seed+0x580FF13);
r.delete();
return shuffled;
}
}
|
Fix MRUtils.Dist() to use a global (Iced) hash table (was node-local and transient, led to spurious NPE).
|
h2o-core/src/main/java/water/util/MRUtils.java
|
Fix MRUtils.Dist() to use a global (Iced) hash table (was node-local and transient, led to spurious NPE).
|
|
Java
|
apache-2.0
|
1eb7093257a4242581fe616603af820f886c6f30
| 0
|
nassim-git/project-voldemort,nassim-git/project-voldemort,nassim-git/project-voldemort,nassim-git/project-voldemort
|
/*
* Copyright 2008-2009 LinkedIn, 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 voldemort.store.mysql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import voldemort.VoldemortException;
import voldemort.store.Entry;
import voldemort.store.PersistenceFailureException;
import voldemort.store.StorageEngine;
import voldemort.store.StoreUtils;
import voldemort.utils.ByteArray;
import voldemort.utils.ClosableIterator;
import voldemort.versioning.ObsoleteVersionException;
import voldemort.versioning.Occured;
import voldemort.versioning.VectorClock;
import voldemort.versioning.Version;
import voldemort.versioning.Versioned;
import com.google.common.collect.Lists;
/**
* A StorageEngine that uses Mysql for persistence
*
* @author jay
*
*/
public class MysqlStorageEngine implements StorageEngine<ByteArray, byte[]> {
private static final Logger logger = Logger.getLogger(MysqlStorageEngine.class);
private static int MYSQL_ERR_DUP_KEY = 1022;
private static int MYSQL_ERR_DUP_ENTRY = 1062;
private final String name;
private final DataSource datasource;
public MysqlStorageEngine(String name, DataSource datasource) {
this.name = name;
this.datasource = datasource;
if(!tableExists()) {
create();
}
}
private boolean tableExists() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String select = "show tables like '" + getName() + "'";
try {
conn = this.datasource.getConnection();
stmt = conn.prepareStatement(select);
rs = stmt.executeQuery();
return rs.next();
} catch(SQLException e) {
throw new PersistenceFailureException("SQLException while checking for table existence!",
e);
} finally {
tryClose(rs);
tryClose(stmt);
tryClose(conn);
}
}
public void destroy() {
execute("drop table if exists " + getName());
}
public void create() {
execute("create table " + getName()
+ " (key_ varbinary(200) not null, version_ varbinary(200) not null, "
+ " value_ blob, primary key(key_, version_)) engine = InnoDB");
}
public void execute(String query) {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = datasource.getConnection();
stmt = conn.prepareStatement(query);
stmt.executeUpdate();
} catch(SQLException e) {
throw new PersistenceFailureException("SQLException while performing operation.", e);
} finally {
tryClose(stmt);
tryClose(conn);
}
}
public ClosableIterator<Entry<ByteArray, Versioned<byte[]>>> entries() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String select = "select key_, version_, value_ from " + name;
try {
conn = datasource.getConnection();
stmt = conn.prepareStatement(select);
rs = stmt.executeQuery();
return new MysqlClosableIterator(conn, stmt, rs);
} catch(SQLException e) {
throw new PersistenceFailureException("Fix me!", e);
}
}
public void close() throws PersistenceFailureException {
// don't close datasource cause others could be using it
}
public boolean delete(ByteArray key, Version maxVersion) throws PersistenceFailureException {
StoreUtils.assertValidKey(key);
Connection conn = null;
PreparedStatement selectStmt = null;
ResultSet rs = null;
String select = "select key_, version_ from " + name + " where key_ = ? for update";
try {
conn = datasource.getConnection();
selectStmt = conn.prepareStatement(select);
selectStmt.setBytes(1, key.get());
rs = selectStmt.executeQuery();
boolean deletedSomething = false;
while(rs.next()) {
byte[] theKey = rs.getBytes("key_");
byte[] version = rs.getBytes("version_");
if(new VectorClock(version).compare(maxVersion) == Occured.BEFORE) {
delete(conn, theKey, version);
deletedSomething = true;
}
}
return deletedSomething;
} catch(SQLException e) {
throw new PersistenceFailureException("Fix me!", e);
} finally {
tryClose(rs);
tryClose(selectStmt);
tryClose(conn);
}
}
private void delete(Connection connection, byte[] key, byte[] version) throws SQLException {
String delete = "delete from " + name + " where key_ = ? and version_ = ?";
PreparedStatement deleteStmt = null;
try {
deleteStmt = connection.prepareStatement(delete);
deleteStmt.setBytes(1, key);
deleteStmt.setBytes(2, version);
deleteStmt.executeUpdate();
} finally {
tryClose(deleteStmt);
}
}
public Map<ByteArray, List<Versioned<byte[]>>> getAll(Iterable<ByteArray> keys)
throws VoldemortException {
StoreUtils.assertValidKeys(keys);
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String select = "select version_, value_ from " + name + " where key_ = ?";
try {
conn = datasource.getConnection();
stmt = conn.prepareStatement(select);
Map<ByteArray, List<Versioned<byte[]>>> result = StoreUtils.newEmptyHashMap(keys);
for(ByteArray key: keys) {
stmt.setBytes(1, key.get());
rs = stmt.executeQuery();
List<Versioned<byte[]>> found = Lists.newArrayList();
while(rs.next()) {
byte[] version = rs.getBytes("version_");
byte[] value = rs.getBytes("value_");
found.add(new Versioned<byte[]>(value, new VectorClock(version)));
}
if(found.size() > 0)
result.put(key, found);
}
return result;
} catch(SQLException e) {
throw new PersistenceFailureException("Fix me!", e);
} finally {
tryClose(rs);
tryClose(stmt);
tryClose(conn);
}
}
public List<Versioned<byte[]>> get(ByteArray key) throws PersistenceFailureException {
StoreUtils.assertValidKey(key);
return StoreUtils.get(this, key);
}
public String getName() {
return name;
}
public void put(ByteArray key, Versioned<byte[]> value) throws PersistenceFailureException {
StoreUtils.assertValidKey(key);
boolean doCommit = false;
Connection conn = null;
PreparedStatement insert = null;
PreparedStatement select = null;
ResultSet results = null;
String insertSql = "insert into " + name + " (key_, version_, value_) values (?, ?, ?)";
String selectSql = "select key_, version_ from " + name + " where key_ = ?";
try {
conn = datasource.getConnection();
conn.setAutoCommit(false);
// check for superior versions
select = conn.prepareStatement(selectSql);
select.setBytes(1, key.get());
results = select.executeQuery();
while(results.next()) {
byte[] thisKey = results.getBytes("key_");
VectorClock version = new VectorClock(results.getBytes("version_"));
Occured occured = value.getVersion().compare(version);
if(occured == Occured.BEFORE)
throw new ObsoleteVersionException("Attempt to put version "
+ value.getVersion()
+ " which is superceeded by " + version
+ ".");
else if(occured == Occured.AFTER)
delete(conn, thisKey, version.toBytes());
}
// Okay, cool, now put the value
insert = conn.prepareStatement(insertSql);
insert.setBytes(1, key.get());
VectorClock clock = (VectorClock) value.getVersion();
insert.setBytes(2, clock.toBytes());
insert.setBytes(3, value.getValue());
insert.executeUpdate();
doCommit = true;
} catch(SQLException e) {
if(e.getErrorCode() == MYSQL_ERR_DUP_KEY || e.getErrorCode() == MYSQL_ERR_DUP_ENTRY) {
throw new ObsoleteVersionException("Key or value already used.");
} else {
throw new PersistenceFailureException("Fix me!", e);
}
} finally {
if(conn != null) {
try {
if(doCommit)
conn.commit();
else
conn.rollback();
} catch(SQLException e) {}
}
tryClose(results);
tryClose(insert);
tryClose(select);
tryClose(conn);
}
}
private void tryClose(ResultSet rs) {
try {
if(rs != null)
rs.close();
} catch(Exception e) {
logger.error("Failed to close resultset.", e);
}
}
private void tryClose(Connection c) {
try {
if(c != null)
c.close();
} catch(Exception e) {
logger.error("Failed to close connection.", e);
}
}
private void tryClose(PreparedStatement s) {
try {
if(s != null)
s.close();
} catch(Exception e) {
logger.error("Failed to close prepared statement.", e);
}
}
private class MysqlClosableIterator implements
ClosableIterator<Entry<ByteArray, Versioned<byte[]>>> {
private boolean hasMore;
private final ResultSet rs;
private final Connection connection;
private final PreparedStatement statement;
public MysqlClosableIterator(Connection connection,
PreparedStatement statement,
ResultSet resultSet) {
try {
// Move to the first item
this.hasMore = resultSet.next();
} catch(SQLException e) {
throw new PersistenceFailureException(e);
}
this.rs = resultSet;
this.connection = connection;
this.statement = statement;
}
public void close() {
tryClose(rs);
tryClose(statement);
tryClose(connection);
}
public boolean hasNext() {
return this.hasMore;
}
public Entry<ByteArray, Versioned<byte[]>> next() {
try {
if(!this.hasMore)
throw new PersistenceFailureException("Next called on iterator, but no more items available!");
ByteArray key = new ByteArray(rs.getBytes("key_"));
byte[] value = rs.getBytes("value_");
VectorClock clock = new VectorClock(rs.getBytes("version_"));
this.hasMore = rs.next();
return new Entry<ByteArray, Versioned<byte[]>>(key, new Versioned<byte[]>(value,
clock));
} catch(SQLException e) {
throw new PersistenceFailureException(e);
}
}
public void remove() {
try {
rs.deleteRow();
} catch(SQLException e) {
throw new PersistenceFailureException(e);
}
}
}
}
|
src/java/voldemort/store/mysql/MysqlStorageEngine.java
|
/*
* Copyright 2008-2009 LinkedIn, 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 voldemort.store.mysql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import voldemort.VoldemortException;
import voldemort.store.Entry;
import voldemort.store.PersistenceFailureException;
import voldemort.store.StorageEngine;
import voldemort.store.StoreUtils;
import voldemort.utils.ByteArray;
import voldemort.utils.ClosableIterator;
import voldemort.versioning.ObsoleteVersionException;
import voldemort.versioning.Occured;
import voldemort.versioning.VectorClock;
import voldemort.versioning.Version;
import voldemort.versioning.Versioned;
import com.google.common.collect.Lists;
/**
* A StorageEngine that uses Mysql for persistence
*
* @author jay
*
*/
public class MysqlStorageEngine implements StorageEngine<ByteArray, byte[]> {
private static final Logger logger = Logger.getLogger(MysqlStorageEngine.class);
private static int MYSQL_ERR_DUP_KEY = 1022;
private static int MYSQL_ERR_DUP_ENTRY = 1062;
private final String name;
private final DataSource datasource;
public MysqlStorageEngine(String name, DataSource datasource) {
this.name = name;
this.datasource = datasource;
if(!tableExists()) {
create();
}
}
private boolean tableExists() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String select = "show tables like '" + getName() + "'";
try {
conn = this.datasource.getConnection();
stmt = conn.prepareStatement(select);
rs = stmt.executeQuery();
return rs.next();
} catch(SQLException e) {
throw new PersistenceFailureException("SQLException while checking for table existence!",
e);
} finally {
tryClose(rs);
tryClose(stmt);
tryClose(conn);
}
}
public void destroy() {
execute("drop table if exists " + getName());
}
public void create() {
execute("create table "
+ getName()
+ " (key_ varbinary(200) not null, version_ varbinary(200) not null, value_ blob, primary key(key_, version_))");
}
public void execute(String query) {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = datasource.getConnection();
stmt = conn.prepareStatement(query);
stmt.executeUpdate();
} catch(SQLException e) {
throw new PersistenceFailureException("SQLException while performing operation.", e);
} finally {
tryClose(stmt);
tryClose(conn);
}
}
public ClosableIterator<Entry<ByteArray, Versioned<byte[]>>> entries() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String select = "select key_, version_, value_ from " + name;
try {
conn = datasource.getConnection();
stmt = conn.prepareStatement(select);
rs = stmt.executeQuery();
return new MysqlClosableIterator(conn, stmt, rs);
} catch(SQLException e) {
throw new PersistenceFailureException("Fix me!", e);
}
}
public void close() throws PersistenceFailureException {
// don't close datasource cause others could be using it
}
public boolean delete(ByteArray key, Version maxVersion) throws PersistenceFailureException {
StoreUtils.assertValidKey(key);
Connection conn = null;
PreparedStatement selectStmt = null;
ResultSet rs = null;
String select = "select key_, version_ from " + name + " where key_ = ? for update";
try {
conn = datasource.getConnection();
selectStmt = conn.prepareStatement(select);
selectStmt.setBytes(1, key.get());
rs = selectStmt.executeQuery();
boolean deletedSomething = false;
while(rs.next()) {
byte[] theKey = rs.getBytes("key_");
byte[] version = rs.getBytes("version_");
if(new VectorClock(version).compare(maxVersion) == Occured.BEFORE) {
delete(conn, theKey, version);
deletedSomething = true;
}
}
return deletedSomething;
} catch(SQLException e) {
throw new PersistenceFailureException("Fix me!", e);
} finally {
tryClose(rs);
tryClose(selectStmt);
tryClose(conn);
}
}
private void delete(Connection connection, byte[] key, byte[] version) throws SQLException {
String delete = "delete from " + name + " where key_ = ? and version_ = ?";
PreparedStatement deleteStmt = null;
try {
deleteStmt = connection.prepareStatement(delete);
deleteStmt.setBytes(1, key);
deleteStmt.setBytes(2, version);
deleteStmt.executeUpdate();
} finally {
tryClose(deleteStmt);
}
}
public Map<ByteArray, List<Versioned<byte[]>>> getAll(Iterable<ByteArray> keys)
throws VoldemortException {
StoreUtils.assertValidKeys(keys);
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String select = "select version_, value_ from " + name + " where key_ = ?";
try {
conn = datasource.getConnection();
stmt = conn.prepareStatement(select);
Map<ByteArray, List<Versioned<byte[]>>> result = StoreUtils.newEmptyHashMap(keys);
for(ByteArray key: keys) {
stmt.setBytes(1, key.get());
rs = stmt.executeQuery();
List<Versioned<byte[]>> found = Lists.newArrayList();
while(rs.next()) {
byte[] version = rs.getBytes("version_");
byte[] value = rs.getBytes("value_");
found.add(new Versioned<byte[]>(value, new VectorClock(version)));
}
if(found.size() > 0)
result.put(key, found);
}
return result;
} catch(SQLException e) {
throw new PersistenceFailureException("Fix me!", e);
} finally {
tryClose(rs);
tryClose(stmt);
tryClose(conn);
}
}
public List<Versioned<byte[]>> get(ByteArray key) throws PersistenceFailureException {
StoreUtils.assertValidKey(key);
return StoreUtils.get(this, key);
}
public String getName() {
return name;
}
public void put(ByteArray key, Versioned<byte[]> value) throws PersistenceFailureException {
StoreUtils.assertValidKey(key);
boolean doCommit = false;
Connection conn = null;
PreparedStatement insert = null;
PreparedStatement select = null;
ResultSet results = null;
String insertSql = "insert into " + name + " (key_, version_, value_) values (?, ?, ?)";
String selectSql = "select key_, version_ from " + name + " where key_ = ?";
try {
conn = datasource.getConnection();
conn.setAutoCommit(false);
// check for superior versions
select = conn.prepareStatement(selectSql);
select.setBytes(1, key.get());
results = select.executeQuery();
while(results.next()) {
byte[] thisKey = results.getBytes("key_");
VectorClock version = new VectorClock(results.getBytes("version_"));
Occured occured = value.getVersion().compare(version);
if(occured == Occured.BEFORE)
throw new ObsoleteVersionException("Attempt to put version "
+ value.getVersion()
+ " which is superceeded by " + version
+ ".");
else if(occured == Occured.AFTER)
delete(conn, thisKey, version.toBytes());
}
// Okay, cool, now put the value
insert = conn.prepareStatement(insertSql);
insert.setBytes(1, key.get());
VectorClock clock = (VectorClock) value.getVersion();
insert.setBytes(2, clock.toBytes());
insert.setBytes(3, value.getValue());
insert.executeUpdate();
} catch(SQLException e) {
if(e.getErrorCode() == MYSQL_ERR_DUP_KEY || e.getErrorCode() == MYSQL_ERR_DUP_ENTRY) {
throw new ObsoleteVersionException("Key or value already used.");
} else {
throw new PersistenceFailureException("Fix me!", e);
}
} finally {
if(conn != null) {
try {
if(doCommit)
conn.commit();
else
conn.rollback();
} catch(SQLException e) {}
}
tryClose(results);
tryClose(insert);
tryClose(select);
tryClose(conn);
}
}
private void tryClose(ResultSet rs) {
try {
if(rs != null)
rs.close();
} catch(Exception e) {
logger.error("Failed to close resultset.", e);
}
}
private void tryClose(Connection c) {
try {
if(c != null)
c.close();
} catch(Exception e) {
logger.error("Failed to close connection.", e);
}
}
private void tryClose(PreparedStatement s) {
try {
if(s != null)
s.close();
} catch(Exception e) {
logger.error("Failed to close prepared statement.", e);
}
}
private class MysqlClosableIterator implements
ClosableIterator<Entry<ByteArray, Versioned<byte[]>>> {
private boolean hasMore;
private final ResultSet rs;
private final Connection connection;
private final PreparedStatement statement;
public MysqlClosableIterator(Connection connection,
PreparedStatement statement,
ResultSet resultSet) {
try {
// Move to the first item
this.hasMore = resultSet.next();
} catch(SQLException e) {
throw new PersistenceFailureException(e);
}
this.rs = resultSet;
this.connection = connection;
this.statement = statement;
}
public void close() {
tryClose(rs);
tryClose(statement);
tryClose(connection);
}
public boolean hasNext() {
return this.hasMore;
}
public Entry<ByteArray, Versioned<byte[]>> next() {
try {
if(!this.hasMore)
throw new PersistenceFailureException("Next called on iterator, but no more items available!");
ByteArray key = new ByteArray(rs.getBytes("key_"));
byte[] value = rs.getBytes("value_");
VectorClock clock = new VectorClock(rs.getBytes("version_"));
this.hasMore = rs.next();
return new Entry<ByteArray, Versioned<byte[]>>(key, new Versioned<byte[]>(value,
clock));
} catch(SQLException e) {
throw new PersistenceFailureException(e);
}
}
public void remove() {
try {
rs.deleteRow();
} catch(SQLException e) {
throw new PersistenceFailureException(e);
}
}
}
}
|
Fix transactional bug in mysql--transaction must be committed.
|
src/java/voldemort/store/mysql/MysqlStorageEngine.java
|
Fix transactional bug in mysql--transaction must be committed.
|
|
Java
|
apache-2.0
|
7b0a9478f32bf05af4ce5e1d3c584ff3dbbbe262
| 0
|
b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl
|
/*
* Copyright 2011-2020 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.test.commons.snomed;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import org.eclipse.emf.common.util.WrappedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.b2international.commons.ReflectionUtils;
import com.b2international.commons.options.MetadataImpl;
import com.b2international.index.es.client.EsIndexStatus;
import com.b2international.index.revision.RevisionBranch.BranchState;
import com.b2international.snowowl.core.ServiceProvider;
import com.b2international.snowowl.core.api.IBranchPath;
import com.b2international.snowowl.core.branch.Branch;
import com.b2international.snowowl.core.branch.BranchPathUtils;
import com.b2international.snowowl.core.config.SnowOwlConfiguration;
import com.b2international.snowowl.core.domain.BranchContext;
import com.b2international.snowowl.core.domain.DelegatingContext;
import com.b2international.snowowl.core.domain.RepositoryContext;
import com.b2international.snowowl.core.domain.RepositoryContextProvider;
import com.b2international.snowowl.core.events.DelegatingRequest;
import com.b2international.snowowl.core.events.Request;
import com.b2international.snowowl.core.request.BranchRequest;
import com.b2international.snowowl.core.request.CodeSystemResourceRequest;
import com.b2international.snowowl.eventbus.EventBusUtil;
import com.b2international.snowowl.eventbus.IEventBus;
/**
* @since 6.4
*/
public final class TestBranchContext extends DelegatingContext implements BranchContext, RepositoryContextProvider {
private final String repositoryId;
private final Branch branch;
private TestBranchContext(String repositoryId, Branch branch) {
super(ServiceProvider.EMPTY);
this.repositoryId = repositoryId;
this.branch = branch;
}
@Override
public RepositoryContext getContext(String repositoryId) {
return this;
}
@Override
public Logger log() {
return LoggerFactory.getLogger(repositoryId);
}
@Override
public Branch branch() {
return branch;
}
@Override
public String path() {
return branch.path();
}
@Override
public SnowOwlConfiguration config() {
return service(SnowOwlConfiguration.class);
}
@Override
public String id() {
return repositoryId;
}
@Override
public Health health() {
return Health.GREEN;
}
@Override
public List<EsIndexStatus> indices() {
return Collections.emptyList();
}
public static TestBranchContext.Builder on(String branch) {
return new TestBranchContext.Builder(branch);
}
public static class Builder {
private TestBranchContext context;
Builder(String branch) {
final String repositoryId = UUID.randomUUID().toString();
IBranchPath branchPath = BranchPathUtils.createPath(branch);
final Branch mockBranch = new Branch(1L, branchPath.lastSegment(), branchPath.getParentPath(), 0L, 1L, false, new MetadataImpl(), BranchState.FORWARD, branchPath, Collections.emptyList());
context = new TestBranchContext(repositoryId, mockBranch);
final IEventBus bus = EventBusUtil.getDirectBus(repositoryId);
bus.registerHandler(Request.ADDRESS, message -> {
try {
final Request<?, ?> req = message.body(Request.class);
final BranchRequest<?> branchReq = Request.getNestedRequest(req, BranchRequest.class);
final CodeSystemResourceRequest<?> codeSystemResourceRequest = Request.getNestedRequest(req, CodeSystemResourceRequest.class);
final Request<BranchContext, ?> innerReq = branchReq != null ? ReflectionUtils.getField(DelegatingRequest.class, branchReq, "next") : ReflectionUtils.getField(DelegatingRequest.class, codeSystemResourceRequest, "next");
message.reply(innerReq.execute(context));
} catch (WrappedException e1) {
message.fail(e1.getCause());
} catch (Throwable e2) {
message.fail(e2);
}
});
with(IEventBus.class, bus);
with(RepositoryContextProvider.class, context);
}
public <T> Builder with(Class<T> type, T object) {
context.bind(type, object);
return this;
}
public BranchContext build() {
return context;
}
}
}
|
tests/com.b2international.snowowl.test.commons/src/com/b2international/snowowl/test/commons/snomed/TestBranchContext.java
|
/*
* Copyright 2011-2020 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.test.commons.snomed;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import org.eclipse.emf.common.util.WrappedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.b2international.commons.ReflectionUtils;
import com.b2international.commons.options.MetadataImpl;
import com.b2international.index.es.client.EsIndexStatus;
import com.b2international.index.revision.RevisionBranch.BranchState;
import com.b2international.snowowl.core.ServiceProvider;
import com.b2international.snowowl.core.api.IBranchPath;
import com.b2international.snowowl.core.branch.Branch;
import com.b2international.snowowl.core.branch.BranchPathUtils;
import com.b2international.snowowl.core.config.SnowOwlConfiguration;
import com.b2international.snowowl.core.domain.BranchContext;
import com.b2international.snowowl.core.domain.DelegatingContext;
import com.b2international.snowowl.core.domain.RepositoryContext;
import com.b2international.snowowl.core.domain.RepositoryContextProvider;
import com.b2international.snowowl.core.events.DelegatingRequest;
import com.b2international.snowowl.core.events.Request;
import com.b2international.snowowl.core.request.BranchRequest;
import com.b2international.snowowl.core.request.HealthCheckingRequest;
import com.b2international.snowowl.core.request.RepositoryRequest;
import com.b2international.snowowl.eventbus.EventBusUtil;
import com.b2international.snowowl.eventbus.IEventBus;
/**
* @since 6.4
*/
public final class TestBranchContext extends DelegatingContext implements BranchContext, RepositoryContextProvider {
private final String repositoryId;
private final Branch branch;
private TestBranchContext(String repositoryId, Branch branch) {
super(ServiceProvider.EMPTY);
this.repositoryId = repositoryId;
this.branch = branch;
}
@Override
public RepositoryContext getContext(String repositoryId) {
return this;
}
@Override
public Logger log() {
return LoggerFactory.getLogger(repositoryId);
}
@Override
public Branch branch() {
return branch;
}
@Override
public String path() {
return branch.path();
}
@Override
public SnowOwlConfiguration config() {
return service(SnowOwlConfiguration.class);
}
@Override
public String id() {
return repositoryId;
}
@Override
public Health health() {
return Health.GREEN;
}
@Override
public List<EsIndexStatus> indices() {
return Collections.emptyList();
}
public static TestBranchContext.Builder on(String branch) {
return new TestBranchContext.Builder(branch);
}
public static class Builder {
private TestBranchContext context;
Builder(String branch) {
final String repositoryId = UUID.randomUUID().toString();
IBranchPath branchPath = BranchPathUtils.createPath(branch);
final Branch mockBranch = new Branch(1L, branchPath.lastSegment(), branchPath.getParentPath(), 0L, 1L, false, new MetadataImpl(), BranchState.FORWARD, branchPath, Collections.emptyList());
context = new TestBranchContext(repositoryId, mockBranch);
final IEventBus bus = EventBusUtil.getDirectBus(repositoryId);
bus.registerHandler(Request.ADDRESS, message -> {
try {
final RepositoryRequest<?> repoReq = message.body(RepositoryRequest.class);
final HealthCheckingRequest<?> healthReq = ReflectionUtils.getField(DelegatingRequest.class, repoReq, "next");
final BranchRequest<?> branchReq = ReflectionUtils.getField(DelegatingRequest.class, healthReq, "next");
final Request<BranchContext, ?> innerReq = ReflectionUtils.getField(DelegatingRequest.class, branchReq, "next");
message.reply(innerReq.execute(context));
} catch (WrappedException e1) {
message.fail(e1.getCause());
} catch (Throwable e2) {
message.fail(e2);
}
});
with(IEventBus.class, bus);
with(RepositoryContextProvider.class, context);
}
public <T> Builder with(Class<T> type, T object) {
context.bind(type, object);
return this;
}
public BranchContext build() {
return context;
}
}
}
|
[tests] support generic CodeSystemResourceRequest in TestBranchContext
|
tests/com.b2international.snowowl.test.commons/src/com/b2international/snowowl/test/commons/snomed/TestBranchContext.java
|
[tests] support generic CodeSystemResourceRequest in TestBranchContext
|
|
Java
|
apache-2.0
|
cfe13deccd451fa38a7b26f8e5a2821b91c3dcc0
| 0
|
apache/felix-dev,apache/felix-dev,apache/felix-dev,apache/felix-dev
|
/*
* 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.felix.dm.impl.dependencies;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.apache.felix.dm.dependencies.ConfigurationDependency;
import org.apache.felix.dm.dependencies.Dependency;
import org.apache.felix.dm.dependencies.ServiceDependency;
import org.apache.felix.dm.impl.Logger;
import org.apache.felix.dm.management.ServiceComponentDependency;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
/**
* Configuration dependency that can track the availability of a (valid) configuration.
* To use it, specify a PID for the configuration. The dependency is always required,
* because if it is not, it does not make sense to use the dependency manager. In that
* scenario, simply register your service as a <code>ManagedService(Factory)</code> and
* handle everything yourself. Also, only managed services are supported, not factories.
* There are a couple of things you need to be aware of when implementing the
* <code>updated(Dictionary)</code> method:
* <ul>
* <li>Make sure it throws a <code>ConfigurationException</code> when you get a
* configuration that is invalid. In this case, the dependency will not change:
* if it was not available, it will still not be. If it was available, it will
* remain available and implicitly assume you keep working with your old
* configuration.</li>
* <li>This method will be called before all required dependencies are available.
* Make sure you do not depend on these to parse your settings.</li>
* </ul>
*
* @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
*/
public class ConfigurationDependencyImpl implements ConfigurationDependency, ManagedService, ServiceComponentDependency, DependencyActivation {
private BundleContext m_context;
private String m_pid;
private ServiceRegistration m_registration;
protected List m_services = new ArrayList();
private Dictionary m_settings;
private boolean m_propagate;
private final Logger m_logger;
private String m_callback;
private boolean m_isStarted;
private final Set m_updateInvokedCache = new HashSet();
public ConfigurationDependencyImpl(BundleContext context, Logger logger) {
m_context = context;
m_logger = logger;
}
public synchronized boolean isAvailable() {
return m_settings != null;
}
/**
* Will always return <code>true</code> as optional configuration dependencies
* do not make sense. You might as well just implement <code>ManagedService</code>
* yourself in those cases.
*/
public boolean isRequired() {
return true;
}
public boolean isInstanceBound() {
// for now, configuration dependencies never are
return false;
}
/**
* Returns <code>true</code> when configuration properties should be propagated
* as service properties.
*/
public boolean isPropagated() {
return m_propagate;
}
public Dictionary getConfiguration() {
return m_settings;
}
public void start(DependencyService service) {
boolean needsStarting = false;
synchronized (this) {
m_services.add(service);
if (!m_isStarted) {
m_isStarted = true;
needsStarting = true;
}
}
if (needsStarting) {
Properties props = new Properties();
props.put(Constants.SERVICE_PID, m_pid);
m_registration = m_context.registerService(ManagedService.class.getName(), this, props);
}
}
public void stop(DependencyService service) {
boolean needsStopping = false;
synchronized (this) {
if (m_services.size() == 1 && m_services.contains(service)) {
m_isStarted = false;
needsStopping = true;
}
}
if (needsStopping) {
m_registration.unregister();
m_registration = null;
m_services.remove(service);
}
}
public ConfigurationDependency setCallback(String callback) {
m_callback = callback;
return this;
}
public void updated(Dictionary settings) throws ConfigurationException {
m_updateInvokedCache.clear();
Dictionary oldSettings = null;
synchronized (this) {
oldSettings = m_settings;
}
if (oldSettings == null && settings == null) {
// CM has started but our configuration is not still present in the CM database: ignore
return;
}
Object[] services = m_services.toArray();
for (int i = 0; i < services.length; i++) {
DependencyService ds = (DependencyService) services[i];
// if non-null settings come in, we have to instantiate the service and
// apply these settings
ds.initService();
Object service = ds.getService();
if (service != null) {
invokeUpdate(ds, service, settings);
}
else {
m_logger.log(Logger.LOG_ERROR, "Service " + ds + " with configuration dependency " + this + " could not be instantiated.");
return;
}
}
synchronized (this) {
m_settings = settings;
}
for (int i = 0; i < services.length; i++) {
DependencyService ds = (DependencyService) services[i];
// If these settings did not cause a configuration exception, we determine if they have
// caused the dependency state to change
if ((oldSettings == null) && (settings != null)) {
ds.dependencyAvailable(this);
}
if ((oldSettings != null) && (settings == null)) {
ds.dependencyUnavailable(this);
}
if ((oldSettings != null) && (settings != null)) {
ds.dependencyChanged(this);
}
}
}
public void invokeUpdate(DependencyService ds, Object service, Dictionary settings) throws ConfigurationException {
if (m_updateInvokedCache.add(ds)) {
String callback = (m_callback == null) ? "updated" : m_callback;
Method m;
try {
m = service.getClass().getDeclaredMethod(callback, new Class[] { Dictionary.class });
m.setAccessible(true);
// if exception is thrown here, what does that mean for the
// state of this dependency? how smart do we want to be??
// it's okay like this, if the new settings contain errors, we
// remain in the state we were, assuming that any error causes
// the "old" configuration to stay in effect.
// CM will log any thrown exceptions.
m.invoke(service, new Object[] { settings });
}
catch (InvocationTargetException e) {
// The component has thrown an exception during it's callback invocation.
if (e.getTargetException() instanceof ConfigurationException) {
// the callback threw an OSGi ConfigurationException: just re-throw it.
throw (ConfigurationException) e.getTargetException();
}
else {
// wrap the callback exception into a ConfigurationException.
throw new ConfigurationException(null, "Service " + ds + " with " + this.toString() + " could not be updated", e.getTargetException());
}
}
catch (Throwable t) {
// wrap any other exception as a ConfigurationException.
throw new ConfigurationException(null, "Service " + ds + " with " + this.toString() + " could not be updated", t);
}
}
}
/**
* Sets the <code>service.pid</code> of the configuration you
* are depending on.
*/
public ConfigurationDependency setPid(String pid) {
ensureNotActive();
m_pid = pid;
return this;
}
/**
* Sets propagation of the configuration properties to the service
* properties. Any additional service properties specified directly
* are merged with these.
*/
public ConfigurationDependency setPropagate(boolean propagate) {
ensureNotActive();
m_propagate = propagate;
return this;
}
private void ensureNotActive() {
if (m_services != null && m_services.size() > 0) {
throw new IllegalStateException("Cannot modify state while active.");
}
}
public String toString() {
return "ConfigurationDependency[" + m_pid + "]";
}
public String getName() {
return m_pid;
}
public int getState() {
return (isAvailable() ? 1 : 0) + (isRequired() ? 2 : 0);
}
public String getType() {
return "configuration";
}
}
|
dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/ConfigurationDependencyImpl.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.felix.dependencymanager.dependencies;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.apache.felix.dependencymanager.Dependency;
import org.apache.felix.dependencymanager.DependencyService;
import org.apache.felix.dependencymanager.impl.Logger;
import org.apache.felix.dependencymanager.management.ServiceComponentDependency;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
/**
* Configuration dependency that can track the availability of a (valid) configuration.
* To use it, specify a PID for the configuration. The dependency is always required,
* because if it is not, it does not make sense to use the dependency manager. In that
* scenario, simply register your service as a <code>ManagedService(Factory)</code> and
* handle everything yourself. Also, only managed services are supported, not factories.
* There are a couple of things you need to be aware of when implementing the
* <code>updated(Dictionary)</code> method:
* <ul>
* <li>Make sure it throws a <code>ConfigurationException</code> when you get a
* configuration that is invalid. In this case, the dependency will not change:
* if it was not available, it will still not be. If it was available, it will
* remain available and implicitly assume you keep working with your old
* configuration.</li>
* <li>This method will be called before all required dependencies are available.
* Make sure you do not depend on these to parse your settings.</li>
* </ul>
*
* @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
*/
public class ConfigurationDependency implements Dependency, ManagedService, ServiceComponentDependency {
private BundleContext m_context;
private String m_pid;
private ServiceRegistration m_registration;
protected List m_services = new ArrayList();
private Dictionary m_settings;
private boolean m_propagate;
private final Logger m_logger;
private String m_callback;
private boolean m_isStarted;
private final Set m_updateInvokedCache = new HashSet();
public ConfigurationDependency(BundleContext context, Logger logger) {
m_context = context;
m_logger = logger;
}
public synchronized boolean isAvailable() {
return m_settings != null;
}
/**
* Will always return <code>true</code> as optional configuration dependencies
* do not make sense. You might as well just implement <code>ManagedService</code>
* yourself in those cases.
*/
public boolean isRequired() {
return true;
}
public boolean isInstanceBound() {
// for now, configuration dependencies never are
return false;
}
/**
* Returns <code>true</code> when configuration properties should be propagated
* as service properties.
*/
public boolean isPropagated() {
return m_propagate;
}
public Dictionary getConfiguration() {
return m_settings;
}
public void start(DependencyService service) {
boolean needsStarting = false;
synchronized (this) {
m_services.add(service);
if (!m_isStarted) {
m_isStarted = true;
needsStarting = true;
}
}
if (needsStarting) {
Properties props = new Properties();
props.put(Constants.SERVICE_PID, m_pid);
m_registration = m_context.registerService(ManagedService.class.getName(), this, props);
}
}
public void stop(DependencyService service) {
boolean needsStopping = false;
synchronized (this) {
if (m_services.size() == 1 && m_services.contains(service)) {
m_isStarted = false;
needsStopping = true;
}
}
if (needsStopping) {
m_registration.unregister();
m_registration = null;
m_services.remove(service);
}
}
public Dependency setCallback(String callback) {
m_callback = callback;
return this;
}
public void updated(Dictionary settings) throws ConfigurationException {
m_updateInvokedCache.clear();
Dictionary oldSettings = null;
synchronized (this) {
oldSettings = m_settings;
}
if (oldSettings == null && settings == null) {
// CM has started but our configuration is not still present in the CM database: ignore
return;
}
Object[] services = m_services.toArray();
for (int i = 0; i < services.length; i++) {
DependencyService ds = (DependencyService) services[i];
// if non-null settings come in, we have to instantiate the service and
// apply these settings
ds.initService();
Object service = ds.getService();
if (service != null) {
invokeUpdate(ds, service, settings);
}
else {
m_logger.log(Logger.LOG_ERROR, "Service " + ds + " with configuration dependency " + this + " could not be instantiated.");
return;
}
}
synchronized (this) {
m_settings = settings;
}
for (int i = 0; i < services.length; i++) {
DependencyService ds = (DependencyService) services[i];
// If these settings did not cause a configuration exception, we determine if they have
// caused the dependency state to change
if ((oldSettings == null) && (settings != null)) {
ds.dependencyAvailable(this);
}
if ((oldSettings != null) && (settings == null)) {
ds.dependencyUnavailable(this);
}
if ((oldSettings != null) && (settings != null)) {
ds.dependencyChanged(this);
}
}
}
public void invokeUpdate(DependencyService ds, Object service, Dictionary settings) throws ConfigurationException {
if (m_updateInvokedCache.add(ds)) {
String callback = (m_callback == null) ? "updated" : m_callback;
Method m;
try {
m = service.getClass().getDeclaredMethod(callback, new Class[] { Dictionary.class });
m.setAccessible(true);
// if exception is thrown here, what does that mean for the
// state of this dependency? how smart do we want to be??
// it's okay like this, if the new settings contain errors, we
// remain in the state we were, assuming that any error causes
// the "old" configuration to stay in effect.
// CM will log any thrown exceptions.
m.invoke(service, new Object[] { settings });
}
catch (InvocationTargetException e) {
// The component has thrown an exception during it's callback invocation.
if (e.getTargetException() instanceof ConfigurationException) {
// the callback threw an OSGi ConfigurationException: just re-throw it.
throw (ConfigurationException) e.getTargetException();
}
else {
// wrap the callback exception into a ConfigurationException.
throw new ConfigurationException(null, "Service " + ds + " with " + this.toString() + " could not be updated", e.getTargetException());
}
}
catch (Throwable t) {
// wrap any other exception as a ConfigurationException.
throw new ConfigurationException(null, "Service " + ds + " with " + this.toString() + " could not be updated", t);
}
}
}
/**
* Sets the <code>service.pid</code> of the configuration you
* are depending on.
*/
public ConfigurationDependency setPid(String pid) {
ensureNotActive();
m_pid = pid;
return this;
}
/**
* Sets propagation of the configuration properties to the service
* properties. Any additional service properties specified directly
* are merged with these.
*/
public ConfigurationDependency setPropagate(boolean propagate) {
ensureNotActive();
m_propagate = propagate;
return this;
}
private void ensureNotActive() {
if (m_services != null && m_services.size() > 0) {
throw new IllegalStateException("Cannot modify state while active.");
}
}
public String toString() {
return "ConfigurationDependency[" + m_pid + "]";
}
public String getName() {
return m_pid;
}
public int getState() {
return (isAvailable() ? 1 : 0) + (isRequired() ? 2 : 0);
}
public String getType() {
return "configuration";
}
}
|
renamed package to org.apache.felix.dm.impl.dependencies; the setCallback method returns now a ConfigurationDependency instead of a Dependency
git-svn-id: e057f57e93a604d3b43d277ae69bde5ebf332112@887412 13f79535-47bb-0310-9956-ffa450edef68
|
dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/ConfigurationDependencyImpl.java
|
renamed package to org.apache.felix.dm.impl.dependencies; the setCallback method returns now a ConfigurationDependency instead of a Dependency
|
|
Java
|
apache-2.0
|
24f691d7d75afb986acc0f78ff6872e35c6c032d
| 0
|
ChristianWulf/teetime,ChristianWulf/teetime,teetime-framework/teetime,teetime-framework/teetime
|
/**
* Copyright (C) 2015 Christian Wulf, Nelson Tavares de Sousa (http://christianwulf.github.io/teetime)
*
* 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 teetime.framework.signal;
import java.util.List;
import java.util.Set;
import teetime.framework.InputPort;
import teetime.framework.Stage;
public final class StartingSignal implements ISignal {
@Override
public void trigger(final Stage stage) throws Exception {
stage.onStarting();
}
@Override
public boolean mayBeTriggered(final Set<InputPort<?>> receivedInputPorts, final List<InputPort<?>> allInputPorts) {
return receivedInputPorts.size() == 1;
}
}
|
src/main/java/teetime/framework/signal/StartingSignal.java
|
/**
* Copyright (C) 2015 Christian Wulf, Nelson Tavares de Sousa (http://christianwulf.github.io/teetime)
*
* 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 teetime.framework.signal;
import java.util.List;
import java.util.Set;
import teetime.framework.InputPort;
import teetime.framework.Stage;
public final class StartingSignal implements ISignal {
@Override
public void trigger(final Stage stage) throws Exception {
stage.onStarting();
}
@Override
public boolean mayBeTriggered(final Set<InputPort<?>> receivedInputPorts, final List<InputPort<?>> allInputPorts) {
return true;
}
}
|
StartingSignal will only be passed on on the first occurrence
|
src/main/java/teetime/framework/signal/StartingSignal.java
|
StartingSignal will only be passed on on the first occurrence
|
|
Java
|
apache-2.0
|
5361c14e49336d0d64b73f1e6b19dd3424249394
| 0
|
slide-lig/TopPI,slide-lig/TopPI
|
package fr.liglab.lcm.tests;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import fr.liglab.lcm.internals.ItemsetsFactory;
public class ItemsetsFactoryTest {
ItemsetsFactory factory;
@Before
public void setUp() throws Exception {
factory = new ItemsetsFactory();
}
@After
public void tearDown() throws Exception {
factory = null;
}
@Test
public void testEmpty() {
assertTrue(factory.isEmpty());
int[] result = factory.get();
assertEquals(0, result.length);
factory.add(1);
assertFalse(factory.isEmpty());
}
@Test
public void testBuildingAndOrdering() {
for (int i = 0; i < 10; i++) {
factory.add(i);
}
int[] result = factory.get();
assertEquals(10, result.length);
for (int i = 0; i < 10; i++) {
assertEquals(i, result[i]);
}
}
@Test
public void testLooooongArray() {
for (int i = 10000; i > 0; i--) {
factory.add(i);
}
int[] result = factory.get();
assertEquals(10000, result.length);
assertEquals(10000, result[0]);
assertEquals(1, result[result.length-1]);
}
@Test
public void testMultipleInstanciations() {
int[] result = factory.get();
assertEquals(0, result.length);
factory.add(1);
result = factory.get();
assertEquals(1, result.length);
assertEquals(1, result[0]);
testLooooongArray();
testBuildingAndOrdering();
}
}
|
src/test/java/fr/liglab/lcm/tests/ItemsetsFactoryTest.java
|
package fr.liglab.lcm.tests;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import fr.liglab.lcm.internals.ItemsetsFactory;
public class ItemsetsFactoryTest {
ItemsetsFactory factory;
@Before
public void setUp() throws Exception {
factory = new ItemsetsFactory();
}
@After
public void tearDown() throws Exception {
factory = null;
}
@Test
public void testEmpty() {
assertTrue(factory.isEmpty());
int[] result = factory.get();
assertEquals(0, result.length);
factory.add(1);
assertFalse(factory.isEmpty());
}
@Test
public void testBuildingAndOrdering() {
for (int i = 0; i < 10; i++) {
factory.add(i);
}
int[] result = factory.get();
assertEquals(10, result.length);
for (int i = 0; i < 10; i++) {
assertEquals(i, result[i]);
}
}
@Test
public void testLooooongArray() {
for (int i = 10000; i > 0; i--) {
factory.add(i);
}
int[] result = factory.get();
assertEquals(10000, result.length);
assertEquals(10000, result[0]);
assertEquals(1, result[result.length-1]);
}
}
|
one more ItemsetsFactoryTest
|
src/test/java/fr/liglab/lcm/tests/ItemsetsFactoryTest.java
|
one more ItemsetsFactoryTest
|
|
Java
|
apache-2.0
|
a85b121bc686f886c5fbde77eccffce9f00b3fcf
| 0
|
Orange-OpenSource/ATK,Orange-OpenSource/ATK,Orange-OpenSource/ATK,Orange-OpenSource/ATK
|
/*
* Software Name : ATK
*
* Copyright (C) 2007 - 2012 France Télécom
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ------------------------------------------------------------------
* File Name : AutomaticPhoneDetection.java
*
* Created : 30/10/2009
* Author(s) : Yvain Leyral
*/
package com.orange.atk.phone.detection;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
import com.orange.atk.atkUI.corecli.Configuration;
import com.orange.atk.error.ErrorManager;
import com.orange.atk.internationalization.ResourceManager;
import com.orange.atk.phone.DefaultPhone;
import com.orange.atk.phone.PhoneException;
import com.orange.atk.phone.PhoneInterface;
import com.orange.atk.phone.android.AndroidDriver;
import com.orange.atk.phone.android.AndroidICSDriver;
import com.orange.atk.phone.android.AndroidJBDriver;
import com.orange.atk.phone.android.AndroidMonkeyDriver;
import com.orange.atk.phone.android.AndroidPhone;
import com.orange.atk.platform.Platform;
public class AutomaticPhoneDetection {
//singleton pattern
private PhoneInterface selectedPhone= null;
private List<PhoneInterface> connectedDevices;
private DeviceDetectionThread deviceDetectionThread;
private AndroidDebugBridge bridge;
private List<DeviceDetectionListener> deviceDetectionListeners = new ArrayList<DeviceDetectionListener>();
private static AutomaticPhoneDetection instance=null;
private static String adbLocation;
private static String defaultAdbLocation = Platform.getInstance().getDefaultADBLocation();
private boolean launchThread = true;
public static AutomaticPhoneDetection getInstance(){
return AutomaticPhoneDetection.getInstance(true);
}
public static AutomaticPhoneDetection getInstance(boolean launchThread){
if(instance ==null) {
instance = new AutomaticPhoneDetection(launchThread);
}
return instance;
}
//default constructor
private AutomaticPhoneDetection(boolean launchThread) {
if (launchThread) {
deviceDetectionThread = new DeviceDetectionThread();
deviceDetectionThread.start();
}
connectedDevices = new ArrayList<PhoneInterface>();
}
public void addDeviceDetectionListener(DeviceDetectionListener listener) {
deviceDetectionListeners.add(listener);
}
public void pauseDetection() {
if(deviceDetectionThread!=null){
deviceDetectionThread.pauseDetection();
}
}
public void resumeDetection() {
if(deviceDetectionThread!=null){
deviceDetectionThread.resumeDetection();
}
}
public void stopDetection(DeviceDetectionListener listener) {
deviceDetectionListeners.remove(listener);
if (deviceDetectionListeners.size()<=1){
deviceDetectionThread.exit();
close();
}
}
/**
* Fabric which return the phone currently connected to the PC
* @return phoneInterface. It allows communicate with the phone detected.
*/
public PhoneInterface getDevice()
{
if (selectedPhone==null) return new DefaultPhone();
return selectedPhone;
}
public List<PhoneInterface> getDevices(){
synchronized (connectedDevices) {
List<PhoneInterface> connectedEnabledDevices = new ArrayList<PhoneInterface>();
for (int i=0; i<connectedDevices.size(); i++) {
if (connectedDevices.get(i) instanceof AndroidPhone) {
if (!((AndroidPhone) connectedDevices.get(i)).isDisabledPhone()) {
connectedEnabledDevices.add(connectedDevices.get(i));
}
}
else {
connectedEnabledDevices.add(connectedDevices.get(i));
}
}
return connectedEnabledDevices;
}
}
public void setSelectedDevice(PhoneInterface phone) {
if (phone != selectedPhone) {
selectedPhone = phone;
for (int i=0; i<deviceDetectionListeners.size(); i++) {
deviceDetectionListeners.get(i).deviceSelectedChanged();
}
}
}
@SuppressWarnings("unchecked")
public void checkDevices() {
boolean changed = false;
List<PhoneInterface> newConnectedDevices = new ArrayList<PhoneInterface>();
//ANDROID Devices detection
IDevice[] androidDevices = initddmlib();
for (int i=0 ; i<androidDevices.length ; i++) {
IDevice androidDevice = androidDevices[i];
if (androidDevice.isOnline()) {
boolean found = false;
for (int j=0; j<connectedDevices.size(); j++) {
PhoneInterface phone = connectedDevices.get(j);
String uid = AndroidPhone.getUID(androidDevice);
String connectedPhoneUid = phone.getUID();
if (connectedPhoneUid!=null && connectedPhoneUid.equals(uid)) {
found = true;
newConnectedDevices.add(phone);
if (phone.getCnxStatus()!=PhoneInterface.CNX_STATUS_AVAILABLE) {
phone.setCnxStatus(PhoneInterface.CNX_STATUS_AVAILABLE);
changed = true;
if(phone instanceof AndroidMonkeyDriver){
Logger.getLogger(this.getClass()).info("refresh ddmlib handler for MonkeyDriver enabled device");
try {
((AndroidMonkeyDriver)phone).setDevice(androidDevice);
} catch (PhoneException e) {
Logger.getLogger(this.getClass()).error("unable to refresh ddmlib handler");
}
}
}
}
}
if (!found) {
String vendor = AndroidPhone.getVendor(androidDevice);
if (vendor!=null) vendor = vendor.toLowerCase();
String model = AndroidPhone.getModel(androidDevice);
String version = "";
version = AndroidPhone.getVersion(androidDevice);
if (model!=null) model = model.toLowerCase();
if(vendor!=null && model!=null){
PhoneInterface newPhone;
try {
float v=Float.parseFloat(version.substring(0, 3));
Logger.getLogger(this.getClass()).info(v);
if ( v >= 2.0f){
if (v >= 4.0f){
if (v >= 4.1f){
Logger.getLogger(this.getClass()).info("Android Jelly bean detected !");
newPhone = new AndroidJBDriver(vendor+"_"+model, version, androidDevice);
}else{
Logger.getLogger(this.getClass()).info("Android ICS detected !");
newPhone = new AndroidICSDriver(vendor+"_"+model, version, androidDevice);
}
}else{
newPhone = new AndroidMonkeyDriver(vendor+"_"+model, version, androidDevice);
}
}else{
newPhone = new AndroidDriver(vendor+"_"+model, version, androidDevice);
}
newPhone.setCnxStatus(PhoneInterface.CNX_STATUS_AVAILABLE);
newConnectedDevices.add(newPhone);
Logger.getLogger(this.getClass()).info("New phone "+newPhone.getName()+" connected");
if (!((AndroidPhone)newPhone).isDisabledPhone()) changed = true;
} catch (PhoneException e) {
// NOTHING TO DO HERE
}
} else {
PhoneInterface newPhone = new AndroidPhone(androidDevice);
newPhone.setCnxStatus(PhoneInterface.CNX_STATUS_AVAILABLE);
newConnectedDevices.add(newPhone);
Logger.getLogger(this.getClass()).info("New phone "+newPhone.getName()+" connected");
changed = true;
}
}
}
}
synchronized(connectedDevices) {
// the devices not present in newConnectedDevices are the one that have been disconnected
for (int i=connectedDevices.size()-1; i>=0; i--) {
PhoneInterface phone = connectedDevices.get(i);
if (!newConnectedDevices.contains(phone)) {
if (phone.getCnxStatus()!=PhoneInterface.CNX_STATUS_DISCONNECTED) {
phone.setCnxStatus(PhoneInterface.CNX_STATUS_DISCONNECTED);
if (phone instanceof AndroidPhone) {
if (!((AndroidPhone)phone).isDisabledPhone()) changed = true;
} else changed = true;
}
if (phone.isInRecordingMode()) phone.stopRecordingMode();
if (phone.isInTestingMode()) phone.stopTestingMode();
if (selectedPhone != phone) {
connectedDevices.remove(phone);
if (phone instanceof AndroidPhone) {
if (!((AndroidPhone)phone).isDisabledPhone()) changed = true;
} else changed = true;
}
} else newConnectedDevices.remove(phone);
}
// add the new device connected to the list
for (int i=0; i<newConnectedDevices.size(); i++) {
PhoneInterface phone = newConnectedDevices.get(i);
connectedDevices.add(phone);
}
}
if (changed) notifyDevicesConnectedChanged();
}
public void notifyDevicesConnectedChanged() {
for (int i=0; i<deviceDetectionListeners.size(); i++) {
deviceDetectionListeners.get(i).devicesConnectedChanged();
}
}
/**
* Detect if actual phone is a nokia phone
* @return true if phone connected is a nokia.
*/
public Boolean isNokia(){
//update device
getDevice();
if (selectedPhone!=null) return (selectedPhone.getType() == PhoneInterface.TYPE_S60) ;
else return false;
}
/**
* Use adb location set by user in com.android.screenshot.bindir properties
* or use default location (<i>Install_dir</i>/AndroidTools/adb.exe)
* @return null or Device detected
*/
public IDevice[] initddmlib() {
String newAdbLocation = null;
if (Boolean.valueOf(Configuration.getProperty(Configuration.SPECIFICADB, "false")))
newAdbLocation = Configuration.getProperty(Configuration.ADBPATH)+ Platform.FILE_SEPARATOR+"adb";
else newAdbLocation = defaultAdbLocation;
if (bridge==null || !newAdbLocation.equals(adbLocation)) {
Logger.getLogger(this.getClass()).debug("Initializing ADB bridge : "+newAdbLocation);
adbLocation = newAdbLocation;
if (bridge!=null) AndroidDebugBridge.disconnectBridge();
AndroidDebugBridge.init(false /* debugger support */);
bridge = AndroidDebugBridge.getBridge();
if (bridge==null) bridge = AndroidDebugBridge.createBridge(adbLocation, true );
if (bridge==null) Logger.getLogger(this.getClass()).debug("bridge is null");
//AndroidDebugBridge bridge = AndroidDebugBridge.createBridge(adbLocation, false /* forceNewBridge */);
// we can't just ask for the device list right away, as the internal thread getting
// them from ADB may not be done getting the first list.
// Since we don't really want getDevices() to be blocking, we wait here manually.
int count = 0;
while (bridge.hasInitialDeviceList() == false) {
try {
Thread.sleep(100);
count++;
} catch (InterruptedException e) { }
// let's not wait > 10 sec.
if (count > 100) {
Logger.getLogger(this.getClass() ).warn("Timeout getting device list!");
return new IDevice[0];
}
}
}
return bridge.getDevices();
}
/**
* Search the config file path of the phone in parameters.
* prefer use {@link #getxmlfilepath()}.
*
* @param phoneDefault the phone to find the config file
* @return the config file path
*/
public String getxmlfilepath()
{
String JATKpath = Platform.getInstance().getJATKPath();
String xmlconfilepath = JATKpath+Platform.FILE_SEPARATOR+"ConfigFiles"+Platform.FILE_SEPARATOR;
// Test to determine which config file to use
PhoneInterface phone = AutomaticPhoneDetection.getInstance().getDevice();
if (phone != null) {
xmlconfilepath += phone.getConfigFile();
}
return xmlconfilepath;
}
public String getADBLocation() {
return adbLocation;
}
/**
* close all fabric (like androidDebugBridge)
*/
private void close() {
if (bridge!=null) AndroidDebugBridge.terminate();
}
}
|
src/com/orange/atk/phone/detection/AutomaticPhoneDetection.java
|
/*
* Software Name : ATK
*
* Copyright (C) 2007 - 2012 France Télécom
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ------------------------------------------------------------------
* File Name : AutomaticPhoneDetection.java
*
* Created : 30/10/2009
* Author(s) : Yvain Leyral
*/
package com.orange.atk.phone.detection;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
import com.orange.atk.atkUI.corecli.Configuration;
import com.orange.atk.error.ErrorManager;
import com.orange.atk.internationalization.ResourceManager;
import com.orange.atk.phone.DefaultPhone;
import com.orange.atk.phone.PhoneException;
import com.orange.atk.phone.PhoneInterface;
import com.orange.atk.phone.android.AndroidDriver;
import com.orange.atk.phone.android.AndroidICSDriver;
import com.orange.atk.phone.android.AndroidJBDriver;
import com.orange.atk.phone.android.AndroidMonkeyDriver;
import com.orange.atk.phone.android.AndroidPhone;
import com.orange.atk.platform.Platform;
public class AutomaticPhoneDetection {
//singleton pattern
private PhoneInterface selectedPhone= null;
private List<PhoneInterface> connectedDevices;
private DeviceDetectionThread deviceDetectionThread;
private AndroidDebugBridge bridge;
private List<DeviceDetectionListener> deviceDetectionListeners = new ArrayList<DeviceDetectionListener>();
private static AutomaticPhoneDetection instance=null;
private static String adbLocation;
private static String defaultAdbLocation = Platform.getInstance().getDefaultADBLocation();
private boolean launchThread = true;
public static AutomaticPhoneDetection getInstance(){
return AutomaticPhoneDetection.getInstance(true);
}
public static AutomaticPhoneDetection getInstance(boolean launchThread){
if(instance ==null) {
instance = new AutomaticPhoneDetection(launchThread);
}
return instance;
}
//default constructor
private AutomaticPhoneDetection(boolean launchThread) {
if (launchThread) {
deviceDetectionThread = new DeviceDetectionThread();
deviceDetectionThread.start();
}
connectedDevices = new ArrayList<PhoneInterface>();
}
public void addDeviceDetectionListener(DeviceDetectionListener listener) {
deviceDetectionListeners.add(listener);
}
public void pauseDetection() {
if(deviceDetectionThread!=null){
deviceDetectionThread.pauseDetection();
}
}
public void resumeDetection() {
if(deviceDetectionThread!=null){
deviceDetectionThread.resumeDetection();
}
}
public void stopDetection(DeviceDetectionListener listener) {
deviceDetectionListeners.remove(listener);
if (deviceDetectionListeners.size()<=1){
deviceDetectionThread.exit();
close();
}
}
/**
* Fabric which return the phone currently connected to the PC
* @return phoneInterface. It allows communicate with the phone detected.
*/
public PhoneInterface getDevice()
{
if (selectedPhone==null) return new DefaultPhone();
return selectedPhone;
}
public List<PhoneInterface> getDevices(){
synchronized (connectedDevices) {
List<PhoneInterface> connectedEnabledDevices = new ArrayList<PhoneInterface>();
for (int i=0; i<connectedDevices.size(); i++) {
if (connectedDevices.get(i) instanceof AndroidPhone) {
if (!((AndroidPhone) connectedDevices.get(i)).isDisabledPhone()) {
connectedEnabledDevices.add(connectedDevices.get(i));
}
}
else {
connectedEnabledDevices.add(connectedDevices.get(i));
}
}
return connectedEnabledDevices;
}
}
public void setSelectedDevice(PhoneInterface phone) {
if (phone != selectedPhone) {
selectedPhone = phone;
for (int i=0; i<deviceDetectionListeners.size(); i++) {
deviceDetectionListeners.get(i).deviceSelectedChanged();
}
}
}
@SuppressWarnings("unchecked")
public void checkDevices() {
boolean changed = false;
List<PhoneInterface> newConnectedDevices = new ArrayList<PhoneInterface>();
//ANDROID Devices detection
IDevice[] androidDevices = initddmlib();
for (int i=0 ; i<androidDevices.length ; i++) {
IDevice androidDevice = androidDevices[i];
if (androidDevice.isOnline()) {
boolean found = false;
for (int j=0; j<connectedDevices.size(); j++) {
PhoneInterface phone = connectedDevices.get(j);
String uid = AndroidPhone.getUID(androidDevice);
String connectedPhoneUid = phone.getUID();
if (connectedPhoneUid!=null && connectedPhoneUid.equals(uid)) {
found = true;
newConnectedDevices.add(phone);
if (phone.getCnxStatus()!=PhoneInterface.CNX_STATUS_AVAILABLE) {
phone.setCnxStatus(PhoneInterface.CNX_STATUS_AVAILABLE);
changed = true;
if(phone instanceof AndroidMonkeyDriver){
Logger.getLogger(this.getClass()).info("refresh ddmlib handler for MonkeyDriver enabled device");
try {
((AndroidMonkeyDriver)phone).setDevice(androidDevice);
} catch (PhoneException e) {
Logger.getLogger(this.getClass()).error("unable to refresh ddmlib handler");
}
}
}
}
}
if (!found) {
String vendor = AndroidPhone.getVendor(androidDevice);
if (vendor!=null) vendor = vendor.toLowerCase();
String model = AndroidPhone.getModel(androidDevice);
String version = "";
version = AndroidPhone.getVersion(androidDevice);
if (model!=null) model = model.toLowerCase();
if(vendor!=null && model!=null){
PhoneInterface newPhone;
try {
float v=Float.parseFloat(version.substring(0, 3));
Logger.getLogger(this.getClass()).info(v);
if ( v >= 2.0f){
if (v >= 4.0f){
if (v >= 4.1f){
Logger.getLogger(this.getClass()).info("Android Jelly bean detected !");
newPhone = new AndroidJBDriver(vendor+"_"+model, version, androidDevice);
}else{
Logger.getLogger(this.getClass()).info("Android ICS detected !");
newPhone = new AndroidICSDriver(vendor+"_"+model, version, androidDevice);
}
}else{
newPhone = new AndroidMonkeyDriver(vendor+"_"+model, version, androidDevice);
}
}else{
newPhone = new AndroidDriver(vendor+"_"+model, version, androidDevice);
}
newPhone.setCnxStatus(PhoneInterface.CNX_STATUS_AVAILABLE);
newConnectedDevices.add(newPhone);
Logger.getLogger(this.getClass()).info("New phone "+newPhone.getName()+" connected");
if (!((AndroidPhone)newPhone).isDisabledPhone()) changed = true;
} catch (PhoneException e) {
// NOTHING TO DO HERE
}
} else {
PhoneInterface newPhone = new AndroidPhone(androidDevice);
newPhone.setCnxStatus(PhoneInterface.CNX_STATUS_AVAILABLE);
newConnectedDevices.add(newPhone);
Logger.getLogger(this.getClass()).info("New phone "+newPhone.getName()+" connected");
changed = true;
}
}
}
}
synchronized(connectedDevices) {
// the devices not present in newConnectedDevices are the one that have been disconnected
for (int i=connectedDevices.size()-1; i>=0; i--) {
PhoneInterface phone = connectedDevices.get(i);
if (!newConnectedDevices.contains(phone)) {
if (phone.getCnxStatus()!=PhoneInterface.CNX_STATUS_DISCONNECTED) {
phone.setCnxStatus(PhoneInterface.CNX_STATUS_DISCONNECTED);
if (phone instanceof AndroidPhone) {
if (!((AndroidPhone)phone).isDisabledPhone()) changed = true;
} else changed = true;
}
if (phone.isInRecordingMode()) phone.stopRecordingMode();
if (phone.isInTestingMode()) phone.stopTestingMode();
if (selectedPhone != phone) {
connectedDevices.remove(phone);
if (phone instanceof AndroidPhone) {
if (!((AndroidPhone)phone).isDisabledPhone()) changed = true;
} else changed = true;
}
} else newConnectedDevices.remove(phone);
}
// add the new device connected to the list
for (int i=0; i<newConnectedDevices.size(); i++) {
PhoneInterface phone = newConnectedDevices.get(i);
connectedDevices.add(phone);
}
}
if (changed) notifyDevicesConnectedChanged();
}
public void notifyDevicesConnectedChanged() {
for (int i=0; i<deviceDetectionListeners.size(); i++) {
deviceDetectionListeners.get(i).devicesConnectedChanged();
}
}
/**
* Detect if actual phone is a nokia phone
* @return true if phone connected is a nokia.
*/
public Boolean isNokia(){
//update device
getDevice();
if (selectedPhone!=null) return (selectedPhone.getType() == PhoneInterface.TYPE_S60) ;
else return false;
}
/**
* Use adb location set by user in com.android.screenshot.bindir properties
* or use default location (<i>Install_dir</i>/AndroidTools/adb.exe)
* @return null or Device detected
*/
public IDevice[] initddmlib() {
String newAdbLocation = null;
if (Boolean.valueOf(Configuration.getProperty(Configuration.SPECIFICADB, "false")))
newAdbLocation = Configuration.getProperty(Configuration.ADBPATH)+ Platform.FILE_SEPARATOR+"adb";
else newAdbLocation = defaultAdbLocation;
if (bridge==null || !newAdbLocation.equals(adbLocation)) {
Logger.getLogger(this.getClass()).debug("Initializing ADB bridge : "+newAdbLocation);
adbLocation = newAdbLocation;
if (bridge!=null) AndroidDebugBridge.disconnectBridge();
AndroidDebugBridge.init(false /* debugger support */);
bridge = AndroidDebugBridge.getBridge();
if (bridge==null) bridge = AndroidDebugBridge.createBridge(adbLocation, true );
if (bridge==null) Logger.getLogger(this.getClass()).debug("bridge is null");
//AndroidDebugBridge bridge = AndroidDebugBridge.createBridge(adbLocation, false /* forceNewBridge */);
// we can't just ask for the device list right away, as the internal thread getting
// them from ADB may not be done getting the first list.
// Since we don't really want getDevices() to be blocking, we wait here manually.
int count = 0;
while (bridge.hasInitialDeviceList() == false) {
try {
Thread.sleep(100);
count++;
} catch (InterruptedException e) { }
// let's not wait > 10 sec.
if (count > 100) {
Logger.getLogger(this.getClass() ).warn("Timeout getting device list!");
return new IDevice[0];
}
}
}
return bridge.getDevices();
}
/**
* Search the config file path of the phone in parameters.
* prefer use {@link #getxmlfilepath()}.
*
* @param phoneDefault the phone to find the config file
* @return the config file path
*/
public String getxmlfilepath()
{
String JATKpath = Platform.getInstance().getJATKPath();
String xmlconfilepath = JATKpath+Platform.FILE_SEPARATOR+"log"+
Platform.FILE_SEPARATOR+"ConfigFiles"+Platform.FILE_SEPARATOR;
// Test to determine which config file to use
PhoneInterface phone = AutomaticPhoneDetection.getInstance().getDevice();
if (phone != null) {
xmlconfilepath += phone.getConfigFile();
} else xmlconfilepath += "se.xml";
return xmlconfilepath;
}
public String getADBLocation() {
return adbLocation;
}
/**
* close all fabric (like androidDebugBridge)
*/
private void close() {
if (bridge!=null) AndroidDebugBridge.terminate();
}
}
|
wrong path to look for phone configuration file (why was there a "log"
subdirectory ??? weird ...)
|
src/com/orange/atk/phone/detection/AutomaticPhoneDetection.java
|
wrong path to look for phone configuration file (why was there a "log" subdirectory ??? weird ...)
|
|
Java
|
apache-2.0
|
6c0e8662de610b55ccba42efc0d9a0b870f14ab8
| 0
|
openwms/org.openwms,openwms/org.openwms
|
/*
* openwms.org, the Open Warehouse Management System.
*
* This file is part of openwms.org.
*
* openwms.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* openwms.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software. If not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.openwms.core.service.spring;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import junit.framework.Assert;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.openwms.core.domain.system.usermanagement.Grant;
import org.openwms.core.domain.system.usermanagement.SecurityObject;
import org.openwms.core.integration.RoleDao;
import org.openwms.core.integration.SecurityObjectDao;
import org.openwms.core.test.AbstractMockitoTests;
/**
* A SecurityServiceTest.
*
* @author <a href="mailto:scherrer@openwms.org">Heiko Scherrer</a>
* @version $Revision: $
* @since 0.1
*/
public class SecurityServiceTest extends AbstractMockitoTests {
@Mock
private SecurityObjectDao dao;
@SuppressWarnings("unused")
@Mock
private RoleDao roleDao;
@InjectMocks
private SecurityServiceImpl srv;
/**
* Positive test findAll method.
*/
@Test
public final void testFindAll() {
List<SecurityObject> result = new ArrayList<SecurityObject>();
result.add(new Grant("GRANT1"));
result.add(new Grant("GRANT2"));
when(dao.findAll()).thenReturn(result);
Assert.assertTrue(srv.findAll().size() == 2);
verify(dao, times(1)).findAll();
}
/**
* Positive test findAll method with empty result
*/
@Test
public final void testFindAllEmpty() {
when(dao.findAll()).thenReturn(null);
Assert.assertTrue(srv.findAll().isEmpty());
verify(dao, times(1)).findAll();
}
/**
* Test method for
* {@link org.openwms.core.service.spring.SecurityServiceImpl#login()}.
*/
@Test
public final void testLogin() {
srv.login();
}
/**
* Test method for
* {@link org.openwms.core.service.spring.SecurityServiceImpl#mergeGrants(java.lang.String, java.util.List)}
* .
*/
@Test
public final void testMergeGrantsWithNull() {
try {
srv.mergeGrants(null, null);
fail("Must throw an illegalArgumentException");
} catch (IllegalArgumentException iae) {
logger.debug("OK: IllegalArgumentException thrown when calling merge with null");
}
}
/**
* Test method for
* {@link org.openwms.core.service.spring.SecurityServiceImpl#mergeGrants(java.lang.String, java.util.List)}
* .
*
* Add a new Grant.
*/
@Test
public final void testMergeGrantsNew() {
// prepare data
List<Grant> persistedGrants = new ArrayList<Grant>();
Grant testGrant = new Grant("TMS_NEW");
persistedGrants.add(new Grant("TMS_KEY1"));
List<Grant> newGrants = new ArrayList<Grant>();
newGrants.add(testGrant);
// preparing mocks
when(dao.findAllOfModule("TMS%")).thenReturn(persistedGrants);
when(dao.merge(testGrant)).thenReturn(testGrant);
// when(roleDao.removeFromRoles(persistedGrants));
// do test call
List<Grant> result = srv.mergeGrants("TMS", newGrants);
// verify mock invocations
// New Grant shall be added...
verify(dao).merge(testGrant);
// Verify the the new Grant will not be in the list of removed Grants...
verify(dao, never()).delete(Arrays.asList(new Grant[] { testGrant }));
// But the existing Grant has to be removed, because it is not in the
// list of merging Grants...
verify(dao).delete(Arrays.asList(new Grant[] { new Grant("TMS_KEY1") }));
// check the results
assertEquals(1, result.size());
assertTrue(result.contains(testGrant));
}
/**
* Test method for
* {@link org.openwms.core.service.spring.SecurityServiceImpl#mergeGrants(java.lang.String, java.util.List)}
* .
*
* Merge existing Grants.
*/
@Test
public final void testMergeGrantsExisting() {
// FIXME [scherrer] : Verify test!
// prepare data
List<Grant> persistedGrants = new ArrayList<Grant>();
persistedGrants.add(new Grant("TMS_NEW"));
List<Grant> newGrants = new ArrayList<Grant>();
Grant testGrant = new Grant("TMS_NEW");
newGrants.add(testGrant);
// preparing mocks
when(dao.findAllOfModule("TMS%")).thenReturn(persistedGrants);
when(dao.merge(testGrant)).thenReturn(testGrant);
// do test call
List<Grant> result = srv.mergeGrants("TMS", newGrants);
// verify mock invocations
// New Grant shall be added...
verify(dao, never()).merge(testGrant);
// Verify the the new Grant will not be in the list of removed Grants...
verify(dao, never()).delete(Arrays.asList(new Grant[] { testGrant }));
// check the results
assertEquals(1, result.size());
assertTrue(result.contains(testGrant));
}
}
|
org.openwms/trunk/org.openwms.core/org.openwms.core.service.spring/src/test/java/org/openwms/core/service/spring/SecurityServiceTest.java
|
/*
* openwms.org, the Open Warehouse Management System.
*
* This file is part of openwms.org.
*
* openwms.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* openwms.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software. If not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.openwms.core.service.spring;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.openwms.core.domain.system.usermanagement.Grant;
import org.openwms.core.integration.RoleDao;
import org.openwms.core.integration.SecurityObjectDao;
import org.openwms.core.test.AbstractMockitoTests;
/**
* A SecurityServiceTest.
*
* @author <a href="mailto:scherrer@openwms.org">Heiko Scherrer</a>
* @version $Revision: $
* @since 0.1
*/
public class SecurityServiceTest extends AbstractMockitoTests {
@Mock
private SecurityObjectDao dao;
@Mock
private RoleDao roleDao;
@InjectMocks
private SecurityServiceImpl srv;
/**
* Test method for
* {@link org.openwms.core.service.spring.SecurityServiceImpl#login()}.
*/
@Test
public final void testLogin() {
srv.login();
}
/**
* Test method for
* {@link org.openwms.core.service.spring.SecurityServiceImpl#mergeGrants(java.lang.String, java.util.List)}
* .
*/
@Test
public final void testMergeGrantsWithNull() {
try {
srv.mergeGrants(null, null);
fail("Must throw an illegalArgumentException");
} catch (IllegalArgumentException iae) {
logger.debug("OK: IllegalArgumentException thrown when calling merge with null");
}
}
/**
* Test method for
* {@link org.openwms.core.service.spring.SecurityServiceImpl#mergeGrants(java.lang.String, java.util.List)}
* .
*
* Add a new Grant.
*/
@Test
public final void testMergeGrantsNew() {
// prepare data
List<Grant> persistedGrants = new ArrayList<Grant>();
Grant testGrant = new Grant("TMS_NEW");
persistedGrants.add(new Grant("TMS_KEY1"));
List<Grant> newGrants = new ArrayList<Grant>();
newGrants.add(testGrant);
// preparing mocks
when(dao.findAllOfModule("TMS%")).thenReturn(persistedGrants);
when(dao.merge(testGrant)).thenReturn(testGrant);
// when(roleDao.removeFromRoles(persistedGrants));
// do test call
List<Grant> result = srv.mergeGrants("TMS", newGrants);
// verify mock invocations
// New Grant shall be added...
verify(dao).merge(testGrant);
// Verify the the new Grant will not be in the list of removed Grants...
verify(dao, never()).delete(Arrays.asList(new Grant[] { testGrant }));
// But the existing Grant has to be removed, because it is not in the
// list of merging Grants...
verify(dao).delete(Arrays.asList(new Grant[] { new Grant("TMS_KEY1") }));
// check the results
assertEquals(1, result.size());
assertTrue(result.contains(testGrant));
}
/**
* Test method for
* {@link org.openwms.core.service.spring.SecurityServiceImpl#mergeGrants(java.lang.String, java.util.List)}
* .
*
* Merge existing Grants.
*/
@Test
public final void testMergeGrantsExisting() {
// FIXME [scherrer] : Verify test!
// prepare data
List<Grant> persistedGrants = new ArrayList<Grant>();
persistedGrants.add(new Grant("TMS_NEW"));
List<Grant> newGrants = new ArrayList<Grant>();
Grant testGrant = new Grant("TMS_NEW");
newGrants.add(testGrant);
// preparing mocks
when(dao.findAllOfModule("TMS%")).thenReturn(persistedGrants);
when(dao.merge(testGrant)).thenReturn(testGrant);
// do test call
List<Grant> result = srv.mergeGrants("TMS", newGrants);
// verify mock invocations
// New Grant shall be added...
verify(dao, never()).merge(testGrant);
// Verify the the new Grant will not be in the list of removed Grants...
verify(dao, never()).delete(Arrays.asList(new Grant[] { testGrant }));
// check the results
assertEquals(1, result.size());
assertTrue(result.contains(testGrant));
}
}
|
git-svn-id: https://openwms2005.svn.sourceforge.net/svnroot/openwms2005@1757 fda5f131-174c-0410-8613-e0905860106b
|
org.openwms/trunk/org.openwms.core/org.openwms.core.service.spring/src/test/java/org/openwms/core/service/spring/SecurityServiceTest.java
| ||
Java
|
apache-2.0
|
09e1ab08350d57e059a76e68c1b0db9b3da7c7cf
| 0
|
bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr
|
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package io.joynr.util;
import static org.junit.Assert.assertNotNull;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import io.joynr.dispatcher.rpc.RequestStatus;
public class ReflectionUtilsTest {
private void addSingleElementToFixture(Map<String, Class<?>[]> fixture,
String expectedDatatypeName,
Class<?> datatype) {
fixture.put(expectedDatatypeName, new Class<?>[]{ datatype });
}
@Test
public void testToDatatypeNames() {
Map<String, Class<?>[]> fixture = new HashMap<>();
addSingleElementToFixture(fixture, "Boolean", Boolean.class);
addSingleElementToFixture(fixture, "Boolean[]", Boolean[].class);
addSingleElementToFixture(fixture, "Byte", Byte.class);
addSingleElementToFixture(fixture, "Byte[]", Byte[].class);
addSingleElementToFixture(fixture, "Short", Short.class);
addSingleElementToFixture(fixture, "Short[]", Short[].class);
addSingleElementToFixture(fixture, "Integer", Integer.class);
addSingleElementToFixture(fixture, "Integer[]", Integer[].class);
addSingleElementToFixture(fixture, "Long", Long.class);
addSingleElementToFixture(fixture, "Long[]", Long[].class);
addSingleElementToFixture(fixture, "Float", Float.class);
addSingleElementToFixture(fixture, "Float[]", Float[].class);
addSingleElementToFixture(fixture, "Double", Double.class);
addSingleElementToFixture(fixture, "Double[]", Double[].class);
addSingleElementToFixture(fixture, "String", String.class);
addSingleElementToFixture(fixture, "String[]", String[].class);
addSingleElementToFixture(fixture, "io.joynr.dispatcher.rpc.RequestStatus", RequestStatus.class);
addSingleElementToFixture(fixture, "io.joynr.dispatcher.rpc.RequestStatus[]", RequestStatus[].class);
for (Map.Entry<String, Class<?>[]> entry : fixture.entrySet()) {
String datatypeName = ReflectionUtils.toDatatypeNames(entry.getValue())[0];
String key = entry.getKey();
Assert.assertEquals(key, datatypeName);
}
}
@Test
public void testGetStaticMethodFromSuperInterfacesWithClassContainingSearchedMethod() throws NoSuchMethodException {
assertNotNull(ReflectionUtils.getStaticMethodFromSuperInterfaces(TestClassContainingSearchedMethod.class,
"oneMethodToRuleThemAll"));
}
@Test(expected = NoSuchMethodException.class)
public void testGetStaticMethodFromSuperInterfacesWithClassNotContainingSearchedMethod() throws NoSuchMethodException {
ReflectionUtils.getStaticMethodFromSuperInterfaces(TestClassNotContainingSearchedMethod.class,
"oneMethodToRuleThemAll");
}
@Test
public void testGetStaticMethodFromSuperInterfacesWithParentClassContainingSearchedMethod() throws NoSuchMethodException {
assertNotNull(ReflectionUtils.getStaticMethodFromSuperInterfaces(TestClassWithParentContainingSearchedMethod.class,
"oneMethodToRuleThemAll"));
}
@Test(expected = NoSuchMethodException.class)
public void testGetStaticMethodFromSuperInterfacesWithParentClassNotContainingSearchedMethod() throws NoSuchMethodException {
ReflectionUtils.getStaticMethodFromSuperInterfaces(TestClassWithParentNotContainingSearchedMethod.class,
"oneMethodToRuleThemAll");
}
@Test
public void testGetStaticMethodFromSuperInterfacesWithInterfaceContainingSearchedMethod() throws NoSuchMethodException {
ReflectionUtils.getStaticMethodFromSuperInterfaces(TestInterfaceContainingSearchedMethod.class,
"oneMethodToRuleThemAll");
}
@Test(expected = NoSuchMethodException.class)
public void testGetStaticMethodFromSuperInterfacesWithInterfaceNotContainingSearchedMethod() throws NoSuchMethodException {
ReflectionUtils.getStaticMethodFromSuperInterfaces(TestInterfaceNotContainingSearchedMethod.class,
"oneMethodToRuleThemAll");
}
@Test
public void testGetStaticMethodFromSuperInterfacesWithInterfaceExtendingInterfaceContainingSearchedMethod() throws NoSuchMethodException {
ReflectionUtils.getStaticMethodFromSuperInterfaces(TestInterfaceExtendingInterfaceContainingSearchedMethod.class,
"oneMethodToRuleThemAll");
}
@Test(expected = NoSuchMethodException.class)
public void testGetStaticMethodFromSuperInterfacesWithInterfaceExtendingInterfaceNotContainingSearchedMethod() throws NoSuchMethodException {
ReflectionUtils.getStaticMethodFromSuperInterfaces(TestInterfaceExtendingInterfaceNotContainingSearchedMethod.class,
"oneMethodToRuleThemAll");
}
private class TestClassContainingSearchedMethod {
public void oneMethodToRuleThemAll() {
};
}
private class TestClassWithParentContainingSearchedMethod extends ParentClassContainingSearchedMethod {
}
private class TestClassNotContainingSearchedMethod {
}
private class TestClassWithParentNotContainingSearchedMethod extends ParentClassNotContainingSearchedMethod {
}
private class ParentClassContainingSearchedMethod {
public void oneMethodToRuleThemAll() {
};
}
private class ParentClassNotContainingSearchedMethod {
}
private interface TestInterfaceContainingSearchedMethod {
public static void oneMethodToRuleThemAll() {
};
}
private interface TestInterfaceNotContainingSearchedMethod {
}
private interface TestInterfaceExtendingInterfaceContainingSearchedMethod
extends TestInterfaceContainingSearchedMethod {
}
private interface TestInterfaceExtendingInterfaceNotContainingSearchedMethod
extends TestInterfaceNotContainingSearchedMethod {
}
}
|
java/javaapi/src/test/java/io/joynr/util/ReflectionUtilsTest.java
|
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package io.joynr.util;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import io.joynr.dispatcher.rpc.RequestStatus;
public class ReflectionUtilsTest {
private void addSingleElementToFixture(Map<String, Class<?>[]> fixture,
String expectedDatatypeName,
Class<?> datatype) {
fixture.put(expectedDatatypeName, new Class<?>[]{ datatype });
}
@Test
public void testToDatatypeNames() {
Map<String, Class<?>[]> fixture = new HashMap<>();
addSingleElementToFixture(fixture, "Boolean", Boolean.class);
addSingleElementToFixture(fixture, "Boolean[]", Boolean[].class);
addSingleElementToFixture(fixture, "Byte", Byte.class);
addSingleElementToFixture(fixture, "Byte[]", Byte[].class);
addSingleElementToFixture(fixture, "Short", Short.class);
addSingleElementToFixture(fixture, "Short[]", Short[].class);
addSingleElementToFixture(fixture, "Integer", Integer.class);
addSingleElementToFixture(fixture, "Integer[]", Integer[].class);
addSingleElementToFixture(fixture, "Long", Long.class);
addSingleElementToFixture(fixture, "Long[]", Long[].class);
addSingleElementToFixture(fixture, "Float", Float.class);
addSingleElementToFixture(fixture, "Float[]", Float[].class);
addSingleElementToFixture(fixture, "Double", Double.class);
addSingleElementToFixture(fixture, "Double[]", Double[].class);
addSingleElementToFixture(fixture, "String", String.class);
addSingleElementToFixture(fixture, "String[]", String[].class);
addSingleElementToFixture(fixture, "io.joynr.dispatcher.rpc.RequestStatus", RequestStatus.class);
addSingleElementToFixture(fixture, "io.joynr.dispatcher.rpc.RequestStatus[]", RequestStatus[].class);
for (Map.Entry<String, Class<?>[]> entry : fixture.entrySet()) {
String datatypeName = ReflectionUtils.toDatatypeNames(entry.getValue())[0];
String key = entry.getKey();
Assert.assertEquals(key, datatypeName);
}
}
}
|
[Java] Add tests for ReflectionUtils.getStaticMethodFromSuperInterfaces
|
java/javaapi/src/test/java/io/joynr/util/ReflectionUtilsTest.java
|
[Java] Add tests for ReflectionUtils.getStaticMethodFromSuperInterfaces
|
|
Java
|
apache-2.0
|
e9f459febf65de92ae99222fc2c476d54f7900db
| 0
|
langerhans/bitcoinj-alice-hd
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bitcoinj.core;
import org.bitcoinj.utils.*;
import org.slf4j.*;
import javax.annotation.*;
import java.lang.ref.*;
import java.util.*;
import java.util.concurrent.locks.*;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* <p>Tracks transactions that are being announced across the network. Typically one is created for you by a
* {@link PeerGroup} and then given to each Peer to update. The current purpose is to let Peers update the confidence
* (number of peers broadcasting). It helps address an attack scenario in which a malicious remote peer (or several)
* feeds you invalid transactions, eg, ones that spend coins which don't exist. If you don't see most of the peers
* announce the transaction within a reasonable time, it may be that the TX is not valid. Alternatively, an attacker
* may control your entire internet connection: in this scenario counting broadcasting peers does not help you.</p>
*
* <p>It is <b>not</b> at this time directly equivalent to the Satoshi clients memory pool, which tracks
* all transactions not currently included in the best chain - it's simply a cache.</p>
*/
public class TxConfidenceTable {
private static final Logger log = LoggerFactory.getLogger(TxConfidenceTable.class);
protected ReentrantLock lock = Threading.lock("txconfidencetable");
private static class WeakConfidenceReference extends WeakReference<TransactionConfidence> {
public Sha256Hash hash;
public WeakConfidenceReference(TransactionConfidence confidence, ReferenceQueue<TransactionConfidence> queue) {
super(confidence, queue);
hash = confidence.getTransactionHash();
}
}
private LinkedHashMap<Sha256Hash, WeakConfidenceReference> table;
// This ReferenceQueue gets entries added to it when they are only weakly reachable, ie, the TxConfidenceTable is the
// only thing that is tracking the confidence data anymore. We check it from time to time and delete table entries
// corresponding to expired transactions. In this way memory usage of the system is in line with however many
// transactions you actually care to track the confidence of. We can still end up with lots of hashes being stored
// if our peers flood us with invs but the MAX_SIZE param caps this.
private ReferenceQueue<TransactionConfidence> referenceQueue;
/** The max size of a table created with the no-args constructor. */
public static final int MAX_SIZE = 1000;
/**
* Creates a table that will track at most the given number of transactions (allowing you to bound memory
* usage).
* @param size Max number of transactions to track. The table will fill up to this size then stop growing.
*/
public TxConfidenceTable(final int size) {
table = new LinkedHashMap<Sha256Hash, WeakConfidenceReference>() {
@Override
protected boolean removeEldestEntry(Map.Entry<Sha256Hash, WeakConfidenceReference> entry) {
// An arbitrary choice to stop the memory used by tracked transactions getting too huge in the event
// of some kind of DoS attack.
return size() > size;
}
};
referenceQueue = new ReferenceQueue<TransactionConfidence>();
}
/**
* Creates a table that will track at most {@link TxConfidenceTable#MAX_SIZE} entries. You should normally use
* this constructor.
*/
public TxConfidenceTable() {
this(MAX_SIZE);
}
/**
* If any transactions have expired due to being only weakly reachable through us, go ahead and delete their
* table entries - it means we downloaded the transaction and sent it to various event listeners, none of
* which bothered to keep a reference. Typically, this is because the transaction does not involve any keys that
* are relevant to any of our wallets.
*/
public void cleanTable() {
lock.lock();
try {
Reference<? extends TransactionConfidence> ref;
while ((ref = referenceQueue.poll()) != null) {
// Find which transaction got deleted by the GC.
WeakConfidenceReference txRef = (WeakConfidenceReference) ref;
// And remove the associated map entry so the other bits of memory can also be reclaimed.
table.remove(txRef.hash);
}
} finally {
lock.unlock();
}
}
/**
* Reset the state of the mempool i.e. forget everything
*/
public void reset() {
lock.lock();
try {
table.clear();
} finally {
lock.unlock();
}
}
/**
* Returns the number of peers that have seen the given hash recently.
*/
public int numBroadcastPeers(Sha256Hash txHash) {
lock.lock();
try {
cleanTable();
WeakConfidenceReference entry = table.get(txHash);
if (entry == null) {
return 0; // No such TX known.
} else {
TransactionConfidence confidence = entry.get();
if (confidence == null) {
// Such a TX hash was seen, but nothing seemed to care so we ended up throwing away the data.
table.remove(txHash);
return 0;
} else {
return confidence.numBroadcastPeers();
}
}
} finally {
lock.unlock();
}
}
/**
* Called by peers when they see a transaction advertised in an "inv" message. It passes the data on to the relevant
* {@link org.bitcoinj.core.TransactionConfidence} object, creating it if needed.
*
* @return the number of peers that have now announced this hash (including the caller)
*/
public TransactionConfidence seen(Sha256Hash hash, PeerAddress byPeer) {
TransactionConfidence confidence;
boolean fresh = false;
lock.lock();
{
cleanTable();
confidence = getOrCreate(hash);
fresh = confidence.markBroadcastBy(byPeer);
}
lock.unlock();
if (fresh)
confidence.queueListeners(TransactionConfidence.Listener.ChangeReason.SEEN_PEERS);
return confidence;
}
/**
* Returns the {@link TransactionConfidence} for the given hash if we have downloaded it, or null if that tx hash
* is unknown to the system at this time.
*/
public TransactionConfidence getOrCreate(Sha256Hash hash) {
checkNotNull(hash);
lock.lock();
try {
WeakConfidenceReference reference = table.get(hash);
if (reference != null) {
TransactionConfidence confidence = reference.get();
if (confidence != null)
return confidence;
}
TransactionConfidence newConfidence = new TransactionConfidence(hash);
table.put(hash, new WeakConfidenceReference(newConfidence, referenceQueue));
return newConfidence;
} finally {
lock.unlock();
}
}
/**
* Returns the {@link TransactionConfidence} for the given hash if we have downloaded it, or null if that tx hash
* is unknown to the system at this time.
*/
@Nullable
public TransactionConfidence get(Sha256Hash hash) {
lock.lock();
try {
WeakConfidenceReference ref = table.get(hash);
if (ref == null)
return null;
TransactionConfidence confidence = ref.get();
if (confidence != null)
return confidence;
else
return null;
} finally {
lock.unlock();
}
}
}
|
core/src/main/java/org/bitcoinj/core/TxConfidenceTable.java
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bitcoinj.core;
import org.bitcoinj.utils.*;
import org.slf4j.*;
import javax.annotation.*;
import java.lang.ref.*;
import java.util.*;
import java.util.concurrent.locks.*;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* <p>Tracks transactions that are being announced across the network. Typically one is created for you by a
* {@link PeerGroup} and then given to each Peer to update. The current purpose is to let Peers update the confidence
* (number of peers broadcasting). It helps address an attack scenario in which a malicious remote peer (or several)
* feeds you invalid transactions, eg, ones that spend coins which don't exist. If you don't see most of the peers
* announce the transaction within a reasonable time, it may be that the TX is not valid. Alternatively, an attacker
* may control your entire internet connection: in this scenario counting broadcasting peers does not help you.</p>
*
* <p>It is <b>not</b> at this time directly equivalent to the Satoshi clients memory pool, which tracks
* all transactions not currently included in the best chain - it's simply a cache.</p>
*/
public class TxConfidenceTable {
private static final Logger log = LoggerFactory.getLogger(TxConfidenceTable.class);
protected ReentrantLock lock = Threading.lock("txconfidencetable");
private static class WeakConfidenceReference extends WeakReference<TransactionConfidence> {
public Sha256Hash hash;
public WeakConfidenceReference(TransactionConfidence confidence, ReferenceQueue<TransactionConfidence> queue) {
super(confidence, queue);
hash = confidence.getTransactionHash();
}
}
private LinkedHashMap<Sha256Hash, WeakConfidenceReference> table;
// This ReferenceQueue gets entries added to it when they are only weakly reachable, ie, the TxConfidenceTable is the
// only thing that is tracking the confidence data anymore. We check it from time to time and delete table entries
// corresponding to expired transactions. In this way memory usage of the system is in line with however many
// transactions you actually care to track the confidence of. We can still end up with lots of hashes being stored
// if our peers flood us with invs but the MAX_SIZE param caps this.
private ReferenceQueue<TransactionConfidence> referenceQueue;
/** The max size of a table created with the no-args constructor. */
public static final int MAX_SIZE = 1000;
/**
* Creates a table that will track at most the given number of transactions (allowing you to bound memory
* usage).
* @param size Max number of transactions to track. The table will fill up to this size then stop growing.
*/
public TxConfidenceTable(final int size) {
table = new LinkedHashMap<Sha256Hash, WeakConfidenceReference>() {
@Override
protected boolean removeEldestEntry(Map.Entry<Sha256Hash, WeakConfidenceReference> entry) {
// An arbitrary choice to stop the memory used by tracked transactions getting too huge in the event
// of some kind of DoS attack.
return size() > size;
}
};
referenceQueue = new ReferenceQueue<TransactionConfidence>();
}
/**
* Creates a table that will track at most {@link TxConfidenceTable#MAX_SIZE} entries. You should normally use
* this constructor.
*/
public TxConfidenceTable() {
this(MAX_SIZE);
}
/**
* If any transactions have expired due to being only weakly reachable through us, go ahead and delete their
* table entries - it means we downloaded the transaction and sent it to various event listeners, none of
* which bothered to keep a reference. Typically, this is because the transaction does not involve any keys that
* are relevant to any of our wallets.
*/
private void cleanTable() {
lock.lock();
try {
Reference<? extends TransactionConfidence> ref;
while ((ref = referenceQueue.poll()) != null) {
// Find which transaction got deleted by the GC.
WeakConfidenceReference txRef = (WeakConfidenceReference) ref;
// And remove the associated map entry so the other bits of memory can also be reclaimed.
table.remove(txRef.hash);
}
} finally {
lock.unlock();
}
}
/**
* Returns the number of peers that have seen the given hash recently.
*/
public int numBroadcastPeers(Sha256Hash txHash) {
lock.lock();
try {
cleanTable();
WeakConfidenceReference entry = table.get(txHash);
if (entry == null) {
return 0; // No such TX known.
} else {
TransactionConfidence confidence = entry.get();
if (confidence == null) {
// Such a TX hash was seen, but nothing seemed to care so we ended up throwing away the data.
table.remove(txHash);
return 0;
} else {
return confidence.numBroadcastPeers();
}
}
} finally {
lock.unlock();
}
}
/**
* Called by peers when they see a transaction advertised in an "inv" message. It passes the data on to the relevant
* {@link org.bitcoinj.core.TransactionConfidence} object, creating it if needed.
*
* @return the number of peers that have now announced this hash (including the caller)
*/
public TransactionConfidence seen(Sha256Hash hash, PeerAddress byPeer) {
TransactionConfidence confidence;
boolean fresh = false;
lock.lock();
{
cleanTable();
confidence = getOrCreate(hash);
fresh = confidence.markBroadcastBy(byPeer);
}
lock.unlock();
if (fresh)
confidence.queueListeners(TransactionConfidence.Listener.ChangeReason.SEEN_PEERS);
return confidence;
}
/**
* Returns the {@link TransactionConfidence} for the given hash if we have downloaded it, or null if that tx hash
* is unknown to the system at this time.
*/
public TransactionConfidence getOrCreate(Sha256Hash hash) {
checkNotNull(hash);
lock.lock();
try {
WeakConfidenceReference reference = table.get(hash);
if (reference != null) {
TransactionConfidence confidence = reference.get();
if (confidence != null)
return confidence;
}
TransactionConfidence newConfidence = new TransactionConfidence(hash);
table.put(hash, new WeakConfidenceReference(newConfidence, referenceQueue));
return newConfidence;
} finally {
lock.unlock();
}
}
/**
* Returns the {@link TransactionConfidence} for the given hash if we have downloaded it, or null if that tx hash
* is unknown to the system at this time.
*/
@Nullable
public TransactionConfidence get(Sha256Hash hash) {
lock.lock();
try {
WeakConfidenceReference ref = table.get(hash);
if (ref == null)
return null;
TransactionConfidence confidence = ref.get();
if (confidence != null)
return confidence;
else
return null;
} finally {
lock.unlock();
}
}
}
|
added ability to reset mempool
|
core/src/main/java/org/bitcoinj/core/TxConfidenceTable.java
|
added ability to reset mempool
|
|
Java
|
apache-2.0
|
bd6b79cc68f149a05eb254f30277e39184b69f4c
| 0
|
fengshao0907/hazelcast-simulator,hazelcast/hazelcast-simulator,eminn/hazelcast-simulator,pveentjer/hazelcast-simulator,pveentjer/hazelcast-simulator,eminn/hazelcast-simulator,hasancelik/hazelcast-stabilizer,gAmUssA/hazelcast-simulator,hazelcast/hazelcast-simulator,gAmUssA/hazelcast-simulator,Danny-Hazelcast/hazelcast-stabilizer,Donnerbart/hazelcast-simulator,hasancelik/hazelcast-stabilizer,hazelcast/hazelcast-simulator,Donnerbart/hazelcast-simulator,fengshao0907/hazelcast-simulator,jerrinot/hazelcast-stabilizer,jerrinot/hazelcast-stabilizer,Danny-Hazelcast/hazelcast-stabilizer
|
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.stabilizer;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import org.apache.commons.lang3.text.StrSubstitutor;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.Socket;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.Deque;
import java.util.Formatter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.locks.LockSupport;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import static java.lang.String.format;
public final class Utils {
public static final String NEW_LINE = System.getProperty("line.separator");
private static final String DEFAULT_DELIMITER = ", ";
private static final String EXCEPTION_SEPARATOR = "------ End remote and begin local stack-trace ------";
private static final String USER_HOME = System.getProperty("user.home");
private static final ILogger log = Logger.getLogger(Utils.class);
private static volatile String hostAddress;
public static void fixRemoteStackTrace(Throwable remoteCause, StackTraceElement[] localSideStackTrace) {
StackTraceElement[] remoteStackTrace = remoteCause.getStackTrace();
StackTraceElement[] newStackTrace = new StackTraceElement[localSideStackTrace.length + remoteStackTrace.length];
System.arraycopy(remoteStackTrace, 0, newStackTrace, 0, remoteStackTrace.length);
newStackTrace[remoteStackTrace.length] = new StackTraceElement(EXCEPTION_SEPARATOR, "", null, -1);
System.arraycopy(localSideStackTrace, 1, newStackTrace, remoteStackTrace.length + 1, localSideStackTrace.length - 1);
remoteCause.setStackTrace(newStackTrace);
}
/**
* Formats a number and adds padding to the left.
* It is very inefficient; but a lot easier to deal with the formatting API.
*
* @param number number to format
* @param length width of padding
* @return formatted number
*/
public static String formatDouble(double number, int length) {
StringBuffer sb = new StringBuffer();
Formatter f = new Formatter(sb);
f.format("%(,.2f", number);
return padLeft(sb.toString(), length);
}
public static String formatLong(long number, int length) {
StringBuffer sb = new StringBuffer();
Formatter f = new Formatter(sb);
f.format("%(,d", number);
return padLeft(sb.toString(), length);
}
public static String padRight(String s, int n) {
if (n <= 0 || s == null || s.isEmpty()) {
return s;
}
try {
return String.format("%-" + n + "s", s);
} catch (Exception e) {
log.warning("String " + s + " and padding length " + n + " caused an exception!");
e.printStackTrace();
return s;
}
}
public static String padLeft(String s, int n) {
if (n <= 0 || s == null || s.isEmpty()) {
return s;
}
try {
return String.format("%" + n + "s", s);
} catch (Exception e) {
log.warning("String " + s + " and padding length " + n + " caused an exception!");
e.printStackTrace();
return s;
}
}
public static File newFile(String path) {
path = path.trim();
if (path.equals("~")) {
path = USER_HOME;
} else if (path.startsWith("~" + File.separator)) {
path = USER_HOME + path.substring(1);
}
path = new StrSubstitutor().replace(path);
return new File(path);
}
public static String getText(String url) throws IOException {
URL website = new URL(url);
URLConnection connection = website.openConnection();
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return response.toString();
} finally {
closeQuietly(in);
}
}
public static File newFile(File file, String... items) {
for (String item : items) {
file = new File(file, item);
}
return file;
}
public static File newFile(String... items) {
File file = newFile(items[0]);
for (int k = 1; k < items.length; k++) {
file = new File(file, items[k]);
}
return file;
}
public static String getHostAddress() {
if (hostAddress != null) {
return hostAddress;
}
synchronized (Utils.class) {
try {
if (hostAddress != null) {
return hostAddress;
}
Socket s = new Socket("google.com", 80);
hostAddress = s.getLocalAddress().getHostAddress();
s.close();
return hostAddress;
} catch (IOException io) {
throw new RuntimeException(io);
}
}
}
public static void writeObject(Object o, File file) {
File tmpFile = new File(file.getParent(), file.getName() + ".tmp");
try {
final FileOutputStream fous = new FileOutputStream(tmpFile);
try {
ObjectOutput output = new ObjectOutputStream(fous);
output.writeObject(o);
} finally {
Utils.closeQuietly(fous);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
if (!tmpFile.renameTo(file)) {
throw new RuntimeException(format("Could not rename [%s] to [%s]",
tmpFile.getAbsolutePath(), file.getAbsolutePath()));
}
}
public static <E> E readObject(File file) {
try {
FileInputStream fis = new FileInputStream(file);
try {
ObjectInputStream in = new ObjectInputStream(fis);
return (E) in.readObject();
} finally {
Utils.closeQuietly(fis);
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public static void writeText(String text, File file) {
if (text == null) {
throw new NullPointerException("text can't be null");
}
if (file == null) {
throw new NullPointerException("file can't be null");
}
try {
FileOutputStream stream = new FileOutputStream(file);
try {
Writer writer = new BufferedWriter(new OutputStreamWriter(stream));
writer.write(text);
writer.close();
} finally {
closeQuietly(stream);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void appendText(String text, String file) {
appendText(text, new File(file));
}
public static void appendText(String text, File file) {
if (text == null) {
throw new NullPointerException("text can't be null");
}
if (file == null) {
throw new NullPointerException("file can't be null");
}
try {
FileOutputStream stream = new FileOutputStream(file, true);
try {
Writer writer = new BufferedWriter(new OutputStreamWriter(stream));
writer.write(text);
writer.close();
} finally {
closeQuietly(stream);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String fileAsText(String filePath) {
return fileAsText(new File(filePath));
}
public static String[] fileAsLines(File file) {
return fileAsText(file).split("\n");
}
public static String fileAsText(File file) {
try {
FileInputStream stream = new FileInputStream(file);
try {
Reader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
char[] buffer = new char[8192];
int read;
while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
builder.append(buffer, 0, read);
}
return builder.toString();
} finally {
closeQuietly(stream);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void delete(File f) throws IOException {
if (!f.exists()) {
return;
}
if (f.isDirectory()) {
for (File c : f.listFiles()) {
delete(c);
}
}
if (!f.delete()) {
throw new FileNotFoundException("Failed to delete file: " + f);
}
}
public static void ensureExistingDirectory(File dir) {
if (dir.isDirectory()) {
return;
}
if (dir.isFile()) {
throw new IllegalArgumentException(format("File [%s] is not a directory", dir.getAbsolutePath()));
}
if (!dir.mkdirs()) {
throw new RuntimeException("Could not create directory: " + dir.getAbsolutePath());
}
}
public static String getVersion() {
return Utils.class.getPackage().getImplementationVersion();
}
public static byte[] zip(List<File> roots) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Deque<File> queue = new LinkedList<File>();
ZipOutputStream zout = new ZipOutputStream(out);
Set<String> names = new HashSet<String>();
try {
for (File root : roots) {
URI base = root.isDirectory() ? root.toURI() : root.getParentFile().toURI();
queue.push(root);
while (!queue.isEmpty()) {
File file = queue.pop();
if (file.getName().equals(".DS_Store")) {
continue;
}
// log.finest("Zipping: " + file.getAbsolutePath());
if (file.isDirectory()) {
String name = base.relativize(file.toURI()).getPath();
name = name.endsWith("/") ? name : name + "/";
if (names.add(name)) {
zout.putNextEntry(new ZipEntry(name));
}
for (File kid : file.listFiles()) {
queue.push(kid);
}
} else {
String name = base.relativize(file.toURI()).getPath();
zout.putNextEntry(new ZipEntry(name));
copy(file, zout);
zout.closeEntry();
}
}
}
} finally {
zout.close();
}
return out.toByteArray();
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
while (true) {
int readCount = in.read(buffer);
if (readCount < 0) {
break;
}
out.write(buffer, 0, readCount);
}
}
private static void copy(File file, OutputStream out) throws IOException {
InputStream in = new FileInputStream(file);
try {
copy(in, out);
} finally {
in.close();
}
}
public static String throwableToString(Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
public static void unzip(byte[] content, final File destinationDir) throws IOException {
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(content));
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
String fileName = zipEntry.getName();
File file = new File(destinationDir + File.separator + fileName);
// log.finest("Unzipping: " + file.getAbsolutePath());
if (zipEntry.isDirectory()) {
file.mkdirs();
} else {
file.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(file);
try {
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
} finally {
closeQuietly(fos);
}
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
public static File getStablizerHome() {
String home = System.getenv("STABILIZER_HOME");
if (home == null) {
return new File(System.getProperty("user.dir"));
} else {
return new File(home);
}
}
public static void closeQuietly(Socket socket) {
if (socket == null) {
return;
}
try {
socket.close();
} catch (IOException ignore) {
}
}
public static void closeQuietly(Closeable... closeables) {
for (Closeable c : closeables) {
closeQuietly(c);
}
}
public static void closeQuietly(Closeable c) {
if (c == null) return;
try {
c.close();
} catch (IOException ignore) {
}
}
public static void closeQuietly(XMLStreamWriter c) {
if (c == null) return;
try {
c.close();
} catch (XMLStreamException ignore) {
}
}
public static void sleepSeconds(int seconds) {
try {
Thread.sleep(seconds * 1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static void sleepMillis(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static void sleepNanos(long nanos) {
if (nanos <= 0) {
return;
}
LockSupport.parkNanos(nanos);
}
public static void exitWithError(ILogger logger, String msg) {
logger.severe(msg);
System.exit(1);
}
private Utils() {
}
public static String secondsToHuman(long seconds) {
long time = seconds;
long s = time % 60;
time = time / 60;
long m = time % 60;
time = time / 60;
long h = time % 24;
time = time / 24;
long days = time;
StringBuilder sb = new StringBuilder();
sb.append(format("%02d", days)).append("d ")
.append(format("%02d", h)).append("h ")
.append(format("%02d", m)).append("m ")
.append(format("%02d", s)).append("s");
return sb.toString();
}
public static Properties loadProperties(File file) {
Properties properties = new Properties();
final FileInputStream in;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
//should not be thrown since it is already verified that the property file exist.
throw new RuntimeException(e);
}
try {
properties.load(in);
return properties;
} catch (IOException e) {
throw new RuntimeException(format("Failed to load testsuite property file [%s]", file.getAbsolutePath()), e);
} finally {
Utils.closeQuietly(in);
}
}
public static String join(Iterable<?> collection) {
return join(collection, DEFAULT_DELIMITER);
}
public static String join(Iterable<?> collection, String delimiter) {
StringBuilder builder = new StringBuilder();
Iterator<?> iterator = collection.iterator();
while (iterator.hasNext()) {
Object o = iterator.next();
builder.append(o);
if (iterator.hasNext()) {
builder.append(delimiter);
}
}
return builder.toString();
}
public static File getFile(OptionSpec<String> spec, OptionSet options, String desc) {
File file = newFile(options.valueOf(spec));
if (!file.exists()) {
exitWithError(log, format("%s [%s] does not exist\n", desc, file));
}
return file;
}
public static List<File> getFilesFromClassPath(String classpath) throws IOException {
if (classpath == null) {
return Collections.EMPTY_LIST;
}
List<File> files = new LinkedList<File>();
for (String filePath : classpath.split(";")) {
File file = new File(filePath);
if (file.getName().contains("*")) {
File parent = file.getParentFile();
if (!parent.isDirectory()) {
throw new IOException(format("Cannot convert classpath to java.io.File. [%s] is not a directory", parent));
}
String regex = file.getName().replace("*", "(.*)");
for (File child : parent.listFiles()) {
if (child.getName().matches(regex)) {
files.add(child);
}
}
} else if (file.exists()) {
files.add(file);
} else {
Utils.exitWithError(log, format("Cannot convert classpath to java.io.File. [%s] doesn't exist", filePath));
}
}
return files;
}
}
|
stabilizer/src/main/java/com/hazelcast/stabilizer/Utils.java
|
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.stabilizer;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import org.apache.commons.lang3.text.StrSubstitutor;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.Socket;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.Deque;
import java.util.Formatter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.locks.LockSupport;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import static java.lang.String.format;
public final class Utils {
public static final String NEW_LINE = System.getProperty("line.separator");
private static final String DEFAULT_DELIMITER = ", ";
private static final String EXCEPTION_SEPARATOR = "------ End remote and begin local stack-trace ------";
private static final String USER_HOME = System.getProperty("user.home");
private static final ILogger log = Logger.getLogger(Utils.class);
private static volatile String hostAddress;
public static void fixRemoteStackTrace(Throwable remoteCause, StackTraceElement[] localSideStackTrace) {
StackTraceElement[] remoteStackTrace = remoteCause.getStackTrace();
StackTraceElement[] newStackTrace = new StackTraceElement[localSideStackTrace.length + remoteStackTrace.length];
System.arraycopy(remoteStackTrace, 0, newStackTrace, 0, remoteStackTrace.length);
newStackTrace[remoteStackTrace.length] = new StackTraceElement(EXCEPTION_SEPARATOR, "", null, -1);
System.arraycopy(localSideStackTrace, 1, newStackTrace, remoteStackTrace.length + 1, localSideStackTrace.length - 1);
remoteCause.setStackTrace(newStackTrace);
}
/**
* Formats a number and adds padding to the left.
* It is very inefficient; but a lot easier to deal with the formatting API.
*
* @param number number to format
* @param length width of padding
* @return formatted number
*/
public static String formatDouble(double number, int length) {
StringBuffer sb = new StringBuffer();
Formatter f = new Formatter(sb);
f.format("%(,.2f", number);
return padLeft(sb.toString(), length);
}
public static String formatLong(long number, int length) {
StringBuffer sb = new StringBuffer();
Formatter f = new Formatter(sb);
f.format("%(,d", number);
return padLeft(sb.toString(), length);
}
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%1$" + n + "s", s);
}
public static File newFile(String path) {
path = path.trim();
if (path.equals("~")) {
path = USER_HOME;
} else if (path.startsWith("~" + File.separator)) {
path = USER_HOME + path.substring(1);
}
path = new StrSubstitutor().replace(path);
return new File(path);
}
public static String getText(String url) throws IOException {
URL website = new URL(url);
URLConnection connection = website.openConnection();
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return response.toString();
} finally {
closeQuietly(in);
}
}
public static File newFile(File file, String... items) {
for (String item : items) {
file = new File(file, item);
}
return file;
}
public static File newFile(String... items) {
File file = newFile(items[0]);
for (int k = 1; k < items.length; k++) {
file = new File(file, items[k]);
}
return file;
}
public static String getHostAddress() {
if (hostAddress != null) {
return hostAddress;
}
synchronized (Utils.class) {
try {
if (hostAddress != null) {
return hostAddress;
}
Socket s = new Socket("google.com", 80);
hostAddress = s.getLocalAddress().getHostAddress();
s.close();
return hostAddress;
} catch (IOException io) {
throw new RuntimeException(io);
}
}
}
public static void writeObject(Object o, File file) {
File tmpFile = new File(file.getParent(), file.getName() + ".tmp");
try {
final FileOutputStream fous = new FileOutputStream(tmpFile);
try {
ObjectOutput output = new ObjectOutputStream(fous);
output.writeObject(o);
} finally {
Utils.closeQuietly(fous);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
if (!tmpFile.renameTo(file)) {
throw new RuntimeException(format("Could not rename [%s] to [%s]",
tmpFile.getAbsolutePath(), file.getAbsolutePath()));
}
}
public static <E> E readObject(File file) {
try {
FileInputStream fis = new FileInputStream(file);
try {
ObjectInputStream in = new ObjectInputStream(fis);
return (E) in.readObject();
} finally {
Utils.closeQuietly(fis);
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public static void writeText(String text, File file) {
if (text == null) {
throw new NullPointerException("text can't be null");
}
if (file == null) {
throw new NullPointerException("file can't be null");
}
try {
FileOutputStream stream = new FileOutputStream(file);
try {
Writer writer = new BufferedWriter(new OutputStreamWriter(stream));
writer.write(text);
writer.close();
} finally {
closeQuietly(stream);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void appendText(String text, String file) {
appendText(text, new File(file));
}
public static void appendText(String text, File file) {
if (text == null) {
throw new NullPointerException("text can't be null");
}
if (file == null) {
throw new NullPointerException("file can't be null");
}
try {
FileOutputStream stream = new FileOutputStream(file, true);
try {
Writer writer = new BufferedWriter(new OutputStreamWriter(stream));
writer.write(text);
writer.close();
} finally {
closeQuietly(stream);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String fileAsText(String filePath) {
return fileAsText(new File(filePath));
}
public static String[] fileAsLines(File file) {
return fileAsText(file).split("\n");
}
public static String fileAsText(File file) {
try {
FileInputStream stream = new FileInputStream(file);
try {
Reader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
char[] buffer = new char[8192];
int read;
while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
builder.append(buffer, 0, read);
}
return builder.toString();
} finally {
closeQuietly(stream);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void delete(File f) throws IOException {
if (!f.exists()) {
return;
}
if (f.isDirectory()) {
for (File c : f.listFiles()) {
delete(c);
}
}
if (!f.delete()) {
throw new FileNotFoundException("Failed to delete file: " + f);
}
}
public static void ensureExistingDirectory(File dir) {
if (dir.isDirectory()) {
return;
}
if (dir.isFile()) {
throw new IllegalArgumentException(format("File [%s] is not a directory", dir.getAbsolutePath()));
}
if (!dir.mkdirs()) {
throw new RuntimeException("Could not create directory: " + dir.getAbsolutePath());
}
}
public static String getVersion() {
return Utils.class.getPackage().getImplementationVersion();
}
public static byte[] zip(List<File> roots) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Deque<File> queue = new LinkedList<File>();
ZipOutputStream zout = new ZipOutputStream(out);
Set<String> names = new HashSet<String>();
try {
for (File root : roots) {
URI base = root.isDirectory() ? root.toURI() : root.getParentFile().toURI();
queue.push(root);
while (!queue.isEmpty()) {
File file = queue.pop();
if (file.getName().equals(".DS_Store")) {
continue;
}
// log.finest("Zipping: " + file.getAbsolutePath());
if (file.isDirectory()) {
String name = base.relativize(file.toURI()).getPath();
name = name.endsWith("/") ? name : name + "/";
if (names.add(name)) {
zout.putNextEntry(new ZipEntry(name));
}
for (File kid : file.listFiles()) {
queue.push(kid);
}
} else {
String name = base.relativize(file.toURI()).getPath();
zout.putNextEntry(new ZipEntry(name));
copy(file, zout);
zout.closeEntry();
}
}
}
} finally {
zout.close();
}
return out.toByteArray();
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
while (true) {
int readCount = in.read(buffer);
if (readCount < 0) {
break;
}
out.write(buffer, 0, readCount);
}
}
private static void copy(File file, OutputStream out) throws IOException {
InputStream in = new FileInputStream(file);
try {
copy(in, out);
} finally {
in.close();
}
}
public static String throwableToString(Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
public static void unzip(byte[] content, final File destinationDir) throws IOException {
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(content));
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
String fileName = zipEntry.getName();
File file = new File(destinationDir + File.separator + fileName);
// log.finest("Unzipping: " + file.getAbsolutePath());
if (zipEntry.isDirectory()) {
file.mkdirs();
} else {
file.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(file);
try {
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
} finally {
closeQuietly(fos);
}
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
public static File getStablizerHome() {
String home = System.getenv("STABILIZER_HOME");
if (home == null) {
return new File(System.getProperty("user.dir"));
} else {
return new File(home);
}
}
public static void closeQuietly(Socket socket) {
if (socket == null) {
return;
}
try {
socket.close();
} catch (IOException ignore) {
}
}
public static void closeQuietly(Closeable... closeables) {
for (Closeable c : closeables) {
closeQuietly(c);
}
}
public static void closeQuietly(Closeable c) {
if (c == null) return;
try {
c.close();
} catch (IOException ignore) {
}
}
public static void closeQuietly(XMLStreamWriter c) {
if (c == null) return;
try {
c.close();
} catch (XMLStreamException ignore) {
}
}
public static void sleepSeconds(int seconds) {
try {
Thread.sleep(seconds * 1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static void sleepMillis(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static void sleepNanos(long nanos) {
if (nanos <= 0) {
return;
}
LockSupport.parkNanos(nanos);
}
public static void exitWithError(ILogger logger, String msg) {
logger.severe(msg);
System.exit(1);
}
private Utils() {
}
public static String secondsToHuman(long seconds) {
long time = seconds;
long s = time % 60;
time = time / 60;
long m = time % 60;
time = time / 60;
long h = time % 24;
time = time / 24;
long days = time;
StringBuilder sb = new StringBuilder();
sb.append(format("%02d", days)).append("d ")
.append(format("%02d", h)).append("h ")
.append(format("%02d", m)).append("m ")
.append(format("%02d", s)).append("s");
return sb.toString();
}
public static Properties loadProperties(File file) {
Properties properties = new Properties();
final FileInputStream in;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
//should not be thrown since it is already verified that the property file exist.
throw new RuntimeException(e);
}
try {
properties.load(in);
return properties;
} catch (IOException e) {
throw new RuntimeException(format("Failed to load testsuite property file [%s]", file.getAbsolutePath()), e);
} finally {
Utils.closeQuietly(in);
}
}
public static String join(Iterable<?> collection) {
return join(collection, DEFAULT_DELIMITER);
}
public static String join(Iterable<?> collection, String delimiter) {
StringBuilder builder = new StringBuilder();
Iterator<?> iterator = collection.iterator();
while (iterator.hasNext()) {
Object o = iterator.next();
builder.append(o);
if (iterator.hasNext()) {
builder.append(delimiter);
}
}
return builder.toString();
}
public static File getFile(OptionSpec<String> spec, OptionSet options, String desc) {
File file = newFile(options.valueOf(spec));
if (!file.exists()) {
exitWithError(log, format("%s [%s] does not exist\n", desc, file));
}
return file;
}
public static List<File> getFilesFromClassPath(String classpath) throws IOException {
if (classpath == null) {
return Collections.EMPTY_LIST;
}
List<File> files = new LinkedList<File>();
for (String filePath : classpath.split(";")) {
File file = new File(filePath);
if (file.getName().contains("*")) {
File parent = file.getParentFile();
if (!parent.isDirectory()) {
throw new IOException(format("Cannot convert classpath to java.io.File. [%s] is not a directory", parent));
}
String regex = file.getName().replace("*", "(.*)");
for (File child : parent.listFiles()) {
if (child.getName().matches(regex)) {
files.add(child);
}
}
} else if (file.exists()) {
files.add(file);
} else {
Utils.exitWithError(log, format("Cannot convert classpath to java.io.File. [%s] doesn't exist", filePath));
}
}
return files;
}
}
|
Made padRight() and padLeft() more safe for invalid arguments.
|
stabilizer/src/main/java/com/hazelcast/stabilizer/Utils.java
|
Made padRight() and padLeft() more safe for invalid arguments.
|
|
Java
|
apache-2.0
|
e16bc548422568d1fa190e26853860682af5b383
| 0
|
anthcp/cdap,mpouttuclarke/cdap,hsaputra/cdap,caskdata/cdap,chtyim/cdap,mpouttuclarke/cdap,chtyim/cdap,hsaputra/cdap,mpouttuclarke/cdap,anthcp/cdap,caskdata/cdap,mpouttuclarke/cdap,hsaputra/cdap,hsaputra/cdap,anthcp/cdap,caskdata/cdap,caskdata/cdap,caskdata/cdap,chtyim/cdap,chtyim/cdap,mpouttuclarke/cdap,chtyim/cdap,chtyim/cdap,anthcp/cdap,hsaputra/cdap,caskdata/cdap,anthcp/cdap
|
/*
* Copyright © 2015 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package co.cask.cdap.template.etl.batch.source;
import co.cask.cdap.api.annotation.Description;
import co.cask.cdap.api.annotation.Name;
import co.cask.cdap.api.annotation.Plugin;
import co.cask.cdap.api.common.Bytes;
import co.cask.cdap.api.data.format.StructuredRecord;
import co.cask.cdap.api.data.schema.Schema;
import co.cask.cdap.api.dataset.DatasetProperties;
import co.cask.cdap.api.dataset.lib.KeyValue;
import co.cask.cdap.api.dataset.lib.KeyValueTable;
import co.cask.cdap.api.templates.plugins.PluginConfig;
import co.cask.cdap.template.etl.api.Emitter;
import co.cask.cdap.template.etl.api.PipelineConfigurer;
import co.cask.cdap.template.etl.api.batch.BatchSource;
import co.cask.cdap.template.etl.api.batch.BatchSourceContext;
import co.cask.cdap.template.etl.common.BatchFileFilter;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* A {@link BatchSource} to use any distributed file system as a Source.
*/
@Plugin(type = "source")
@Name("FileBatchSource")
@Description("Batch source for File Systems")
public class FileBatchSource extends BatchSource<LongWritable, Object, StructuredRecord> {
public static final String INPUT_NAME_CONFIG = "input.path.name";
public static final String INPUT_REGEX_CONFIG = "input.path.regex";
public static final String LAST_TIME_READ = "last.time.read";
public static final String CUTOFF_READ_TIME = "cutoff.read.time";
public static final String USE_TIMEFILTER = "timefilter";
public static final Schema DEFAULT_SCHEMA = Schema.recordOf(
"event",
Schema.Field.of("ts", Schema.of(Schema.Type.LONG)),
Schema.Field.of("body", Schema.of(Schema.Type.STRING))
);
private static final String REGEX_DESCRIPTION = "Regex to filter out filenames in the path. " +
"To use the TimeFilter, input \"timefilter\". The TimeFilter assumes that it " +
"is reading in files with the File log naming convention of YYYY-MM-DD-HH-mm-SS-Tag. The TimeFilter " +
"reads in files from the previous hour if the timeTable field is left blank. So if it's currently " +
"2015-06-16-15 (June 16th 2015, 3pm), it will read in files that contain 2015-06-16-14 in the filename. " +
"If the field timeTable is present, then it will read files in that haven't been read yet.";
private static final String FILESYSTEM_PROPERTIES_DESCRIPTION = "JSON of the properties needed for the " +
"distributed file system. The formatting needs to be as follows:\n{\n\t\"<property name>\" : " +
"\"<property value>\", ...\n}. For example, the property names needed for S3 are \"fs.s3n.awsSecretAccessKey\" " +
"and \"fs.s3n.awsAccessKeyId\".";
private static final String PATH_DESCRIPTION = "Path to file(s) to be read. If a directory is specified, " +
"terminate the path name with a \'/\'";
private static final String TABLE_DESCRIPTION = "Name of the Table that keeps track of the last time files " +
"were read in.";
private static final String INPUT_FORMAT_CLASS_DESCRIPTION = "Name of the input format class, which must be a " +
"subclass of FileInputFormat. Defaults to TextInputFormat";
private static final String FILESYSTEM_DESCRIPTION = "Distributed file system to read in from.";
private static final Gson GSON = new Gson();
private static final Logger LOG = LoggerFactory.getLogger(FileBatchSource.class);
private static final Type ARRAYLIST_DATE_TYPE = new TypeToken<ArrayList<Date>>() { }.getType();
private static final Type MAP_STRING_STRING_TYPE = new TypeToken<Map<String, String>>() { }.getType();
private final FileBatchConfig config;
private KeyValueTable table;
private Date prevHour;
private String datesToRead;
public FileBatchSource(FileBatchConfig config) {
this.config = config;
}
@Override
public void configurePipeline(PipelineConfigurer pipelineConfigurer) {
if (config.timeTable != null) {
pipelineConfigurer.createDataset(config.timeTable, KeyValueTable.class, DatasetProperties.EMPTY);
}
}
@Override
public void prepareRun(BatchSourceContext context) throws Exception {
//SimpleDateFormat needs to be local because it is not threadsafe
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH");
//calculate date one hour ago, rounded down to the nearest hour
prevHour = new Date(context.getLogicalStartTime() - TimeUnit.HOURS.toMillis(1));
Calendar cal = Calendar.getInstance();
cal.setTime(prevHour);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
prevHour = cal.getTime();
Job job = context.getHadoopJob();
Configuration conf = job.getConfiguration();
if (config.fileSystemProperties != null) {
Map<String, String> properties = GSON.fromJson(config.fileSystemProperties, MAP_STRING_STRING_TYPE);
for (Map.Entry<String, String> entry : properties.entrySet()) {
conf.set(entry.getKey(), entry.getValue());
}
}
if (config.fileRegex != null) {
conf.set(INPUT_REGEX_CONFIG, config.fileRegex);
}
conf.set(INPUT_NAME_CONFIG, config.path);
if (config.timeTable != null) {
table = context.getDataset(config.timeTable);
datesToRead = Bytes.toString(table.read(LAST_TIME_READ));
if (datesToRead == null) {
List<Date> firstRun = Lists.newArrayList(new Date(0));
datesToRead = GSON.toJson(firstRun, ARRAYLIST_DATE_TYPE);
}
List<Date> attempted = Lists.newArrayList(prevHour);
String updatedDatesToRead = GSON.toJson(attempted, ARRAYLIST_DATE_TYPE);
if (!updatedDatesToRead.equals(datesToRead)) {
table.write(LAST_TIME_READ, updatedDatesToRead);
}
conf.set(LAST_TIME_READ, datesToRead);
}
conf.set(CUTOFF_READ_TIME, dateFormat.format(prevHour));
if (config.inputFormatClass != null) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Class<? extends FileInputFormat> classType = (Class<? extends FileInputFormat>)
classLoader.loadClass(config.inputFormatClass);
job.setInputFormatClass(classType);
}
FileInputFormat.setInputPathFilter(job, BatchFileFilter.class);
FileInputFormat.addInputPath(job, new Path(config.path));
}
@Override
public void transform(KeyValue<LongWritable, Object> input, Emitter<StructuredRecord> emitter) throws Exception {
StructuredRecord output = StructuredRecord.builder(DEFAULT_SCHEMA)
.set("ts", System.currentTimeMillis())
.set("body", input.getValue().toString())
.build();
emitter.emit(output);
}
@Override
public void onRunFinish(boolean succeeded, BatchSourceContext context) {
if (!succeeded && table != null && USE_TIMEFILTER.equals(config.fileRegex)) {
List<Date> existing = GSON.fromJson(Bytes.toString(table.read(LAST_TIME_READ)), ARRAYLIST_DATE_TYPE);
List<Date> failed = GSON.fromJson(datesToRead, ARRAYLIST_DATE_TYPE);
failed.add(prevHour);
failed.addAll(existing);
table.write(LAST_TIME_READ, GSON.toJson(failed, ARRAYLIST_DATE_TYPE));
}
}
/**
* Config class that contains all the properties needed for the file source.
*/
public static class FileBatchConfig extends PluginConfig {
@Name("fileSystem")
@Description(FILESYSTEM_DESCRIPTION)
private String fileSystem;
@Name("fileSystemProperties")
@Nullable
@Description(FILESYSTEM_PROPERTIES_DESCRIPTION)
private String fileSystemProperties;
@Name("path")
@Description(PATH_DESCRIPTION)
private String path;
@Name("fileRegex")
@Nullable
@Description(REGEX_DESCRIPTION)
private String fileRegex;
@Name("timeTable")
@Nullable
@Description(TABLE_DESCRIPTION)
private String timeTable;
@Name("inputFormatClass")
@Nullable
@Description(INPUT_FORMAT_CLASS_DESCRIPTION)
private String inputFormatClass;
public FileBatchConfig(String fileSystem, String path, @Nullable String regex, @Nullable String timeTable,
@Nullable String inputFormatClass, @Nullable String fileSystemProperties) {
this.fileSystem = fileSystem;
this.fileSystemProperties = fileSystemProperties;
this.path = path;
this.fileRegex = regex;
this.timeTable = timeTable;
this.inputFormatClass = inputFormatClass;
}
}
}
|
cdap-app-templates/cdap-etl/cdap-etl-lib/src/main/java/co/cask/cdap/template/etl/batch/source/FileBatchSource.java
|
/*
* Copyright © 2015 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package co.cask.cdap.template.etl.batch.source;
import co.cask.cdap.api.annotation.Description;
import co.cask.cdap.api.annotation.Name;
import co.cask.cdap.api.annotation.Plugin;
import co.cask.cdap.api.common.Bytes;
import co.cask.cdap.api.data.format.StructuredRecord;
import co.cask.cdap.api.data.schema.Schema;
import co.cask.cdap.api.dataset.DatasetProperties;
import co.cask.cdap.api.dataset.lib.KeyValue;
import co.cask.cdap.api.dataset.lib.KeyValueTable;
import co.cask.cdap.api.templates.plugins.PluginConfig;
import co.cask.cdap.template.etl.api.Emitter;
import co.cask.cdap.template.etl.api.PipelineConfigurer;
import co.cask.cdap.template.etl.api.batch.BatchSource;
import co.cask.cdap.template.etl.api.batch.BatchSourceContext;
import co.cask.cdap.template.etl.common.BatchFileFilter;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* A {@link BatchSource} to use any distributed file system as a Source.
*/
@Plugin(type = "source")
@Name("FileBatchSource")
@Description("Batch source for File Systems")
public class FileBatchSource extends BatchSource<LongWritable, Object, StructuredRecord> {
public static final String INPUT_NAME_CONFIG = "input.path.name";
public static final String INPUT_REGEX_CONFIG = "input.path.regex";
public static final String LAST_TIME_READ = "last.time.read";
public static final String CUTOFF_READ_TIME = "cutoff.read.time";
public static final String USE_TIMEFILTER = "timefilter";
public static final Schema DEFAULT_SCHEMA = Schema.recordOf(
"event",
Schema.Field.of("ts", Schema.of(Schema.Type.LONG)),
Schema.Field.of("body", Schema.of(Schema.Type.STRING))
);
private static final String REGEX_DESCRIPTION = "Regex to filter out filenames in the path. " +
"To use the TimeFilter, input \"timefilter\". The TimeFilter assumes that it " +
"is reading in files with the File log naming convention of YYYY-MM-DD-HH-mm-SS-Tag. The TimeFilter " +
"reads in files from the previous hour if the timeTable field is left blank. So if it's currently " +
"2015-06-16-15 (June 16th 2015, 3pm), it will read in files that contain 2015-06-16-14 in the filename. " +
"If the field timeTable is present, then it will read files in that haven't been read yet.";
private static final String FILESYSTEM_PROPERTIES_DESCRIPTION = "JSON of the properties needed for the " +
"distributed file system. The formatting needs to be as follows:\n{\n\t\"<property name>\" : " +
"\"<property value>\", ...\n}. For example, the property names needed for S3 are \"fs.s3n.awsSecretAccessKey\" " +
"and \"fs.s3n.awsAccessKeyId\".";
private static final String PATH_DESCRIPTION = "Path to file(s) to be read. If a directory is specified, " +
"terminate the path name with a \'/\'";
private static final String TABLE_DESCRIPTION = "Name of the Table that keeps track of the last time files " +
"were read in.";
private static final String INPUT_FORMAT_CLASS_DESCRIPTION = "Name of the input format class, which must be a " +
"subclass of FileInputFormat. Defaults to TextInputFormat";
private static final String FILESYSTEM_DESCRIPTION = "Distributed file system to read in from.";
private static final Gson GSON = new Gson();
private static final Logger LOG = LoggerFactory.getLogger(FileBatchSource.class);
private static final Type ARRAYLIST_DATE_TYPE = new TypeToken<ArrayList<Date>>() { }.getType();
private static final Type MAP_STRING_STRING_TYPE = new TypeToken<Map<String, String>>() { }.getType();
private final FileBatchConfig config;
private KeyValueTable table;
private Date prevHour;
private String datesToRead;
public FileBatchSource(FileBatchConfig config) {
this.config = config;
}
@Override
public void configurePipeline(PipelineConfigurer pipelineConfigurer) {
if (config.timeTable != null) {
pipelineConfigurer.createDataset(config.timeTable, KeyValueTable.class, DatasetProperties.EMPTY);
}
}
@Override
public void prepareRun(BatchSourceContext context) throws Exception {
//SimpleDateFormat needs to be local because it is not threadsafe
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH");
//calculate date one hour ago, rounded down to the nearest hour
prevHour = new Date(context.getLogicalStartTime() - TimeUnit.HOURS.toMillis(1));
Calendar cal = Calendar.getInstance();
cal.setTime(prevHour);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
prevHour = cal.getTime();
Job job = context.getHadoopJob();
Configuration conf = job.getConfiguration();
if (config.fileSystemProperties != null) {
Map<String, String> properties = GSON.fromJson(config.fileSystemProperties, MAP_STRING_STRING_TYPE);
for (Map.Entry<String, String> entry : properties.entrySet()) {
conf.set(entry.getKey(), entry.getValue());
}
}
if (config.fileRegex != null) {
conf.set(INPUT_REGEX_CONFIG, config.fileRegex);
}
conf.set(INPUT_NAME_CONFIG, config.path);
if (config.timeTable != null) {
table = context.getDataset(config.timeTable);
String datesToRead = Bytes.toString(table.read(LAST_TIME_READ));
if (datesToRead == null) {
List<Date> firstRun = Lists.newArrayList(new Date(0));
datesToRead = GSON.toJson(firstRun, ARRAYLIST_DATE_TYPE);
}
List<Date> attempted = Lists.newArrayList(prevHour);
String updatedDatesToRead = GSON.toJson(attempted, ARRAYLIST_DATE_TYPE);
if (!updatedDatesToRead.equals(datesToRead)) {
table.write(LAST_TIME_READ, updatedDatesToRead);
}
conf.set(LAST_TIME_READ, datesToRead);
}
conf.set(CUTOFF_READ_TIME, dateFormat.format(prevHour));
if (config.inputFormatClass != null) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Class<? extends FileInputFormat> classType = (Class<? extends FileInputFormat>)
classLoader.loadClass(config.inputFormatClass);
job.setInputFormatClass(classType);
}
FileInputFormat.setInputPathFilter(job, BatchFileFilter.class);
FileInputFormat.addInputPath(job, new Path(config.path));
}
@Override
public void transform(KeyValue<LongWritable, Object> input, Emitter<StructuredRecord> emitter) throws Exception {
StructuredRecord output = StructuredRecord.builder(DEFAULT_SCHEMA)
.set("ts", System.currentTimeMillis())
.set("body", input.getValue().toString())
.build();
emitter.emit(output);
}
@Override
public void onRunFinish(boolean succeeded, BatchSourceContext context) {
if (!succeeded && table != null && USE_TIMEFILTER.equals(config.fileRegex)) {
List<Date> existing = GSON.fromJson(Bytes.toString(table.read(LAST_TIME_READ)), ARRAYLIST_DATE_TYPE);
List<Date> failed = GSON.fromJson(datesToRead, ARRAYLIST_DATE_TYPE);
failed.add(prevHour);
failed.addAll(existing);
table.write(LAST_TIME_READ, GSON.toJson(failed, ARRAYLIST_DATE_TYPE));
}
}
/**
* Config class that contains all the properties needed for the file source.
*/
public static class FileBatchConfig extends PluginConfig {
@Name("fileSystem")
@Description(FILESYSTEM_DESCRIPTION)
private String fileSystem;
@Name("fileSystemProperties")
@Nullable
@Description(FILESYSTEM_PROPERTIES_DESCRIPTION)
private String fileSystemProperties;
@Name("path")
@Description(PATH_DESCRIPTION)
private String path;
@Name("fileRegex")
@Nullable
@Description(REGEX_DESCRIPTION)
private String fileRegex;
@Name("timeTable")
@Nullable
@Description(TABLE_DESCRIPTION)
private String timeTable;
@Name("inputFormatClass")
@Nullable
@Description(INPUT_FORMAT_CLASS_DESCRIPTION)
private String inputFormatClass;
public FileBatchConfig(String fileSystem, String path, @Nullable String regex, @Nullable String timeTable,
@Nullable String inputFormatClass, @Nullable String fileSystemProperties) {
this.fileSystem = fileSystem;
this.fileSystemProperties = fileSystemProperties;
this.path = path;
this.fileRegex = regex;
this.timeTable = timeTable;
this.inputFormatClass = inputFormatClass;
}
}
}
|
CDAP-3066 fix FileBatchSource
|
cdap-app-templates/cdap-etl/cdap-etl-lib/src/main/java/co/cask/cdap/template/etl/batch/source/FileBatchSource.java
|
CDAP-3066 fix FileBatchSource
|
|
Java
|
apache-2.0
|
d5e4d45480a5f4bee29d348e7c4926c61ea8cd7a
| 0
|
SuperMardle/CodingInterviews,xMardle/CodingInterviews
|
package com.matao;
import java.util.Arrays;
/**
* Created by matao on 2018/8/24.
* <p>
* 一个长度为 n 的数组里所有数字都是在 0 - n-1 范围内。
* 数组中某些数字重复,但不知道有几个数字重复了,也不知道重复次数。
* 请找出数组中任意一个重复的数字。
* input: { 2, 3, 1, 0, 2, 5, 3 }
* output: 2 或 3
*/
public class Q03_DuplicationInArray {
/**
* 暴力求解
* 时间复杂度 O(n^2)
* 空间复杂度 O(1)
*/
public int findDuplication1(int[] data) {
if (data == null || data.length < 2) {
return -1;
}
for (int i = 0; i < data.length; i++) {
for (int j = i + 1; j < data.length; j++) {
if (data[i] == data[j]) {
return data[i];
}
}
}
return -1;
}
/**
* 先进行排序,再一趟遍历。 会改变原数组顺序
* 时间复杂度 O(nlogn)
* 空间复杂度 O(1)
*/
public int findDuplication2(int[] data) {
if (data == null || data.length < 2) {
return -1;
}
Arrays.sort(data);
int prev = data[0];
for (int i = 1; i < data.length; i++) {
if (data[i] == prev) {
return prev;
} else {
prev = data[i];
}
}
return -1;
}
/**
* 借助哈希原理,不会修改原始数据
* n 的数组里所有数字都是在 0 - n-1 范围内, 该哈希解构总长度n,能容纳所有数字,
* 一旦碰撞,则表示有重复数字。
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
public int findDuplication3(int[] data) {
if (data == null || data.length < 2) {
return -1;
}
int[] hashTable = new int[data.length];
for (int item : data) {
if (hashTable[item] == 1) {
return item;
}
hashTable[item] = 1;
}
return -1;
}
/**
* 因为数组长度 n, 且数字都是在 0 - n-1 范围内,
* 根据数字特点,那么重排序后,若没有重复的数字,数字 i 将出现在下标为 i 的位置。即 i == data[i]
* 由于数组中有重复的数字,有些位置可能存在多个数字,同时有些位置可能没有数字。
* 当 data[i] !== i 时候,则将 data[i] 交换到它应该出现的位置,即 data[data[i]]
* 时间复杂度 O(n)
* 空间复杂度 O(1)
*/
public int findDuplication4(int[] data) {
if (data == null || data.length < 2) {
return -1;
}
for (int i = 0; i < data.length; i++) {
while (data[i] != i) {
/**
* pos i ... temp
* value temp data[temp]
*/
int temp = data[i];
if (temp == data[temp]) {
return temp;
}
data[i] = data[temp];
data[temp] = temp;
}
}
return -1;
}
/**
* 二分的思路计数,不修改原始数据,
* 时间复杂度 O(nlogn)
* 空间复杂度 O(1)
*/
public int findDuplication5(int[] data) {
if (data == null || data.length < 2) {
return -1;
}
int start = 0, end = data.length - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
int count = countRange(data, start, mid);
if (start == end) {
if (count > 1) {
return start;
} else {
break;
}
}
if (count > (mid - start + 1)) {
end = mid;
} else {
start = mid + 1;
}
}
return -1;
}
private int countRange(int[] data, int start, int end) {
int count = 0;
for (int i = 0; i < data.length; i++) {
if (start <= data[i] && end >= data[i])
count++;
}
return count;
}
}
|
src/main/java/com/matao/Q03_DuplicationInArray.java
|
package com.matao;
import java.util.Arrays;
/**
* Created by matao on 2018/8/24.
* <p>
* 一个长度为 n 的数组里所有数字都是在 0 - n-1 范围内。
* 数组中某些数字重复,但不知道有几个数字重复了,也不知道重复次数。
* 请找出数组中任意一个重复的数字。
* input: { 2, 3, 1, 0, 2, 5, 3 }
* output: 2 或 3
*/
public class Q03_DuplicationInArray {
/**
* 暴力求解
* 时间复杂度 O(n^2)
* 空间复杂度 O(1)
*/
public int findDuplication1(int[] data) {
if (data == null || data.length < 2) {
return -1;
}
for (int i = 0; i < data.length; i++) {
for (int j = i + 1; j < data.length; j++) {
if (data[i] == data[j]) {
return data[i];
}
}
}
return -1;
}
/**
* 先进行排序,再一趟遍历。 会改变原数组顺序
* 时间复杂度 O(nlogn)
* 空间复杂度 O(1)
*/
public int findDuplication2(int[] data) {
if (data == null || data.length < 2) {
return -1;
}
Arrays.sort(data);
int prev = data[0];
for (int i = 1; i < data.length; i++) {
if (data[i] == prev) {
return prev;
} else {
prev = data[i];
}
}
return -1;
}
/**
* 借助哈希原理,不会修改原始数据
* n 的数组里所有数字都是在 0 - n-1 范围内, 该哈希解构总长度n,能容纳所有数字,
* 一旦碰撞,则表示有重复数字。
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
public int findDuplication3(int[] data) {
if (data == null || data.length < 2) {
return -1;
}
int[] hashTable = new int[data.length];
for (int item : data) {
if (hashTable[item] == 1) {
return item;
}
hashTable[item] = 1;
}
return -1;
}
/**
* 因为数组长度 n, 且数字都是在 0 - n-1 范围内。
* 根据数字特点排序,会修改原始数据,
* 时间复杂度 O(n)
* 空间复杂度 O(1)
*/
public int findDuplication4(int[] data) {
if (data == null || data.length < 2) {
return -1;
}
for (int i = 0; i < data.length; i++) {
while (data[i] != i) { // i 位置上的数data[i]与下标 i 不相等,则判断 data[i] 与 data[data[i]] 是否相等
if (data[i] == data[data[i]]) {
return data[i];
}
int temp = data[i];
data[i] = data[data[i]];
data[data[i]] = temp;
}
}
return -1;
}
/**
* 二分的思路计数,不修改原始数据,
* 时间复杂度 O(nlogn)
* 空间复杂度 O(1)
*/
public int findDuplication5(int[] data) {
if (data == null || data.length < 2) {
return -1;
}
int start = 0, end = data.length - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
int count = countRange(data, start, mid);
if (start == end) {
if (count > 1) {
return start;
} else {
break;
}
}
if (count > (mid - start + 1)) {
end = mid;
} else {
start = mid + 1;
}
}
return -1;
}
private int countRange(int[] data, int start, int end) {
int count = 0;
for (int i = 0; i < data.length; i++) {
if (start <= data[i] && end >= data[i])
count++;
}
return count;
}
}
|
fix: findDuplication4 incorrect swap
|
src/main/java/com/matao/Q03_DuplicationInArray.java
|
fix: findDuplication4 incorrect swap
|
|
Java
|
apache-2.0
|
f8a80266e31eb16ee3999aebc3519639af6b9095
| 0
|
quann169/MotownBlueCurrent,motown-io/motown,pqtoan/motown
|
/**
* Copyright (C) 2013 Motown.IO (info@motown.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.motown.operatorapi.viewmodel.persistence.entities;
import io.motown.domain.api.chargingstation.Accessibility;
import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
@Entity
public class ChargingStation {
@Id
private String id;
private String protocol;
private Date lastTimeBooted;
private Date lastContact;
private Boolean accepted;
private Double latitude;
private Double longitude;
private String addressline1;
private String addressline2;
private String postalCode;
private String city;
private String region;
private String country;
private Accessibility accessibility;
@ElementCollection
private Set<OpeningTime> openingTimes = new HashSet<>();
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = Evse.class)
private Set<Evse> evses = new HashSet<>();
private ChargingStation() {
// Private no-arg constructor for Hibernate.
}
public ChargingStation(String id) {
this.id = id;
this.accepted = false;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public Boolean isAccepted() {
return accepted;
}
public void setAccepted(Boolean accepted) {
this.accepted = accepted;
}
public Date getLastTimeBooted() {
return lastTimeBooted != null ? new Date(lastTimeBooted.getTime()) : null;
}
public void setLastTimeBooted(Date lastTimeBooted) {
this.lastTimeBooted = lastTimeBooted != null ? new Date(lastTimeBooted.getTime()) : null;
}
public Date getLastContact() {
return lastContact != null ? new Date(lastContact.getTime()) : null;
}
public void setLastContact(Date lastContact) {
this.lastContact = lastContact != null ? new Date(lastContact.getTime()) : null;
}
public String getId() {
return id;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public String getAddressline1() {
return addressline1;
}
public void setAddressline1(String addressline1) {
this.addressline1 = addressline1;
}
public String getAddressline2() {
return addressline2;
}
public void setAddressline2(String addressline2) {
this.addressline2 = addressline2;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Accessibility getAccessibility() {
return accessibility;
}
public void setAccessibility(Accessibility accessibility) {
this.accessibility = accessibility; }
public Set<OpeningTime> getOpeningTimes() {
return openingTimes;
}
public void setOpeningTimes(Set<OpeningTime> openingTimes) {
this.openingTimes = openingTimes;
}
public Set<Evse> getEvses() {
return evses;
}
public void setEvses(Set<Evse> evses) {
this.evses = evses;
}
}
|
operator-api/view-model/src/main/java/io/motown/operatorapi/viewmodel/persistence/entities/ChargingStation.java
|
/**
* Copyright (C) 2013 Motown.IO (info@motown.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.motown.operatorapi.viewmodel.persistence.entities;
import io.motown.domain.api.chargingstation.Accessibility;
import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
@Entity
public class ChargingStation {
@Id
private String id;
private String protocol;
private Date updated;
private Date created;
private Date lastTimeBooted;
private Date lastContact;
private Boolean accepted;
private Double latitude;
private Double longitude;
private String addressline1;
private String addressline2;
private String postalCode;
private String city;
private String region;
private String country;
private Accessibility accessibility;
@ElementCollection
private Set<OpeningTime> openingTimes = new HashSet<>();
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = Evse.class)
private Set<Evse> evses = new HashSet<>();
private ChargingStation() {
// Private no-arg constructor for Hibernate.
}
public ChargingStation(String id) {
this.id = id;
this.accepted = false;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public Boolean isAccepted() {
return accepted;
}
public void setAccepted(Boolean accepted) {
this.accepted = accepted;
}
public Date getLastTimeBooted() {
return lastTimeBooted != null ? new Date(lastTimeBooted.getTime()) : null;
}
public void setLastTimeBooted(Date lastTimeBooted) {
this.lastTimeBooted = lastTimeBooted != null ? new Date(lastTimeBooted.getTime()) : null;
}
public Date getLastContact() {
return lastContact != null ? new Date(lastContact.getTime()) : null;
}
public void setLastContact(Date lastContact) {
this.lastContact = lastContact != null ? new Date(lastContact.getTime()) : null;
}
public String getId() {
return id;
}
public Date getUpdated() {
return updated != null ? new Date(updated.getTime()) : null;
}
public Date getCreated() {
return created != null ? new Date(created.getTime()) : null;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public String getAddressline1() {
return addressline1;
}
public void setAddressline1(String addressline1) {
this.addressline1 = addressline1;
}
public String getAddressline2() {
return addressline2;
}
public void setAddressline2(String addressline2) {
this.addressline2 = addressline2;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Accessibility getAccessibility() {
return accessibility;
}
public void setAccessibility(Accessibility accessibility) {
this.accessibility = accessibility;
}
public Set<OpeningTime> getOpeningTimes() {
return openingTimes;
}
public void setOpeningTimes(Set<OpeningTime> openingTimes) {
this.openingTimes = openingTimes;
}
public Set<Evse> getEvses() {
return evses;
}
public void setEvses(Set<Evse> evses) {
this.evses = evses;
}
@PrePersist
protected void onCreate() {
Date now = new Date();
created = now;
updated = now;
}
@PreUpdate
protected void onUpdate() {
updated = new Date();
}
}
|
Removed timestamps from charging station in API
|
operator-api/view-model/src/main/java/io/motown/operatorapi/viewmodel/persistence/entities/ChargingStation.java
|
Removed timestamps from charging station in API
|
|
Java
|
bsd-3-clause
|
e997b2e9baf4067a17a0abab68d7dd842455c806
| 0
|
ksclarke/basex,BaseXdb/basex,ksclarke/basex,ksclarke/basex,JensErat/basex,joansmith/basex,JensErat/basex,drmacro/basex,BaseXdb/basex,joansmith/basex,drmacro/basex,joansmith/basex,deshmnnit04/basex,drmacro/basex,dimitarp/basex,joansmith/basex,ksclarke/basex,JensErat/basex,BaseXdb/basex,vincentml/basex,vincentml/basex,ksclarke/basex,joansmith/basex,dimitarp/basex,JensErat/basex,drmacro/basex,dimitarp/basex,ksclarke/basex,drmacro/basex,ksclarke/basex,vincentml/basex,deshmnnit04/basex,JensErat/basex,dimitarp/basex,ksclarke/basex,vincentml/basex,joansmith/basex,ksclarke/basex,deshmnnit04/basex,BaseXdb/basex,BaseXdb/basex,deshmnnit04/basex,deshmnnit04/basex,drmacro/basex,BaseXdb/basex,BaseXdb/basex,dimitarp/basex,drmacro/basex,dimitarp/basex,dimitarp/basex,deshmnnit04/basex,ksclarke/basex,vincentml/basex,JensErat/basex,joansmith/basex,deshmnnit04/basex,ksclarke/basex,joansmith/basex,drmacro/basex,joansmith/basex,dimitarp/basex,BaseXdb/basex,dimitarp/basex,deshmnnit04/basex,BaseXdb/basex,vincentml/basex,drmacro/basex,vincentml/basex,drmacro/basex,deshmnnit04/basex,deshmnnit04/basex,JensErat/basex,vincentml/basex,BaseXdb/basex,dimitarp/basex,dimitarp/basex,joansmith/basex,drmacro/basex,BaseXdb/basex,vincentml/basex,JensErat/basex,joansmith/basex,vincentml/basex,ksclarke/basex,dimitarp/basex,vincentml/basex,drmacro/basex,BaseXdb/basex,JensErat/basex,deshmnnit04/basex,JensErat/basex,joansmith/basex,deshmnnit04/basex,JensErat/basex,JensErat/basex,vincentml/basex
|
package org.basex.server;
import static org.basex.core.Text.*;
import java.io.IOException;
import org.basex.core.Context;
import org.basex.core.Progress;
import org.basex.core.Prop;
import org.basex.data.XMLSerializer;
import org.basex.io.PrintOutput;
import org.basex.query.QueryException;
import org.basex.query.QueryProcessor;
import org.basex.query.item.Item;
import org.basex.query.iter.Iter;
/**
* Container for processes executing a query with iterative results.
*
* @author Workgroup DBIS, University of Konstanz 2005-10, ISC License
* @author Andreas Weiler
* @author Christian Gruen
*/
final class QueryProcess extends Progress {
/** Processor. */
private final QueryProcessor proc;
/** Serializer. */
private final XMLSerializer xml;
/** Database context. */
private final Context ctx;
/** Monitored flag. */
private boolean monitored;
/** Iterator. */
private Iter iter;
/** Current item. */
private Item item;
/**
* Constructor.
* @param q query string
* @param o output
* @param c database context
* @throws IOException I/O exception
*/
QueryProcess(final String q, final PrintOutput o, final Context c)
throws IOException {
proc = new QueryProcessor(q, c);
xml = new XMLSerializer(o);
ctx = c;
}
/**
* Constructor.
* @throws QueryException query exception
*/
void init() throws QueryException {
proc.parse();
if(!proc.ctx.updating) startTimeout(ctx.prop.num(Prop.TIMEOUT));
monitored = true;
ctx.lock.before(proc.ctx.updating);
iter = proc.iter();
item = iter.next();
}
/**
* Serializes the next item and tests if more items can be returned.
* @return result of check
* @throws IOException Exception
* @throws QueryException query exception
*/
boolean next() throws IOException, QueryException {
if(stopped) throw new QueryException(SERVERTIMEOUT);
final boolean more = item != null;
if(more) {
// item found: send {ITEM}
item.serialize(xml);
item = iter.next();
}
return !more;
}
/**
* Closes the query process.
* @throws IOException I/O exception
*/
void close() throws IOException {
proc.stopTimeout();
xml.close();
proc.close();
if(monitored) ctx.lock.after(proc.ctx.updating);
}
}
|
src/main/java/org/basex/server/QueryProcess.java
|
package org.basex.server;
import static org.basex.core.Text.*;
import java.io.IOException;
import org.basex.core.Context;
import org.basex.core.Progress;
import org.basex.core.Prop;
import org.basex.data.XMLSerializer;
import org.basex.io.PrintOutput;
import org.basex.query.QueryException;
import org.basex.query.QueryProcessor;
import org.basex.query.item.Item;
import org.basex.query.iter.Iter;
/**
* Container for processes executing a query with iterative results.
*
* @author Workgroup DBIS, University of Konstanz 2005-10, ISC License
* @author Andreas Weiler
* @author Christian Gruen
*/
final class QueryProcess extends Progress {
/** Processor. */
private final QueryProcessor proc;
/** Serializer. */
private final XMLSerializer xml;
/** Database context. */
private final Context ctx;
/** Monitored flag. */
private boolean monitored;
/** Iterator. */
private Iter iter;
/** Current item. */
private Item item;
/**
* Constructor.
* @param q query string
* @param o output
* @param c database context
* @throws IOException I/O exception
*/
QueryProcess(final String q, final PrintOutput o, final Context c)
throws IOException {
proc = new QueryProcessor(q, c);
xml = new XMLSerializer(o);
ctx = c;
}
/**
* Constructor.
* @throws QueryException query exception
*/
void init() throws QueryException {
startTimeout(ctx.prop.num(Prop.TIMEOUT));
proc.parse();
monitored = true;
ctx.lock.before(proc.ctx.updating);
iter = proc.iter();
item = iter.next();
}
/**
* Serializes the next item and tests if more items can be returned.
* @return result of check
* @throws IOException Exception
* @throws QueryException query exception
*/
boolean next() throws IOException, QueryException {
if(stopped) throw new QueryException(SERVERTIMEOUT);
final boolean more = item != null;
if(more) {
// item found: send {ITEM}
item.serialize(xml);
item = iter.next();
}
return !more;
}
/**
* Closes the query process.
* @throws IOException I/O exception
*/
void close() throws IOException {
proc.stopTimeout();
xml.close();
proc.close();
if(monitored) ctx.lock.after(proc.ctx.updating);
}
}
|
timeout only for reading queries
|
src/main/java/org/basex/server/QueryProcess.java
|
timeout only for reading queries
|
|
Java
|
bsd-3-clause
|
3722dd9f69f6bac777bfaf2b43e3c2ed1c079bc3
| 0
|
NUBIC/psc-mirror,NUBIC/psc-mirror,NUBIC/psc-mirror,NUBIC/psc-mirror
|
package edu.northwestern.bioinformatics.studycalendar.web.admin;
import edu.northwestern.bioinformatics.studycalendar.security.AuthenticationSystemConfiguration;
import static edu.northwestern.bioinformatics.studycalendar.security.AuthenticationSystemConfiguration.*;
import edu.northwestern.bioinformatics.studycalendar.security.plugin.KnownAuthenticationSystem;
import edu.northwestern.bioinformatics.studycalendar.utils.breadcrumbs.DefaultCrumb;
import edu.northwestern.bioinformatics.studycalendar.web.PscAbstractCommandController;
import edu.northwestern.bioinformatics.studycalendar.web.ControllerTools;
import edu.nwu.bioinformatics.commons.spring.ValidatableValidator;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.apache.commons.lang.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* @author Rhett Sutphin
*/
public class AuthenticationSystemConfigurationController extends PscAbstractCommandController<AuthenticationSystemConfigurationCommand> {
private AuthenticationSystemConfiguration authenticationSystemConfiguration;
private ControllerTools controllerTools;
public AuthenticationSystemConfigurationController() {
setCrumb(new DefaultCrumb("Configure authentication system"));
setValidator(new ValidatableValidator());
}
@Override
protected Object getCommand(HttpServletRequest request) throws Exception {
String requestedAuthSystem = request.getParameter("conf[" + AUTHENTICATION_SYSTEM.getKey() + "].value");
String custom = request.getParameter("customAuthenticationSystemClass");
if (!StringUtils.isBlank(custom)) {
requestedAuthSystem = custom;
}
return new AuthenticationSystemConfigurationCommand(
requestedAuthSystem, authenticationSystemConfiguration, getApplicationContext());
}
@Override
protected boolean suppressBinding(HttpServletRequest request) {
return !isSubmit(request);
}
private boolean isSubmit(HttpServletRequest request) {
return !"GET".equals(request.getMethod());
}
@Override
protected ModelAndView handle(
AuthenticationSystemConfigurationCommand command, BindException errors,
HttpServletRequest request, HttpServletResponse response
) throws Exception {
boolean isCustom = command.getWorkConfiguration().isCustomAuthenticationSystem();
String system = command.getWorkConfiguration().get(AUTHENTICATION_SYSTEM);
Map<String, Object> model = new HashMap<String, Object>(errors.getModel());
model.put("knownAuthenticationSystems", KnownAuthenticationSystem.values());
model.put("authenticationSystemKey", AUTHENTICATION_SYSTEM.getKey());
model.put("isCustomAuthenticationSystem", isCustom);
model.put("currentAuthenticationSystemDisplayName",
isCustom ? system : KnownAuthenticationSystem.valueOf(system).getDisplayName());
if (controllerTools.isAjaxRequest(request)) {
return new ModelAndView("admin/ajax/updateSelectedAuthenticationSystem", model);
} else if (isSubmit(request) && !errors.hasErrors()) {
command.apply();
return new ModelAndView("redirect:/pages/admin/configureAuthentication");
} else {
return new ModelAndView("admin/configureAuthenticationSystem", model);
}
}
////// CONFIGURATION
public void setAuthenticationSystemConfiguration(AuthenticationSystemConfiguration authenticationSystemConfiguration) {
this.authenticationSystemConfiguration = authenticationSystemConfiguration;
}
public void setControllerTools(ControllerTools controllerTools) {
this.controllerTools = controllerTools;
}
}
|
src/main/java/edu/northwestern/bioinformatics/studycalendar/web/admin/AuthenticationSystemConfigurationController.java
|
package edu.northwestern.bioinformatics.studycalendar.web.admin;
import edu.northwestern.bioinformatics.studycalendar.security.AuthenticationSystemConfiguration;
import static edu.northwestern.bioinformatics.studycalendar.security.AuthenticationSystemConfiguration.*;
import edu.northwestern.bioinformatics.studycalendar.security.plugin.KnownAuthenticationSystem;
import edu.northwestern.bioinformatics.studycalendar.utils.breadcrumbs.DefaultCrumb;
import edu.northwestern.bioinformatics.studycalendar.web.PscAbstractCommandController;
import edu.northwestern.bioinformatics.studycalendar.web.ControllerTools;
import edu.nwu.bioinformatics.commons.spring.ValidatableValidator;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* @author Rhett Sutphin
*/
public class AuthenticationSystemConfigurationController extends PscAbstractCommandController<AuthenticationSystemConfigurationCommand> {
private AuthenticationSystemConfiguration authenticationSystemConfiguration;
private ControllerTools controllerTools;
public AuthenticationSystemConfigurationController() {
setCrumb(new DefaultCrumb("Configure authentication system"));
setValidator(new ValidatableValidator());
}
@Override
protected Object getCommand(HttpServletRequest request) throws Exception {
String requestedAuthSystem = request.getParameter("conf[" + AUTHENTICATION_SYSTEM.getKey() + "].value");
return new AuthenticationSystemConfigurationCommand(
requestedAuthSystem, authenticationSystemConfiguration, getApplicationContext());
}
@Override
protected boolean suppressBinding(HttpServletRequest request) {
return !isSubmit(request);
}
private boolean isSubmit(HttpServletRequest request) {
return !"GET".equals(request.getMethod());
}
@Override
protected ModelAndView handle(
AuthenticationSystemConfigurationCommand command, BindException errors,
HttpServletRequest request, HttpServletResponse response
) throws Exception {
boolean isCustom = command.getWorkConfiguration().isCustomAuthenticationSystem();
String system = command.getWorkConfiguration().get(AUTHENTICATION_SYSTEM);
Map<String, Object> model = new HashMap<String, Object>(errors.getModel());
model.put("knownAuthenticationSystems", KnownAuthenticationSystem.values());
model.put("authenticationSystemKey", AUTHENTICATION_SYSTEM.getKey());
model.put("isCustomAuthenticationSystem", isCustom);
model.put("currentAuthenticationSystemDisplayName",
isCustom ? system : KnownAuthenticationSystem.valueOf(system).getDisplayName());
if (controllerTools.isAjaxRequest(request)) {
return new ModelAndView("admin/ajax/updateSelectedAuthenticationSystem", model);
} else if (isSubmit(request) && !errors.hasErrors()) {
command.apply();
return new ModelAndView("redirect:/pages/admin/configureAuthentication");
} else {
return new ModelAndView("admin/configureAuthenticationSystem", model);
}
}
////// CONFIGURATION
public void setAuthenticationSystemConfiguration(AuthenticationSystemConfiguration authenticationSystemConfiguration) {
this.authenticationSystemConfiguration = authenticationSystemConfiguration;
}
public void setControllerTools(ControllerTools controllerTools) {
this.controllerTools = controllerTools;
}
}
|
Set correct value when returning to custom authentication system
git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@2424 0d517254-b314-0410-acde-c619094fa49f
|
src/main/java/edu/northwestern/bioinformatics/studycalendar/web/admin/AuthenticationSystemConfigurationController.java
|
Set correct value when returning to custom authentication system
|
|
Java
|
bsd-3-clause
|
7f82468b0e0b9ecd5c51c3ed0eff5ac4e15ef292
| 0
|
ndexbio/ndex-rest,ndexbio/ndex-rest,ndexbio/ndex-rest,ndexbio/ndex-rest
|
/**
* Copyright (c) 2013, 2016, The Regents of the University of California, The Cytoscape Consortium
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package org.ndexbio.rest.services;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.solr.client.solrj.SolrServerException;
import org.cxio.aspects.datamodels.ATTRIBUTE_DATA_TYPE;
import org.cxio.aspects.datamodels.NetworkAttributesElement;
import org.cxio.metadata.MetaDataCollection;
import org.cxio.metadata.MetaDataElement;
import org.cxio.util.JsonWriter;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import org.ndexbio.common.NdexClasses;
import org.ndexbio.common.cx.CXAspectWriter;
import org.ndexbio.common.cx.CXNetworkFileGenerator;
import org.ndexbio.common.cx.OpaqueAspectIterator;
import org.ndexbio.common.models.dao.postgresql.Helper;
import org.ndexbio.common.models.dao.postgresql.NetworkDAO;
import org.ndexbio.common.models.dao.postgresql.TaskDAO;
import org.ndexbio.common.models.dao.postgresql.UserDAO;
import org.ndexbio.common.solr.NetworkGlobalIndexManager;
import org.ndexbio.common.util.NdexUUIDFactory;
import org.ndexbio.common.util.Util;
import org.ndexbio.model.cx.Provenance;
import org.ndexbio.model.exceptions.ForbiddenOperationException;
import org.ndexbio.model.exceptions.InvalidNetworkException;
import org.ndexbio.model.exceptions.NdexException;
import org.ndexbio.model.exceptions.NetworkConcurrentModificationException;
import org.ndexbio.model.exceptions.ObjectNotFoundException;
import org.ndexbio.model.exceptions.UnauthorizedOperationException;
import org.ndexbio.model.object.NdexPropertyValuePair;
import org.ndexbio.model.object.NdexProvenanceEventType;
import org.ndexbio.model.object.Permissions;
import org.ndexbio.model.object.Priority;
import org.ndexbio.model.object.ProvenanceEntity;
import org.ndexbio.model.object.ProvenanceEvent;
import org.ndexbio.model.object.SimplePropertyValuePair;
import org.ndexbio.model.object.Status;
import org.ndexbio.model.object.Task;
import org.ndexbio.model.object.TaskType;
import org.ndexbio.model.object.User;
import org.ndexbio.model.object.network.NetworkSummary;
import org.ndexbio.model.object.network.VisibilityType;
import org.ndexbio.model.tools.ProvenanceHelpers;
import org.ndexbio.rest.Configuration;
import org.ndexbio.rest.annotations.ApiDoc;
import org.ndexbio.task.CXNetworkLoadingTask;
import org.ndexbio.task.NdexServerQueue;
import org.ndexbio.task.SolrTaskDeleteNetwork;
import org.ndexbio.task.SolrTaskRebuildNetworkIdx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
@Path("/v2/network")
public class NetworkServiceV2 extends NdexService {
static Logger logger = LoggerFactory.getLogger(NetworkService.class);
static private final String readOnlyParameter = "readOnly";
public NetworkServiceV2(@Context HttpServletRequest httpRequest
// @Context org.jboss.resteasy.spi.HttpResponse response
) {
super(httpRequest);
// response.getOutputHeaders().putSingle("WWW-Authenticate", "Basic");
}
/**************************************************************************
* Returns network provenance.
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
* @throws NdexException
* @throws SQLException
*
**************************************************************************/
@PermitAll
@GET
@Path("/{networkid}/provenance")
@Produces("application/json")
@ApiDoc("This method retrieves the 'provenance' attribute of the network specified by 'networkId', if it " +
"exists. The returned value is a JSON ProvenanceEntity object which in turn contains a " +
"tree-structure of ProvenanceEvent and ProvenanceEntity objects that describe the provenance " +
"history of the network. See the document NDEx Provenance History for a detailed description of " +
"this structure and best practices for its use.")
public ProvenanceEntity getProvenance(
@PathParam("networkid") final String networkIdStr,
@QueryParam("accesskey") String accessKey)
throws IllegalArgumentException, JsonParseException, JsonMappingException, IOException, NdexException, SQLException {
logger.info("[start: Getting provenance of network {}]", networkIdStr);
UUID networkId = UUID.fromString(networkIdStr);
try (NetworkDAO daoNew = new NetworkDAO()) {
if ( !daoNew.isReadable(networkId, getLoggedInUserId()) && (!daoNew.accessKeyIsValid(networkId, accessKey)))
throw new UnauthorizedOperationException("Network " + networkId + " is not readable to this user.");
logger.info("[end: Got provenance of network {}]", networkId);
return daoNew.getProvenance(networkId);
}
}
/**************************************************************************
* Updates network provenance.
* @throws Exception
*
**************************************************************************/
@PUT
@Path("/{networkid}/provenance")
@Produces("application/json")
@ApiDoc("Updates the 'provenance' field of the network specified by 'networkId' to be the " +
"ProvenanceEntity object in the PUT data. The ProvenanceEntity object is expected to represent " +
"the current state of the network and to contain a tree-structure of ProvenanceEvent and " +
"ProvenanceEntity objects that describe the networks provenance history.")
public void setProvenance(@PathParam("networkid")final String networkIdStr, final ProvenanceEntity provenance)
throws Exception {
logger.info("[start: Updating provenance of network {}]", networkIdStr);
User user = getLoggedInUser();
setProvenance_aux(networkIdStr, provenance, user);
}
protected static void setProvenance_aux(final String networkIdStr, final ProvenanceEntity provenance, User user)
throws Exception {
try (NetworkDAO daoNew = new NetworkDAO()){
UUID networkId = UUID.fromString(networkIdStr);
if ( !daoNew.isWriteable(networkId, user.getExternalId())) {
logger.error("[end: No write permissions for user account {} on network {}]",
user.getUserName(), networkId);
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if(daoNew.isReadOnly(networkId)) {
daoNew.close();
logger.info("[end: Can't modify readonly network {}]", networkId);
throw new NdexException ("Can't update readonly network.");
}
if (!daoNew.networkIsValid(networkId))
throw new InvalidNetworkException();
if ( daoNew.networkIsLocked(networkId,6)) {
daoNew.close();
throw new NetworkConcurrentModificationException ();
}
daoNew.lockNetwork(networkId);
daoNew.setProvenance(networkId, provenance);
daoNew.commit();
//Recreate the CX file
// NetworkSummary fullSummary = daoNew.getNetworkSummaryById(networkId);
// MetaDataCollection metadata = daoNew.getMetaDataCollection(networkId);
CXNetworkFileGenerator g = new CXNetworkFileGenerator(networkId, daoNew, new Provenance(provenance));
g.reCreateCXFile();
daoNew.unlockNetwork(networkId);
return ; // provenance; // daoNew.getProvenance(networkUUID);
} catch (Exception e) {
//if (null != daoNew) daoNew.rollback();
logger.error("[end: Updating provenance of network {}. Exception caught:]{}", networkIdStr, e);
throw e;
} finally {
logger.info("[end: Updated provenance of network {}]", networkIdStr);
}
}
/**************************************************************************
* Sets network properties.
* @throws Exception
*
**************************************************************************/
@PUT
@Path("/{networkid}/properties")
@Produces("application/json")
@ApiDoc("Updates the 'properties' field of the network specified by 'networkId' to be the list of " +
"NdexPropertyValuePair objects in the PUT data.")
public int setNetworkProperties(
@PathParam("networkid")final String networkId,
final List<NdexPropertyValuePair> properties)
throws Exception {
// logger.info("[start: Updating properties of network {}]", networkId);
User user = getLoggedInUser();
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO daoNew = new NetworkDAO()) {
if(daoNew.isReadOnly(networkUUID)) {
logger.info("[end: Can't modify readonly network {}]", networkId);
throw new NdexException ("Can't update readonly network.");
}
if ( !daoNew.isWriteable(networkUUID, user.getExternalId())) {
logger.error("[end: No write permissions for user account {} on network {}]",
user.getUserName(), networkId);
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if ( daoNew.networkIsLocked(networkUUID,10)) {
throw new NetworkConcurrentModificationException ();
}
if ( !daoNew.networkIsValid(networkUUID))
throw new InvalidNetworkException();
daoNew.lockNetwork(networkUUID);
try {
int i = daoNew.setNetworkProperties(networkUUID, properties);
//DW: Handle provenance
ProvenanceEntity oldProv = daoNew.getProvenance(networkUUID);
ProvenanceEntity newProv = new ProvenanceEntity();
newProv.setUri( oldProv.getUri() );
NetworkSummary summary = daoNew.getNetworkSummaryById(networkUUID);
Helper.populateProvenanceEntity(newProv, summary);
ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.SET_NETWORK_PROPERTIES, summary.getModificationTime());
List<SimplePropertyValuePair> eventProperties = new ArrayList<>();
Helper.addUserInfoToProvenanceEventProperties( eventProperties, user);
for( NdexPropertyValuePair vp : properties )
{
SimplePropertyValuePair svp = new SimplePropertyValuePair(vp.getPredicateString(), vp.getValue());
eventProperties.add(svp);
}
event.setProperties(eventProperties);
List<ProvenanceEntity> oldProvList = new ArrayList<>();
oldProvList.add(oldProv);
event.setInputs(oldProvList);
newProv.setCreationEvent(event);
daoNew.setProvenance(networkUUID, newProv);
NetworkSummary fullSummary = daoNew.getNetworkSummaryById(networkUUID);
//update the networkProperty aspect
List<NetworkAttributesElement> attrs = getNetworkAttributeAspectsFromSummary(fullSummary);
if ( attrs.size() > 0 ) {
try (CXAspectWriter writer = new CXAspectWriter(Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/aspects/"
+ NetworkAttributesElement.ASPECT_NAME) ) {
for ( NetworkAttributesElement e : attrs) {
writer.writeCXElement(e);
writer.flush();
}
}
}
//update metadata
MetaDataCollection metadata = daoNew.getMetaDataCollection(networkUUID);
MetaDataElement elmt = metadata.getMetaDataElement(NetworkAttributesElement.ASPECT_NAME);
if ( elmt == null) {
elmt = new MetaDataElement();
}
elmt.setElementCount(Long.valueOf(attrs.size()));
daoNew.updateMetadataColleciton(networkUUID, metadata);
//Recreate the CX file
CXNetworkFileGenerator g = new CXNetworkFileGenerator(networkUUID, fullSummary, metadata, newProv);
g.reCreateCXFile();
// update the solr Index
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,true,false));
return i;
} finally {
daoNew.unlockNetwork(networkUUID);
}
} catch (Exception e) {
//logger.severe("Error occurred when update network properties: " + e.getMessage());
//e.printStackTrace();
//if (null != daoNew) daoNew.rollback();
logger.error("Updating properties of network {}. Exception caught:]{}", networkId, e);
throw new NdexException(e.getMessage(), e);
} finally {
logger.info("[end: Updated properties of network {}]", networkId);
}
}
/*
*
* Operations returning Networks
*
*/
@PermitAll
@GET
@Path("/{networkid}/summary")
@Produces("application/json")
@ApiDoc("Retrieves a NetworkSummary object based on the network specified by 'networkId'. This " +
"method returns an error if the network is not found or if the authenticated user does not have " +
"READ permission for the network.")
public NetworkSummary getNetworkSummary(
@PathParam("networkid") final String networkIdStr ,
@QueryParam("accesskey") String accessKey /*,
@Context org.jboss.resteasy.spi.HttpResponse response*/)
throws IllegalArgumentException, NdexException, SQLException, JsonParseException, JsonMappingException, IOException {
try (NetworkDAO dao = new NetworkDAO()) {
UUID userId = getLoggedInUserId();
UUID networkId = UUID.fromString(networkIdStr);
if ( dao.isReadable(networkId, userId) || dao.accessKeyIsValid(networkId, accessKey)) {
NetworkSummary summary = dao.getNetworkSummaryById(networkId);
// response.getOutputHeaders().putSingle("WWW-Authenticate", "Basic");
return summary;
}
throw new UnauthorizedOperationException ("Unauthorized access to network " + networkId);
}
}
@PermitAll
@GET
@Path("/{networkid}/aspect")
@ApiDoc("The getAspectElement method returns elements in the specified aspect up to the given limit.")
public Response getNetworkCXMetadataCollection( @PathParam("networkid") final String networkId,
@QueryParam("accesskey") String accessKey)
throws Exception {
logger.info("[start: Getting CX metadata from network {}]", networkId);
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO dao = new NetworkDAO() ) {
if ( dao.isReadable(networkUUID, getLoggedInUserId()) || dao.accessKeyIsValid(networkUUID, accessKey)) {
MetaDataCollection mdc = dao.getMetaDataCollection(networkUUID);
logger.info("[end: Return CX metadata from network {}]", networkId);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonWriter wtr = JsonWriter.createInstance(baos,true);
mdc.toJson(wtr);
String s = baos.toString();//"java.nio.charset.StandardCharsets.UTF_8");
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(s).build();
// return mdc;
}
throw new UnauthorizedOperationException("User doesn't have access to this network.");
}
}
@PermitAll
@GET
@Path("/{networkid}/aspect/{aspectname}/metadata")
@ApiDoc("Return the metadata of the given aspect name.")
public MetaDataElement getNetworkCXMetadata(
@PathParam("networkid") final String networkId,
@PathParam("aspectname") final String aspectName
)
throws Exception {
logger.info("[start: Getting {} metadata from network {}]", aspectName, networkId);
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO dao = new NetworkDAO() ) {
if ( dao.isReadable(networkUUID, getLoggedInUserId())) {
MetaDataCollection mdc = dao.getMetaDataCollection(networkUUID);
logger.info("[end: Return CX metadata from network {}]", networkId);
return mdc.getMetaDataElement(aspectName);
}
throw new UnauthorizedOperationException("User doesn't have access to this network.");
}
}
@PermitAll
@GET
@Path("/{networkid}/aspect/{aspectname}")
@ApiDoc("The getAspectElement method returns elements in the specified aspect up to the given limit.")
public Response getAspectElements( @PathParam("networkid") final String networkId,
@PathParam("aspectname") final String aspectName,
@DefaultValue("-1") @QueryParam("size") int limit) throws SQLException, NdexException
{
logger.info("[start: Getting one aspect in network {}]", networkId);
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO dao = new NetworkDAO()) {
if ( !dao.isReadable(networkUUID, getLoggedInUserId())) {
throw new UnauthorizedOperationException("User doesn't have access to this network.");
}
FileInputStream in;
try {
in = new FileInputStream(
Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/aspects/" + aspectName);
} catch (FileNotFoundException e) {
throw new ObjectNotFoundException("Aspect "+ aspectName + " not found in this network.");
}
if ( limit <= 0) {
logger.info("[end: Return cached network {}]", networkId);
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(in).build();
}
PipedInputStream pin = new PipedInputStream();
PipedOutputStream out;
try {
out = new PipedOutputStream(pin);
} catch (IOException e) {
try {
pin.close();
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
throw new NdexException("IOExcetion when creating the piped output stream: "+ e.getMessage());
}
new CXAspectElementsWriterThread(out,in, aspectName, limit).start();
logger.info("[end: Return get one aspect in network {}]", networkId);
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(pin).build();
}
}
@PermitAll
@GET
@Path("/{networkid}")
public Response getCompleteNetworkAsCX( @PathParam("networkid") final String networkId,
@QueryParam("download") boolean isDownload,
@QueryParam("accesskey") String accessKey)
throws IllegalArgumentException, NdexException, SQLException, JsonParseException, JsonMappingException, IOException {
logger.info("[start: Getting complete network {}]", networkId);
String title = null;
try (NetworkDAO dao = new NetworkDAO()) {
UUID networkUUID = UUID.fromString(networkId);
if ( ! dao.isReadable(networkUUID, getLoggedInUserId()) && (!dao.accessKeyIsValid(networkUUID, accessKey)))
throw new UnauthorizedOperationException("User doesn't have read access to this network.");
NetworkSummary s = dao.getNetworkSummaryById(networkUUID);
title = s.getName();
}
if ( title == null || title.length() < 1) {
title = networkId;
}
title.replace('"', '_');
String cxFilePath = Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/network.cx";
try {
FileInputStream in = new FileInputStream(cxFilePath) ;
// setZipFlag();
logger.info("[end: Return network {}]", networkId);
ResponseBuilder r = Response.ok();
if ( isDownload)
r.header("Content-Disposition", "attachment; filename=\"" + title + ".cx\"");
return r.type(MediaType.APPLICATION_JSON_TYPE).entity(in).build();
} catch (IOException e) {
logger.error("[end: Ndex server can't find file: {}]", e.getMessage());
throw new NdexException ("Ndex server can't find file: " + e.getMessage());
}
}
@PermitAll
@GET
@Path("/{networkid}/sample")
@ApiDoc("The getSampleNetworkAsCX method enables an application to obtain a sample of the given network as a CX " +
"structure. The sample network is a 500 random edge subnetwork of the original network if it was created by the server automatically. "
+ "User can also upload their own sample network if they "
+ "")
public Response getSampleNetworkAsCX( @PathParam("networkid") final String networkIdStr ,
@QueryParam("accesskey") String accessKey)
throws IllegalArgumentException, NdexException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
try (NetworkDAO dao = new NetworkDAO()) {
if ( ! dao.isReadable(networkId, getLoggedInUserId()) && (!dao.accessKeyIsValid(networkId, accessKey)))
throw new UnauthorizedOperationException("User doesn't have read access to this network.");
}
String cxFilePath = Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/sample.cx";
try {
FileInputStream in = new FileInputStream(cxFilePath) ;
// setZipFlag();
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(in).build();
} catch ( FileNotFoundException e) {
throw new ObjectNotFoundException("Sample network of " + networkId + " not found");
}
}
@GET
@Path("/{networkid}/accesskey")
@Produces("application/json")
public Map<String,String> getNetworkAccessKey(@PathParam("networkid") final String networkIdStr)
throws IllegalArgumentException, NdexException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
try (NetworkDAO dao = new NetworkDAO()) {
if ( ! dao.isAdmin(networkId, getLoggedInUserId()))
throw new UnauthorizedOperationException("User is not admin of this network.");
String key = dao.getNetworkAccessKey(networkId);
if (key == null || key.length()==0)
return null;
Map<String,String> result = new HashMap<>(1);
result.put("accessKey", key);
return result;
}
}
@PUT
@Path("/{networkid}/accesskey")
@Produces("application/json")
public Map<String,String> disableEnableNetworkAccessKey(@PathParam("networkid") final String networkIdStr,
@QueryParam("action") String action)
throws IllegalArgumentException, NdexException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
if ( ! action.equalsIgnoreCase("disable") && ! action.equalsIgnoreCase("enable"))
throw new NdexException("Value of 'action' paramter can only be 'disable' or 'enable'");
try (NetworkDAO dao = new NetworkDAO()) {
if ( ! dao.isAdmin(networkId, getLoggedInUserId()))
throw new UnauthorizedOperationException("User is not admin of this network.");
String key = null;
if ( action.equalsIgnoreCase("disable"))
dao.disableNetworkAccessKey(networkId);
else
key = dao.enableNetworkAccessKey(networkId);
dao.commit();
if (key == null || key.length()==0)
return null;
Map<String,String> result = new HashMap<>(1);
result.put("accessKey", key);
return result;
}
}
@PUT
@Path("/{networkid}/sample")
@ApiDoc("This method enables an application to set the sample network as a CX " +
"structure. The sample network should be small ( no more than 500 edges normally)")
public void setSampleNetwork( @PathParam("networkid") final String networkId,
String CXString)
throws IllegalArgumentException, NdexException, SQLException {
logger.info("[start: Getting sample network {}]", networkId);
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO dao = new NetworkDAO()) {
if ( ! dao.isAdmin(networkUUID, getLoggedInUserId()))
throw new UnauthorizedOperationException("User is not admin of this network.");
if ( !dao.networkIsLocked(networkUUID))
throw new NetworkConcurrentModificationException();
if ( !dao.networkIsValid(networkUUID))
throw new InvalidNetworkException();
}
String cxFilePath = Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/sample.cx";
try (FileWriter w = new FileWriter(cxFilePath)){
w.write(CXString);
} catch ( IOException e) {
throw new NdexException("Failed to write sample network of " + networkId + ": " + e.getMessage(), e);
}
}
/*
private class CXNetworkWriterThread extends Thread {
private OutputStream o;
private String networkId;
public CXNetworkWriterThread (OutputStream out, String networkUUIDStr) {
o = out;
networkId = networkUUIDStr;
}
public void run() {
try (CXNetworkExporter dao = new CXNetworkExporter (networkId) ) {
dao.writeNetworkInCX(o, true);
} catch (IOException e) {
logger.error("IOException in CXNetworkWriterThread: " + e.getMessage());
e.printStackTrace();
} catch (NdexException e1) {
logger.error("Ndex error: " + e1.getMessage());
e1.printStackTrace();
} catch (Exception e1) {
logger.error("Ndex excption: " + e1.getMessage());
e1.printStackTrace();
} finally {
try {
o.flush();
o.close();
} catch (IOException e) {
e.printStackTrace();
logger.error("Failed to close outputstream in CXNetworkWriterThread.");
}
}
}
} */
/* private class CXNetworkQueryWriterThread extends Thread {
private OutputStream o;
private String networkId;
private CXSimplePathQuery parameters;
public CXNetworkQueryWriterThread (OutputStream out, String networkUUIDStr, CXSimplePathQuery query) {
o = out;
networkId = networkUUIDStr;
this.parameters = query;
}
public void run() {
try (CXNetworkExporter dao = new CXNetworkExporter (networkId) ) {
dao.exportSubnetworkInCX(o, parameters,true);
} catch (IOException e) {
logger.error("IOException in CXNetworkWriterThread: " + e.getMessage());
e.printStackTrace();
} catch (NdexException e1) {
logger.error("Ndex error: " + e1.getMessage());
e1.printStackTrace();
} catch (Exception e1) {
logger.error("Ndex excption: " + e1.getMessage());
e1.printStackTrace();
} finally {
try {
o.flush();
o.close();
} catch (IOException e) {
e.printStackTrace();
logger.error("Failed to close outputstream in CXNetworkWriterThread.");
}
}
}
}
*/
private class CXAspectElementsWriterThread extends Thread {
private OutputStream o;
// private String networkId;
private FileInputStream in;
// private String aspect;
private int limit;
public CXAspectElementsWriterThread (OutputStream out, FileInputStream inputStream, String aspectName, int limit) {
o = out;
// this.networkId = networkId;
// aspect = aspectName;
this.limit = limit;
in = inputStream;
}
public void run() {
try {
OpaqueAspectIterator asi = new OpaqueAspectIterator(in);
try (CXAspectWriter wtr = new CXAspectWriter (o)) {
for ( int i = 0 ; i < limit && asi.hasNext() ; i++) {
wtr.writeCXElement(asi.next());
}
}
} catch (IOException e) {
logger.error("IOException in CXAspectElementWriterThread: " + e.getMessage());
} catch (Exception e1) {
logger.error("Ndex exception: " + e1.getMessage());
} finally {
try {
o.flush();
o.close();
} catch (IOException e) {
logger.error("Failed to close outputstream in CXElementWriterWriterThread");
e.printStackTrace();
}
}
}
}
/*
private class CXNetworkAspectsWriterThread extends Thread {
private OutputStream o;
private String networkId;
private Set<String> aspects;
public CXNetworkAspectsWriterThread (OutputStream out, String networkId, Set<String> aspectNames) {
o = out;
this.networkId = networkId;
this.aspects = aspectNames;
}
public void run() {
try (CXNetworkExporter dao = new CXNetworkExporter (networkId)) {
dao.writeAspectsInCX(o, aspects, true);
} catch (IOException e) {
logger.error("IOException in CXNetworkAspectsWriterThread: " + e.getMessage());
e.printStackTrace();
} catch (NdexException e1) {
logger.error("Ndex error: " + e1.getMessage());
e1.printStackTrace();
} catch (Exception e1) {
logger.error("Ndex exception: " + e1.getMessage());
e1.printStackTrace();
} finally {
try {
o.flush();
o.close();
} catch (IOException e) {
e.printStackTrace();
logger.error("Failed to close outputstream in CXNetworkAspectsWriterThread. " + e.getMessage());
}
}
}
} */
/* private class CXNetworkLoadThread extends Thread {
private UUID networkId;
public CXNetworkLoadThread (UUID networkUUID ) {
this.networkId = networkUUID;
}
public void run() {
}
} */
/*
private ProvenanceEntity getProvenanceEntityFromMultiPart(Map<String, List<InputPart>> uploadForm) throws NdexException, IOException {
List<InputPart> parts = uploadForm.get("provenance");
if (parts == null)
return null;
StringBuffer sb = new StringBuffer();
for (InputPart inputPart : parts) {
org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl p =
(org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl) inputPart;
sb.append(p.getBodyAsString());
}
ObjectMapper mapper = new ObjectMapper();
ProvenanceEntity entity = mapper.readValue(sb.toString(), ProvenanceEntity.class);
if (entity == null || entity.getUri() == null)
throw new NdexException ("Malformed provenance parameter found in posted form data.");
return entity;
} */
/* Note: Will be implemented in services
@PermitAll
@GET
@Path("/export/{networkId}/{format}")
@Produces("application/json")
@ApiDoc("Retrieve an entire network specified by 'networkId' as a Network object. (Compare this method to " +
"getCompleteNetworkAsPropertyGraph).")
public String exportNetwork( @PathParam("networkId") final String networkId,
@PathParam("format") final String format)
throws NdexException {
logger.info("[start: request to export network {}]", networkId);
if ( isReadable(networkId) ) {
String networkName =null;
try (NetworkDAO networkdao = new NetworkDAO(NdexDatabase.getInstance().getAConnection())){
networkName = networkdao.getNetworkSummaryById(networkId).getName();
}
Task exportNetworkTask = new Task();
exportNetworkTask.setTaskType(TaskType.EXPORT_NETWORK_TO_FILE);
exportNetworkTask.setPriority(Priority.LOW);
exportNetworkTask.setResource(networkId);
exportNetworkTask.setStatus(Status.QUEUED);
exportNetworkTask.setDescription("Export network \""+ networkName + "\" in " + format + " format");
try {
exportNetworkTask.setFormat(FileFormat.valueOf(format));
} catch ( Exception e) {
logger.error("[end: Exception caught:]{}", e);
throw new NdexException ("Invalid network format for network export.");
}
try (TaskDAO taskDAO = new TaskDAO(NdexDatabase.getInstance().getAConnection()) ){
exportNetworkTask.setTaskOwnerId(getLoggedInUser().getExternalId());
UUID taskId = taskDAO.createTask(exportNetworkTask);
taskDAO.commit();
logger.info("[start: task created to export network {}]", networkId);
return taskId.toString();
} catch (Exception e) {
logger.error("[end: Exception caught:]{}", e);
throw new NdexException(e.getMessage());
}
}
logger.error("[end: User doesn't have read access network {}. Throwing UnauthorizedOperationException]", networkId);
throw new UnauthorizedOperationException("User doesn't have read access to this network.");
}
*/
/**************************************************************************
* Retrieves array of user membership objects
*
* @param networkId
* The network ID.
* @throws IllegalArgumentException
* Bad input.
* @throws ObjectNotFoundException
* The group doesn't exist.
* @throws NdexException
* Failed to query the database.
* @throws SQLException
**************************************************************************/
@GET
@Path("/{networkid}/permission")
@Produces("application/json")
@ApiDoc("Retrieves a list of Membership objects which specify user permissions for the network specified by " +
"'networkId'. The value of the 'permission' parameter constrains the type of the returned Membership " +
"objects and may take the following set of values: READ, WRITE, and ADMIN. READ, WRITE, and ADMIN are mutually exclusive. Memberships of all types can " +
"be retrieved by permission = 'ALL'. The maximum number of Membership objects to retrieve in the query " +
"is set by 'blockSize' (which may be any number chosen by the user) while 'skipBlocks' specifies the " +
"number of blocks that have already been read.")
public Map<String, String> getNetworkUserMemberships(
@PathParam("networkid") final String networkId,
@QueryParam("type") String sourceType,
@QueryParam("permission") final String permissions ,
@DefaultValue("0") @QueryParam("start") int skipBlocks,
@DefaultValue("100") @QueryParam("size") int blockSize) throws NdexException, SQLException {
logger.info("[start: Get {} accounts on network {}, skipBlocks {}, blockSize {}]",
permissions, networkId, skipBlocks, blockSize);
Permissions permission = null;
if ( permissions != null ){
permission = Permissions.valueOf(permissions.toUpperCase());
}
UUID networkUUID = UUID.fromString(networkId);
boolean returnUsers = true;
if ( sourceType != null ) {
if ( sourceType.toLowerCase().equals("group"))
returnUsers = false;
else if ( !sourceType.toLowerCase().equals("user"))
throw new NdexException("Invalid parameter 'type' " + sourceType + " received, it can only be 'user' or 'group'.");
} else
throw new NdexException("Parameter 'type' is required in this function.");
try (NetworkDAO networkDao = new NetworkDAO()) {
if ( !networkDao.isAdmin(networkUUID, getLoggedInUserId()) )
throw new UnauthorizedOperationException("Authenticate user is not the admin of this network.");
Map<String,String> result = returnUsers?
networkDao.getNetworkUserPermissions(networkUUID, permission, skipBlocks, blockSize):
networkDao.getNetworkGroupPermissions(networkUUID,permission,skipBlocks,blockSize);
logger.info("[end: Got {} members returned for network {}]",
result.size(), networkId);
return result;
}
}
@DELETE
@Path("/{networkid}/permission")
@Produces("application/json")
@ApiDoc("Removes any permission for the network specified by 'networkId' for the user specified by 'userUUID': it" +
" deletes any Membership object that specifies a permission for the user-network combination. This method" +
" will return an error if the authenticated user making the request does not have sufficient permissions " +
"to make the deletion or if the network or user is not found. Removal is also denied if it would leave " +
"the network without any user having ADMIN permissions: NDEx does not permit networks to become 'orphans'" +
" without any owner.")
public int deleteNetworkPermission(
@PathParam("networkid") final String networkIdStr,
@QueryParam("userid") String userIdStr,
@QueryParam("groupid") String groupIdStr
)
throws IllegalArgumentException, NdexException, SolrServerException, IOException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
UUID userId = null;
if ( userIdStr != null)
userId = UUID.fromString(userIdStr);
UUID groupId = null;
if ( groupIdStr != null)
groupId = UUID.fromString(groupIdStr);
if ( userId == null && groupId == null)
throw new NdexException ("Either userid or groupid parameter need to be set for this function.");
if ( userId !=null && groupId != null)
throw new NdexException ("userid and gorupid can't both be set for this function.");
try (NetworkDAO networkDao = new NetworkDAO()){
// User user = getLoggedInUser();
// networkDao.checkPermissionOperationCondition(networkId, user.getExternalId());
if (!networkDao.isAdmin(networkId,getLoggedInUserId())) {
if ( userId != null && !userId.equals(getLoggedInUserId())) {
throw new UnauthorizedOperationException("Unable to delete network permisison: user need to be admin of this network or grantee of this permission.");
}
if ( groupId!=null ) {
throw new UnauthorizedOperationException("Unable to delete network permission: user is not an admin of this network.");
}
}
if( !networkDao.networkIsValid(networkId))
throw new InvalidNetworkException();
int count;
if ( userId !=null)
count = networkDao.revokeUserPrivilege(networkId, userId);
else
count = networkDao.revokeGroupPrivilege(networkId, groupId);
// update the solr Index
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,true,false));
return count;
}
}
/*
*
* Operations on Network permissions
*
*/
@PUT
@Path("/{networkid}/permission")
@Produces("application/json")
@ApiDoc("POSTs a Membership object to update the permission of a user specified by userUUID for the network " +
"specified by networkUUID. The permission is updated to the value specified in the 'permission' field of " +
"the Membership. This method returns 1 if the update is performed and 0 if the update is redundant, " +
"where the user already has the specified permission. It also returns an error if the authenticated user " +
"making the request does not have sufficient permissions or if the network or user is not found. It also " +
"returns an error if it would leave the network without any user having ADMIN permissions: NDEx does not " +
"permit networks to become 'orphans' without any owner. Because we only allow user to be the administrator of a network, "
+ "Granting ADMIN permission to another user will move the admin privilege (ownership) from the network's"
+ " previous administrator (owner) to the new user.")
public int updateNetworkPermission(
@PathParam("networkid") final String networkIdStr,
@QueryParam("userid") String userIdStr,
@QueryParam("groupid") String groupIdStr,
@QueryParam("permission") final String permissions
)
throws IllegalArgumentException, NdexException, SolrServerException, IOException, SQLException {
logger.info("[start: Updating membership for network {}]", networkIdStr);
UUID networkId = UUID.fromString(networkIdStr);
UUID userId = null;
if ( userIdStr != null)
userId = UUID.fromString(userIdStr);
UUID groupId = null;
if ( groupIdStr != null)
groupId = UUID.fromString(groupIdStr);
if ( userId == null && groupId == null)
throw new NdexException ("Either userid or groupid parameter need to be set for this function.");
if ( userId !=null && groupId != null)
throw new NdexException ("userid and gorupid can't both be set for this function.");
if ( permissions == null)
throw new NdexException ("permission parameter is required in this function.");
Permissions p = Permissions.valueOf(permissions.toUpperCase());
try (NetworkDAO networkDao = new NetworkDAO()){
User user = getLoggedInUser();
if (!networkDao.isAdmin(networkId,user.getExternalId())) {
throw new UnauthorizedOperationException("Unable to update network permission: user is not an admin of this network.");
}
if ( !networkDao.networkIsValid(networkId))
throw new InvalidNetworkException();
int count;
if ( userId!=null) {
count = networkDao.grantPrivilegeToUser(networkId, userId, p);
} else
count = networkDao.grantPrivilegeToGroup(networkId, groupId, p);
//networkDao.commit();
// update the solr Index
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,true,false));
logger.info("[end: Updated permission for network {}]", networkId);
return count;
}
}
@PUT
@Path("/{networkid}/profile")
@Produces("application/json")
@ApiDoc("This method updates the profile information of the network specified by networkId based on a " +
"POSTed JSON object specifying the attributes to update. Any profile attributes specified will be " +
"updated but attributes that are not specified will have no effect - omission of an attribute does " +
"not mean deletion of that attribute. The network profile attributes that can be updated by this " +
"method are: 'name', 'description', 'version'. visibility are no longer updated by this function. It is managed by setNetworkFlag function from 2.0")
public void updateNetworkProfile(
@PathParam("networkid") final String networkId,
final NetworkSummary partialSummary
)
throws NdexException, SQLException , IOException, IllegalArgumentException
{
// logger.info("[start: Updating profile information of network {}]", networkId);
try (NetworkDAO networkDao = new NetworkDAO()){
User user = getLoggedInUser();
UUID networkUUID = UUID.fromString(networkId);
if(networkDao.isReadOnly(networkUUID)) {
// logger.info("[end: Can't modify readonly network {}]", networkId);
throw new NdexException ("Can't update readonly network.");
}
if ( !networkDao.isWriteable(networkUUID, user.getExternalId())) {
logger.error("[end: No write permissions for user account {} on network {}]",
user.getUserName(), networkId);
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
Map<String,String> newValues = new HashMap<> ();
List<SimplePropertyValuePair> entityProperties = new ArrayList<>();
if ( partialSummary.getName() != null) {
newValues.put(NdexClasses.Network_P_name, partialSummary.getName());
entityProperties.add( new SimplePropertyValuePair("dc:title", partialSummary.getName()) );
}
if ( partialSummary.getDescription() != null) {
newValues.put( NdexClasses.Network_P_desc, partialSummary.getDescription());
entityProperties.add( new SimplePropertyValuePair("description", partialSummary.getDescription()) );
}
if ( partialSummary.getVersion()!=null ) {
newValues.put( NdexClasses.Network_P_version, partialSummary.getVersion());
entityProperties.add( new SimplePropertyValuePair("version", partialSummary.getVersion()) );
}
if ( newValues.size() > 0 ) {
if (!networkDao.networkIsValid(networkUUID))
throw new InvalidNetworkException();
try {
if ( networkDao.networkIsLocked(networkUUID,10)) {
throw new NetworkConcurrentModificationException ();
}
} catch (InterruptedException e2) {
e2.printStackTrace();
throw new NdexException("Failed to check network lock: " + e2.getMessage());
}
try {
networkDao.lockNetwork(networkUUID);
networkDao.updateNetworkProfile(networkUUID, newValues);
//DW: Handle provenance
//Special Logic. Test whether we should record provenance at all.
//If the only thing that has changed is the visibility, we should not add a provenance
//event.
ProvenanceEntity oldProv = networkDao.getProvenance(networkUUID);
String oldName = "", oldDescription = "", oldVersion ="";
if ( oldProv != null ) {
for( SimplePropertyValuePair oldProperty : oldProv.getProperties() ) {
if( oldProperty.getName() == null )
continue;
if( oldProperty.getName().equals("dc:title") )
oldName = oldProperty.getValue().trim();
else if( oldProperty.getName().equals("description") )
oldDescription = oldProperty.getValue().trim();
else if( oldProperty.getName().equals("version") )
oldVersion = oldProperty.getValue().trim();
}
}
//Treat all summary values that are null like ""
String summaryName = partialSummary.getName() == null ? "" : partialSummary.getName().trim();
String summaryDescription = partialSummary.getDescription() == null ? "" : partialSummary.getDescription().trim();
String summaryVersion = partialSummary.getVersion() == null ? "" : partialSummary.getVersion().trim();
ProvenanceEntity newProv = new ProvenanceEntity();
if( !oldName.equals(summaryName) || !oldDescription.equals(summaryDescription) || !oldVersion.equals(summaryVersion) )
{
if ( oldProv !=null ) //TODO: initialize the URI properly when there is null.
newProv.setUri(oldProv.getUri());
newProv.setProperties(entityProperties);
ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.UPDATE_NETWORK_PROFILE, partialSummary.getModificationTime());
List<SimplePropertyValuePair> eventProperties = new ArrayList<>();
Helper.addUserInfoToProvenanceEventProperties(eventProperties, user);
if (partialSummary.getName() != null)
eventProperties.add(new SimplePropertyValuePair("dc:title", partialSummary.getName()));
if (partialSummary.getDescription() != null)
eventProperties.add(new SimplePropertyValuePair("description", partialSummary.getDescription()));
if (partialSummary.getVersion() != null)
eventProperties.add(new SimplePropertyValuePair("version", partialSummary.getVersion()));
event.setProperties(eventProperties);
List<ProvenanceEntity> oldProvList = new ArrayList<>();
oldProvList.add(oldProv);
event.setInputs(oldProvList);
newProv.setCreationEvent(event);
networkDao.setProvenance(networkUUID, newProv);
}
NetworkSummary fullSummary = networkDao.getNetworkSummaryById(networkUUID);
//update the networkProperty aspect
List<NetworkAttributesElement> attrs = getNetworkAttributeAspectsFromSummary(fullSummary);
if ( attrs.size() > 0 ) {
try (CXAspectWriter writer = new CXAspectWriter(Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/aspects/"
+ NetworkAttributesElement.ASPECT_NAME) ) {
for ( NetworkAttributesElement e : attrs) {
writer.writeCXElement(e);
writer.flush();
}
}
}
//update metadata
MetaDataCollection metadata = networkDao.getMetaDataCollection(networkUUID);
MetaDataElement elmt = metadata.getMetaDataElement(NetworkAttributesElement.ASPECT_NAME);
if ( elmt == null) {
elmt = new MetaDataElement();
}
elmt.setElementCount(Long.valueOf(attrs.size()));
networkDao.updateMetadataColleciton(networkUUID, metadata);
//Recreate the CX file
CXNetworkFileGenerator g = new CXNetworkFileGenerator(networkUUID, fullSummary, metadata, newProv);
g.reCreateCXFile();
networkDao.unlockNetwork(networkUUID);
// update the solr Index
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,true,false));
} catch ( SQLException | IOException | IllegalArgumentException |NdexException e ) {
networkDao.rollback();
try {
networkDao.unlockNetwork(networkUUID);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
throw e;
}
}
} finally {
logger.info("[end: Updated profile information of network {}]", networkId);
}
}
@PUT
@Path("/{networkid}")
@Consumes("multipart/form-data")
@Produces("application/json")
@ApiDoc("This method updates an existing network with new content. The method takes a Network CX " +
"document as the PUT data. The Network's UUID is specified in the URL if this function. " +
" This method errors if the Network object is not " +
"provided or if its UUID does not correspond to an existing network on the NDEx Server. It also " +
"errors if the Network object is larger than a maximum size for network creation set in the NDEx " +
"server configuration. Network UUID is returned. This function also takes an optional 'provenance' field in the posted form."
+ " See createCXNetwork function for more details of this parameter.")
public void updateCXNetwork(final @PathParam("networkid") String networkIdStr,
MultipartFormDataInput input) throws Exception
{
// logger.info("[start: Updating network {} using CX data]", networkIdStr);
UUID networkId = UUID.fromString(networkIdStr);
String ownerAccName = null;
try ( NetworkDAO daoNew = new NetworkDAO() ) {
User user = getLoggedInUser();
try {
if( daoNew.isReadOnly(networkId)) {
logger.info("[end: Can't modify readonly network {}]", networkId);
throw new NdexException ("Can't update readonly network.");
}
if ( !daoNew.isWriteable(networkId, user.getExternalId())) {
logger.error("[end: No write permissions for user account {} on network {}]",
user.getUserName(), networkId);
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if ( daoNew.networkIsLocked(networkId)) {
daoNew.close();
throw new NetworkConcurrentModificationException ();
}
daoNew.lockNetwork(networkId);
ownerAccName = daoNew.getNetworkOwnerAcc(networkId);
UUID tmpNetworkId = storeRawNetwork (input);
String cxFileName = Configuration.getInstance().getNdexRoot() + "/data/" + tmpNetworkId.toString() + "/network.cx";
long fileSize = new File(cxFileName).length();
daoNew.clearNetworkSummary(networkId, fileSize);
java.nio.file.Path src = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + tmpNetworkId);
java.nio.file.Path tgt = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + networkId);
FileUtils.deleteDirectory(new File(Configuration.getInstance().getNdexRoot() + "/data/" + networkId));
Files.move(src, tgt, StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);
String urlStr = Configuration.getInstance().getHostURI() +
Configuration.getInstance().getRestAPIPrefix()+"/network/"+ networkIdStr;
ProvenanceEntity entity = new ProvenanceEntity();
entity.setUri(urlStr + "/summary");
ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.CX_NETWORK_UPDATE, new Timestamp(System.currentTimeMillis()));
List<SimplePropertyValuePair> eventProperties = new ArrayList<>();
Helper.addUserInfoToProvenanceEventProperties( eventProperties, this.getLoggedInUser());
event.setProperties(eventProperties);
ProvenanceEntity inputEntity =daoNew.getProvenance(networkId);
event.addInput(inputEntity);
entity.setCreationEvent(event);
daoNew.setProvenance(networkId, entity);
daoNew.commit();
// daoNew.unlockNetwork(networkId);
} catch (SQLException | NdexException | IOException e) {
// e.printStackTrace();
daoNew.rollback();
daoNew.unlockNetwork(networkId);
throw e;
}
}
NdexServerQueue.INSTANCE.addSystemTask(new CXNetworkLoadingTask(networkId, ownerAccName, true));
// return networkIdStr;
}
@DELETE
@Path("/{networkid}")
@Produces("application/json")
@ApiDoc("Deletes the network specified by networkId. There is no method to undo a deletion, so care " +
"should be exercised. A user can only delete networks that they own.")
public void deleteNetwork(final @PathParam("networkid") String id) throws NdexException, SQLException {
try (NetworkDAO networkDao = new NetworkDAO()) {
UUID networkId = UUID.fromString(id);
UUID userId = getLoggedInUser().getExternalId();
if(networkDao.isAdmin(networkId, userId) ) {
if (!networkDao.isReadOnly(networkId) ) {
if ( !networkDao.networkIsLocked(networkId)) {
/*
NetworkGlobalIndexManager globalIdx = new NetworkGlobalIndexManager();
globalIdx.deleteNetwork(id);
try (SingleNetworkSolrIdxManager idxManager = new SingleNetworkSolrIdxManager(id)) {
idxManager.dropIndex();
}
*/
networkDao.deleteNetwork(UUID.fromString(id), getLoggedInUser().getExternalId());
networkDao.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskDeleteNetwork(networkId));
return;
}
throw new NetworkConcurrentModificationException ();
}
throw new NdexException("Can't delete a read-only network.");
}
throw new NdexException("Only network owner can delete a network.");
} catch ( IOException e ) {
throw new NdexException ("Error occurred when deleting network: " + e.getMessage(), e);
}
}
/**************************************************************************
* Saves an uploaded network file. Determines the type of file uploaded,
* saves the file, and creates a task.
*
* @param uploadedNetwork
* The uploaded network file.
* @throws IllegalArgumentException
* Bad input.
* @throws NdexException
* Failed to parse the file, or create the network in the
* database.
* @throws IOException
**************************************************************************/
/*
* refactored to support non-transactional database operations
*/
@POST
@Path("/upload")
@Consumes("multipart/form-data")
@Produces("application/json")
@ApiDoc("Upload a network file into the current users NDEx account. This can take some time while background " +
"processing converts the data from the file into the common NDEx format. This method errors if the " +
"network is missing or if it has no filename or no file data.")
public Task uploadNetwork( MultipartFormDataInput input)
//@MultipartForm UploadedFile uploadedNetwork)
throws IllegalArgumentException, SecurityException, NdexException, IOException {
logger.info("[start: Uploading network file]");
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
List<InputPart> foo = uploadForm.get("filename");
String fname = "";
for (InputPart inputPart : foo)
{
// convert the uploaded file to inputstream and write it to disk
fname += inputPart.getBodyAsString();
}
if (fname.length() <1) {
throw new NdexException ("");
}
String ext = FilenameUtils.getExtension(fname).toLowerCase();
if ( !ext.equals("sif") && !ext.equals("xbel") && !ext.equals("xgmml") && !ext.equals("owl") && !ext.equals("cx")
&& !ext.equals("xls") && ! ext.equals("xlsx")) {
logger.error("[end: The uploaded file type is not supported; must be Excel, XGMML, SIF, BioPAX cx, or XBEL. Throwing NdexException...]");
throw new NdexException(
"The uploaded file type is not supported; must be Excel, XGMML, SIF, BioPAX, cx or XBEL.");
}
UUID taskId = NdexUUIDFactory.INSTANCE.createNewNDExUUID();
final File uploadedNetworkPath = new File(Configuration.getInstance().getNdexRoot() +
"/uploaded-networks");
if (!uploadedNetworkPath.exists())
uploadedNetworkPath.mkdir();
String fileFullPath = uploadedNetworkPath.getAbsolutePath() + "/" + taskId + "." + ext;
//Get file data to save
List<InputPart> inputParts = uploadForm.get("fileUpload");
final File uploadedNetworkFile = new File(fileFullPath);
if (!uploadedNetworkFile.exists())
try {
uploadedNetworkFile.createNewFile();
} catch (IOException e1) {
logger.error("[end: Failed to create file {} on server when uploading {}. Exception caught:]{}",
fileFullPath, fname, e1);
throw new NdexException ("Failed to create file " + fileFullPath + " on server when uploading " +
fname + ": " + e1.getMessage());
}
byte[] bytes = new byte[2048];
for (InputPart inputPart : inputParts)
{
// convert the uploaded file to inputstream and write it to disk
InputStream inputStream = inputPart.getBody(InputStream.class, null);
OutputStream out = new FileOutputStream(new File(fileFullPath));
int read = 0;
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
}
Task processNetworkTask = new Task();
processNetworkTask.setExternalId(taskId);
processNetworkTask.setDescription(fname); //uploadedNetwork.getFilename());
processNetworkTask.setTaskType(TaskType.PROCESS_UPLOADED_NETWORK);
processNetworkTask.setPriority(Priority.LOW);
processNetworkTask.setProgress(0);
processNetworkTask.setResource(fileFullPath);
processNetworkTask.setStatus(Status.QUEUED);
processNetworkTask.setTaskOwnerId(this.getLoggedInUser().getExternalId());
try (TaskDAO dao = new TaskDAO()){
dao.createTask(processNetworkTask);
dao.commit();
} catch (IllegalArgumentException iae) {
logger.error("[end: Exception caught:]{}", iae);
throw iae;
} catch (Exception e) {
logger.error("[end: Exception caught:]{}", e);
throw new NdexException(e.getMessage());
}
logger.info("[end: Uploading network file. Task for uploading network is created.]");
return processNetworkTask;
}
@PUT
@Path("/{networkid}/systemproperty")
@Produces("application/json")
@ApiDoc("Set the system flag specified by ‘parameter’ to ‘value’ for the network with id ‘networkId’. As of " +
"NDEx v1.2, the only supported parameter is readOnly={true|false}. In 2.0, we added visibility={PUBLIC|PRIVATE}")
public void setNetworkFlag(
@PathParam("networkid") final String networkIdStr,
final Map<String,Object> parameters)
throws IllegalArgumentException, NdexException, SQLException, IOException {
try (NetworkDAO networkDao = new NetworkDAO()) {
UUID networkId = UUID.fromString(networkIdStr);
UUID userId = getLoggedInUser().getExternalId();
// if ( !networkDao.networkIsLocked(networkId)) {
if ( !networkDao.networkIsValid(networkId))
throw new InvalidNetworkException();
if ( parameters.containsKey(readOnlyParameter)) {
if (!networkDao.isAdmin(networkId, userId))
throw new UnauthorizedOperationException("Only network owner can set readOnly Parameter.");
boolean bv = ((Boolean)parameters.get(readOnlyParameter)).booleanValue();
networkDao.setFlag(networkId, "readonly",bv);
}
if ( parameters.containsKey("visibility")) {
if (!networkDao.isAdmin(networkId, userId))
throw new UnauthorizedOperationException("Only network owner can set visibility Parameter.");
networkDao.updateNetworkVisibility(networkId, VisibilityType.valueOf((String)parameters.get("visibility")));
// update the solr Index
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,true,false));
}
if ( parameters.containsKey("showcase")) {
boolean bv = ((Boolean)parameters.get("showcase")).booleanValue();
networkDao.setShowcaseFlag(networkId, userId, bv);
}
networkDao.commit();
return;
// }
// throw new NetworkConcurrentModificationException ();
}
}
@POST
// @PermitAll
@Path("")
@Produces("text/plain")
@Consumes("multipart/form-data")
@ApiDoc("Create a network from the uploaded CX stream. The input cx data is expected to be in the CXNetworkStream field of posted multipart/form-data. "
+ "There is an optional 'provenance' field in the form. Users can use this field to pass in a JSON string of ProvenanceEntity object. When a user pass"
+ " in this object, NDEx server will add this object to the provenance history of the CX network. Otherwise NDEx server will create a ProvenanceEntity "
+ "object and add it to the provenance history of the CX network.")
public Response createCXNetwork( MultipartFormDataInput input
) throws Exception
{
// logger.info("[start: Creating a new network based on a POSTed CX stream.]");
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
UUID uuid = storeRawNetwork ( input);
String uuidStr = uuid.toString();
String urlStr = Configuration.getInstance().getHostURI() +
Configuration.getInstance().getRestAPIPrefix()+"/network/"+ uuidStr;
ProvenanceEntity entity = new ProvenanceEntity();
entity.setUri(urlStr + "/summary");
String cxFileName = Configuration.getInstance().getNdexRoot() + "/data/" + uuidStr + "/network.cx";
long fileSize = new File(cxFileName).length();
// create entry in db.
try (NetworkDAO dao = new NetworkDAO()) {
NetworkSummary summary = dao.CreateEmptyNetworkEntry(uuid, getLoggedInUser().getExternalId(), getLoggedInUser().getUserName(), fileSize);
ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.CX_CREATE_NETWORK, summary.getModificationTime());
List<SimplePropertyValuePair> eventProperties = new ArrayList<>();
Helper.addUserInfoToProvenanceEventProperties( eventProperties, this.getLoggedInUser());
event.setProperties(eventProperties);
entity.setCreationEvent(event);
dao.setProvenance(summary.getExternalId(), entity);
dao.commit();
}
NdexServerQueue.INSTANCE.addSystemTask(new CXNetworkLoadingTask(uuid, getLoggedInUser().getUserName(), false));
logger.info("[end: Created a new network based on a POSTed CX stream.]");
URI l = new URI (urlStr);
return Response.created(l).entity(l).build();
}
private static UUID storeRawNetwork (MultipartFormDataInput input) throws IOException {
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
// ProvenanceEntity entity = this.getProvenanceEntityFromMultiPart(uploadForm);
//Get file data to save
List<InputPart> inputParts = uploadForm.get("CXNetworkStream");
byte[] bytes = new byte[8192];
UUID uuid = NdexUUIDFactory.INSTANCE.createNewNDExUUID();
String pathPrefix = Configuration.getInstance().getNdexRoot() + "/data/" + uuid.toString();
//Create dir
java.nio.file.Path dir = Paths.get(pathPrefix);
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rwxrwxr-x");
FileAttribute<Set<PosixFilePermission>> attr =
PosixFilePermissions.asFileAttribute(perms);
Files.createDirectory(dir,attr);
//write content to file
String cxFilePath = pathPrefix + "/network.cx";
try (FileOutputStream out = new FileOutputStream (cxFilePath ) ){
for (InputPart inputPart : inputParts) {
// convert the uploaded file to inputstream and write it to disk
org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl p =
(org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl) inputPart;
try (InputStream inputStream = p.getBody()) {
int read = 0;
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
}
}
}
return uuid;
}
private static List<NetworkAttributesElement> getNetworkAttributeAspectsFromSummary(NetworkSummary summary)
throws JsonParseException, JsonMappingException, IOException {
List<NetworkAttributesElement> result = new ArrayList<>();
if ( summary.getName() !=null)
result.add(new NetworkAttributesElement(null, NdexClasses.Network_P_name, summary.getName()));
if ( summary.getDescription() != null)
result.add(new NetworkAttributesElement(null, NdexClasses.Network_P_desc, summary.getDescription()));
if ( summary.getVersion() !=null)
result.add(new NetworkAttributesElement(null, NdexClasses.Network_P_version, summary.getVersion()));
if ( summary.getProperties() != null) {
for ( NdexPropertyValuePair p : summary.getProperties()) {
result.add(NetworkAttributesElement.createInstanceWithJsonValue(p.getSubNetworkId(), p.getPredicateString(),
p.getValue(), ATTRIBUTE_DATA_TYPE.fromCxLabel(p.getDataType())));
}
}
return result;
}
@POST
@Path("/{networkid}/copy")
@Produces("text/plain")
public Response cloneNetwork( @PathParam("networkid") final String srcNetworkUUIDStr) throws Exception
{
// logger.info("[start: Creating a new network based on a POSTed CX stream.]");
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
UUID srcNetUUID = UUID.fromString(srcNetworkUUIDStr);
try ( NetworkDAO dao = new NetworkDAO ()) {
if ( ! dao.isReadable(srcNetUUID, getLoggedInUserId()) )
throw new UnauthorizedOperationException("User doesn't have read access to this network.");
if (!dao.networkIsValid(srcNetUUID)) {
throw new NdexException ("Invalid networks can not be copied.");
}
}
UUID uuid = NdexUUIDFactory.INSTANCE.createNewNDExUUID();
String uuidStr = uuid.toString();
// java.nio.file.Path src = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + srcNetUUID.toString());
java.nio.file.Path tgt = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + uuidStr);
//Create dir
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rwxrwxr-x");
FileAttribute<Set<PosixFilePermission>> attr =
PosixFilePermissions.asFileAttribute(perms);
Files.createDirectory(tgt,attr);
File srcAspectDir = new File ( Configuration.getInstance().getNdexRoot() + "/data/" + srcNetUUID.toString() + "/aspects");
File tgtAspectDir = new File ( Configuration.getInstance().getNdexRoot() + "/data/" + uuidStr + "/aspects");
FileUtils.copyDirectory(srcAspectDir, tgtAspectDir);
String urlStr = Configuration.getInstance().getHostURI() +
Configuration.getInstance().getRestAPIPrefix()+"/network/"+ uuidStr;
// ProvenanceEntity entity = new ProvenanceEntity();
// entity.setUri(urlStr + "/summary");
String cxFileName = Configuration.getInstance().getNdexRoot() + "/data/" + srcNetUUID.toString() + "/network.cx";
long fileSize = new File(cxFileName).length();
// copy sample
java.nio.file.Path srcSample = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + srcNetUUID.toString() + "/sample.cx");
if ( Files.exists(srcSample, LinkOption.NOFOLLOW_LINKS)) {
java.nio.file.Path tgtSample = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + uuidStr + "/sample.cx");
Files.copy(srcSample, tgtSample);
}
// create entry in db.
try (NetworkDAO dao = new NetworkDAO()) {
NetworkSummary summary = dao.CreateCloneNetworkEntry(uuid, getLoggedInUser().getExternalId(), getLoggedInUser().getUserName(), fileSize, srcNetUUID);
ProvenanceEntity sourceProvenanceEntity = dao.getProvenance(srcNetUUID);
ProvenanceEntity copyProv = ProvenanceHelpers.createProvenanceHistory(
summary,
Configuration.getInstance().getHostURI(),
NdexProvenanceEventType.CX_NETWORK_CLONE,
new Timestamp(Calendar.getInstance().getTimeInMillis()),
sourceProvenanceEntity
);
dao.setProvenance(uuid, copyProv);
CXNetworkFileGenerator g = new CXNetworkFileGenerator(uuid, dao, new Provenance(copyProv));
g.reCreateCXFile();
dao.commit();
}
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(uuid,true,true));
logger.info("[end: Created a new network based on a POSTed CX stream.]");
URI l = new URI (urlStr);
return Response.created(l).entity(l).build();
}
@POST
@PermitAll
@Path("/properties/score")
@Produces("application/json")
public static int getScoresFromProperties(
final List<NdexPropertyValuePair> properties)
throws Exception {
return Util.getNetworkScores (properties, true);
}
@POST
@PermitAll
@Path("/summary/score")
@Produces("application/json")
public static int getScoresFromNetworkSummary(
final NetworkSummary summary)
throws Exception {
return Util.getNdexScoreFromSummary(summary);
}
}
|
src/main/java/org/ndexbio/rest/services/NetworkServiceV2.java
|
/**
* Copyright (c) 2013, 2016, The Regents of the University of California, The Cytoscape Consortium
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package org.ndexbio.rest.services;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.solr.client.solrj.SolrServerException;
import org.cxio.aspects.datamodels.ATTRIBUTE_DATA_TYPE;
import org.cxio.aspects.datamodels.NetworkAttributesElement;
import org.cxio.metadata.MetaDataCollection;
import org.cxio.metadata.MetaDataElement;
import org.cxio.util.JsonWriter;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import org.ndexbio.common.NdexClasses;
import org.ndexbio.common.cx.CXAspectWriter;
import org.ndexbio.common.cx.CXNetworkFileGenerator;
import org.ndexbio.common.cx.OpaqueAspectIterator;
import org.ndexbio.common.models.dao.postgresql.Helper;
import org.ndexbio.common.models.dao.postgresql.NetworkDAO;
import org.ndexbio.common.models.dao.postgresql.TaskDAO;
import org.ndexbio.common.models.dao.postgresql.UserDAO;
import org.ndexbio.common.solr.NetworkGlobalIndexManager;
import org.ndexbio.common.util.NdexUUIDFactory;
import org.ndexbio.common.util.Util;
import org.ndexbio.model.cx.Provenance;
import org.ndexbio.model.exceptions.ForbiddenOperationException;
import org.ndexbio.model.exceptions.InvalidNetworkException;
import org.ndexbio.model.exceptions.NdexException;
import org.ndexbio.model.exceptions.NetworkConcurrentModificationException;
import org.ndexbio.model.exceptions.ObjectNotFoundException;
import org.ndexbio.model.exceptions.UnauthorizedOperationException;
import org.ndexbio.model.object.NdexPropertyValuePair;
import org.ndexbio.model.object.NdexProvenanceEventType;
import org.ndexbio.model.object.Permissions;
import org.ndexbio.model.object.Priority;
import org.ndexbio.model.object.ProvenanceEntity;
import org.ndexbio.model.object.ProvenanceEvent;
import org.ndexbio.model.object.SimplePropertyValuePair;
import org.ndexbio.model.object.Status;
import org.ndexbio.model.object.Task;
import org.ndexbio.model.object.TaskType;
import org.ndexbio.model.object.User;
import org.ndexbio.model.object.network.NetworkSummary;
import org.ndexbio.model.object.network.VisibilityType;
import org.ndexbio.model.tools.ProvenanceHelpers;
import org.ndexbio.rest.Configuration;
import org.ndexbio.rest.annotations.ApiDoc;
import org.ndexbio.task.CXNetworkLoadingTask;
import org.ndexbio.task.NdexServerQueue;
import org.ndexbio.task.SolrTaskDeleteNetwork;
import org.ndexbio.task.SolrTaskRebuildNetworkIdx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
@Path("/v2/network")
public class NetworkServiceV2 extends NdexService {
static Logger logger = LoggerFactory.getLogger(NetworkService.class);
static private final String readOnlyParameter = "readOnly";
public NetworkServiceV2(@Context HttpServletRequest httpRequest
// @Context org.jboss.resteasy.spi.HttpResponse response
) {
super(httpRequest);
// response.getOutputHeaders().putSingle("WWW-Authenticate", "Basic");
}
/**************************************************************************
* Returns network provenance.
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
* @throws NdexException
* @throws SQLException
*
**************************************************************************/
@PermitAll
@GET
@Path("/{networkid}/provenance")
@Produces("application/json")
@ApiDoc("This method retrieves the 'provenance' attribute of the network specified by 'networkId', if it " +
"exists. The returned value is a JSON ProvenanceEntity object which in turn contains a " +
"tree-structure of ProvenanceEvent and ProvenanceEntity objects that describe the provenance " +
"history of the network. See the document NDEx Provenance History for a detailed description of " +
"this structure and best practices for its use.")
public ProvenanceEntity getProvenance(
@PathParam("networkid") final String networkIdStr,
@QueryParam("accesskey") String accessKey)
throws IllegalArgumentException, JsonParseException, JsonMappingException, IOException, NdexException, SQLException {
logger.info("[start: Getting provenance of network {}]", networkIdStr);
UUID networkId = UUID.fromString(networkIdStr);
try (NetworkDAO daoNew = new NetworkDAO()) {
if ( !daoNew.isReadable(networkId, getLoggedInUserId()) && (!daoNew.accessKeyIsValid(networkId, accessKey)))
throw new UnauthorizedOperationException("Network " + networkId + " is not readable to this user.");
logger.info("[end: Got provenance of network {}]", networkId);
return daoNew.getProvenance(networkId);
}
}
/**************************************************************************
* Updates network provenance.
* @throws Exception
*
**************************************************************************/
@PUT
@Path("/{networkid}/provenance")
@Produces("application/json")
@ApiDoc("Updates the 'provenance' field of the network specified by 'networkId' to be the " +
"ProvenanceEntity object in the PUT data. The ProvenanceEntity object is expected to represent " +
"the current state of the network and to contain a tree-structure of ProvenanceEvent and " +
"ProvenanceEntity objects that describe the networks provenance history.")
public void setProvenance(@PathParam("networkid")final String networkIdStr, final ProvenanceEntity provenance)
throws Exception {
logger.info("[start: Updating provenance of network {}]", networkIdStr);
User user = getLoggedInUser();
setProvenance_aux(networkIdStr, provenance, user);
}
protected static void setProvenance_aux(final String networkIdStr, final ProvenanceEntity provenance, User user)
throws Exception {
try (NetworkDAO daoNew = new NetworkDAO()){
UUID networkId = UUID.fromString(networkIdStr);
if ( !daoNew.isWriteable(networkId, user.getExternalId())) {
logger.error("[end: No write permissions for user account {} on network {}]",
user.getUserName(), networkId);
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if(daoNew.isReadOnly(networkId)) {
daoNew.close();
logger.info("[end: Can't modify readonly network {}]", networkId);
throw new NdexException ("Can't update readonly network.");
}
if (!daoNew.networkIsValid(networkId))
throw new InvalidNetworkException();
if ( daoNew.networkIsLocked(networkId,6)) {
daoNew.close();
throw new NetworkConcurrentModificationException ();
}
daoNew.lockNetwork(networkId);
daoNew.setProvenance(networkId, provenance);
daoNew.commit();
//Recreate the CX file
// NetworkSummary fullSummary = daoNew.getNetworkSummaryById(networkId);
// MetaDataCollection metadata = daoNew.getMetaDataCollection(networkId);
CXNetworkFileGenerator g = new CXNetworkFileGenerator(networkId, daoNew, new Provenance(provenance));
g.reCreateCXFile();
daoNew.unlockNetwork(networkId);
return ; // provenance; // daoNew.getProvenance(networkUUID);
} catch (Exception e) {
//if (null != daoNew) daoNew.rollback();
logger.error("[end: Updating provenance of network {}. Exception caught:]{}", networkIdStr, e);
throw e;
} finally {
logger.info("[end: Updated provenance of network {}]", networkIdStr);
}
}
/**************************************************************************
* Sets network properties.
* @throws Exception
*
**************************************************************************/
@PUT
@Path("/{networkid}/properties")
@Produces("application/json")
@ApiDoc("Updates the 'properties' field of the network specified by 'networkId' to be the list of " +
"NdexPropertyValuePair objects in the PUT data.")
public int setNetworkProperties(
@PathParam("networkid")final String networkId,
final List<NdexPropertyValuePair> properties)
throws Exception {
// logger.info("[start: Updating properties of network {}]", networkId);
User user = getLoggedInUser();
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO daoNew = new NetworkDAO()) {
if(daoNew.isReadOnly(networkUUID)) {
logger.info("[end: Can't modify readonly network {}]", networkId);
throw new NdexException ("Can't update readonly network.");
}
if ( !daoNew.isWriteable(networkUUID, user.getExternalId())) {
logger.error("[end: No write permissions for user account {} on network {}]",
user.getUserName(), networkId);
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if ( daoNew.networkIsLocked(networkUUID,10)) {
throw new NetworkConcurrentModificationException ();
}
if ( !daoNew.networkIsValid(networkUUID))
throw new InvalidNetworkException();
daoNew.lockNetwork(networkUUID);
try {
int i = daoNew.setNetworkProperties(networkUUID, properties);
//DW: Handle provenance
ProvenanceEntity oldProv = daoNew.getProvenance(networkUUID);
ProvenanceEntity newProv = new ProvenanceEntity();
newProv.setUri( oldProv.getUri() );
NetworkSummary summary = daoNew.getNetworkSummaryById(networkUUID);
Helper.populateProvenanceEntity(newProv, summary);
ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.SET_NETWORK_PROPERTIES, summary.getModificationTime());
List<SimplePropertyValuePair> eventProperties = new ArrayList<>();
Helper.addUserInfoToProvenanceEventProperties( eventProperties, user);
for( NdexPropertyValuePair vp : properties )
{
SimplePropertyValuePair svp = new SimplePropertyValuePair(vp.getPredicateString(), vp.getValue());
eventProperties.add(svp);
}
event.setProperties(eventProperties);
List<ProvenanceEntity> oldProvList = new ArrayList<>();
oldProvList.add(oldProv);
event.setInputs(oldProvList);
newProv.setCreationEvent(event);
daoNew.setProvenance(networkUUID, newProv);
NetworkSummary fullSummary = daoNew.getNetworkSummaryById(networkUUID);
//update the networkProperty aspect
List<NetworkAttributesElement> attrs = getNetworkAttributeAspectsFromSummary(fullSummary);
if ( attrs.size() > 0 ) {
try (CXAspectWriter writer = new CXAspectWriter(Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/aspects/"
+ NetworkAttributesElement.ASPECT_NAME) ) {
for ( NetworkAttributesElement e : attrs) {
writer.writeCXElement(e);
writer.flush();
}
}
}
//update metadata
MetaDataCollection metadata = daoNew.getMetaDataCollection(networkUUID);
MetaDataElement elmt = metadata.getMetaDataElement(NetworkAttributesElement.ASPECT_NAME);
if ( elmt == null) {
elmt = new MetaDataElement();
}
elmt.setElementCount(Long.valueOf(attrs.size()));
daoNew.updateMetadataColleciton(networkUUID, metadata);
//Recreate the CX file
CXNetworkFileGenerator g = new CXNetworkFileGenerator(networkUUID, fullSummary, metadata, newProv);
g.reCreateCXFile();
// update the solr Index
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,true,false));
return i;
} finally {
daoNew.unlockNetwork(networkUUID);
}
} catch (Exception e) {
//logger.severe("Error occurred when update network properties: " + e.getMessage());
//e.printStackTrace();
//if (null != daoNew) daoNew.rollback();
logger.error("Updating properties of network {}. Exception caught:]{}", networkId, e);
throw new NdexException(e.getMessage(), e);
} finally {
logger.info("[end: Updated properties of network {}]", networkId);
}
}
/*
*
* Operations returning Networks
*
*/
@PermitAll
@GET
@Path("/{networkid}/summary")
@Produces("application/json")
@ApiDoc("Retrieves a NetworkSummary object based on the network specified by 'networkId'. This " +
"method returns an error if the network is not found or if the authenticated user does not have " +
"READ permission for the network.")
public NetworkSummary getNetworkSummary(
@PathParam("networkid") final String networkIdStr ,
@QueryParam("accesskey") String accessKey /*,
@Context org.jboss.resteasy.spi.HttpResponse response*/)
throws IllegalArgumentException, NdexException, SQLException, JsonParseException, JsonMappingException, IOException {
try (NetworkDAO dao = new NetworkDAO()) {
UUID userId = getLoggedInUserId();
UUID networkId = UUID.fromString(networkIdStr);
if ( dao.isReadable(networkId, userId) || dao.accessKeyIsValid(networkId, accessKey)) {
NetworkSummary summary = dao.getNetworkSummaryById(networkId);
// response.getOutputHeaders().putSingle("WWW-Authenticate", "Basic");
return summary;
}
throw new UnauthorizedOperationException ("Unauthorized access to network " + networkId);
}
}
@PermitAll
@GET
@Path("/{networkid}/aspect")
@ApiDoc("The getAspectElement method returns elements in the specified aspect up to the given limit.")
public Response getNetworkCXMetadataCollection( @PathParam("networkid") final String networkId,
@QueryParam("accesskey") String accessKey)
throws Exception {
logger.info("[start: Getting CX metadata from network {}]", networkId);
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO dao = new NetworkDAO() ) {
if ( dao.isReadable(networkUUID, getLoggedInUserId()) || dao.accessKeyIsValid(networkUUID, accessKey)) {
MetaDataCollection mdc = dao.getMetaDataCollection(networkUUID);
logger.info("[end: Return CX metadata from network {}]", networkId);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonWriter wtr = JsonWriter.createInstance(baos,true);
mdc.toJson(wtr);
String s = baos.toString();//"java.nio.charset.StandardCharsets.UTF_8");
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(s).build();
// return mdc;
}
throw new UnauthorizedOperationException("User doesn't have access to this network.");
}
}
@PermitAll
@GET
@Path("/{networkid}/aspect/{aspectname}/metadata")
@ApiDoc("Return the metadata of the given aspect name.")
public MetaDataElement getNetworkCXMetadata(
@PathParam("networkid") final String networkId,
@PathParam("aspectname") final String aspectName
)
throws Exception {
logger.info("[start: Getting {} metadata from network {}]", aspectName, networkId);
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO dao = new NetworkDAO() ) {
if ( dao.isReadable(networkUUID, getLoggedInUserId())) {
MetaDataCollection mdc = dao.getMetaDataCollection(networkUUID);
logger.info("[end: Return CX metadata from network {}]", networkId);
return mdc.getMetaDataElement(aspectName);
}
throw new UnauthorizedOperationException("User doesn't have access to this network.");
}
}
@PermitAll
@GET
@Path("/{networkid}/aspect/{aspectname}")
@ApiDoc("The getAspectElement method returns elements in the specified aspect up to the given limit.")
public Response getAspectElements( @PathParam("networkid") final String networkId,
@PathParam("aspectname") final String aspectName,
@DefaultValue("-1") @QueryParam("size") int limit) throws SQLException, NdexException
{
logger.info("[start: Getting one aspect in network {}]", networkId);
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO dao = new NetworkDAO()) {
if ( !dao.isReadable(networkUUID, getLoggedInUserId())) {
throw new UnauthorizedOperationException("User doesn't have access to this network.");
}
FileInputStream in;
try {
in = new FileInputStream(
Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/aspects/" + aspectName);
} catch (FileNotFoundException e) {
throw new ObjectNotFoundException("Aspect "+ aspectName + " not found in this network.");
}
if ( limit <= 0) {
logger.info("[end: Return cached network {}]", networkId);
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(in).build();
}
PipedInputStream pin = new PipedInputStream();
PipedOutputStream out;
try {
out = new PipedOutputStream(pin);
} catch (IOException e) {
try {
pin.close();
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
throw new NdexException("IOExcetion when creating the piped output stream: "+ e.getMessage());
}
new CXAspectElementsWriterThread(out,in, aspectName, limit).start();
logger.info("[end: Return get one aspect in network {}]", networkId);
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(pin).build();
}
}
@PermitAll
@GET
@Path("/{networkid}")
public Response getCompleteNetworkAsCX( @PathParam("networkid") final String networkId,
@QueryParam("download") boolean isDownload,
@QueryParam("accesskey") String accessKey)
throws IllegalArgumentException, NdexException, SQLException, JsonParseException, JsonMappingException, IOException {
logger.info("[start: Getting complete network {}]", networkId);
String title = null;
try (NetworkDAO dao = new NetworkDAO()) {
UUID networkUUID = UUID.fromString(networkId);
if ( ! dao.isReadable(networkUUID, getLoggedInUserId()) && (!dao.accessKeyIsValid(networkUUID, accessKey)))
throw new UnauthorizedOperationException("User doesn't have read access to this network.");
NetworkSummary s = dao.getNetworkSummaryById(networkUUID);
title = s.getName();
}
if ( title == null || title.length() < 1) {
title = networkId;
}
title.replace('"', '_');
String cxFilePath = Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/network.cx";
try {
FileInputStream in = new FileInputStream(cxFilePath) ;
// setZipFlag();
logger.info("[end: Return network {}]", networkId);
ResponseBuilder r = Response.ok();
if ( isDownload)
r.header("Content-Disposition", "attachment; filename=\"" + title + ".cx\"");
return r.type(MediaType.APPLICATION_JSON_TYPE).entity(in).build();
} catch (IOException e) {
logger.error("[end: Ndex server can't find file: {}]", e.getMessage());
throw new NdexException ("Ndex server can't find file: " + e.getMessage());
}
}
@PermitAll
@GET
@Path("/{networkid}/sample")
@ApiDoc("The getSampleNetworkAsCX method enables an application to obtain a sample of the given network as a CX " +
"structure. The sample network is a 500 random edge subnetwork of the original network if it was created by the server automatically. "
+ "User can also upload their own sample network if they "
+ "")
public Response getSampleNetworkAsCX( @PathParam("networkid") final String networkIdStr ,
@QueryParam("accesskey") String accessKey)
throws IllegalArgumentException, NdexException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
try (NetworkDAO dao = new NetworkDAO()) {
if ( ! dao.isReadable(networkId, getLoggedInUserId()) && (!dao.accessKeyIsValid(networkId, accessKey)))
throw new UnauthorizedOperationException("User doesn't have read access to this network.");
}
String cxFilePath = Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/sample.cx";
try {
FileInputStream in = new FileInputStream(cxFilePath) ;
// setZipFlag();
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(in).build();
} catch ( FileNotFoundException e) {
throw new ObjectNotFoundException("Sample network of " + networkId + " not found");
}
}
@GET
@Path("/{networkid}/accesskey")
@Produces("text/plain; charset=utf-8")
public String getNetworkAccessKey(@PathParam("networkid") final String networkIdStr)
throws IllegalArgumentException, NdexException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
try (NetworkDAO dao = new NetworkDAO()) {
if ( ! dao.isAdmin(networkId, getLoggedInUserId()))
throw new UnauthorizedOperationException("User is not admin of this network.");
return dao.getNetworkAccessKey(networkId);
}
}
@PUT
@Path("/{networkid}/accesskey")
public String disableEnableNetworkAccessKey(@PathParam("networkid") final String networkIdStr,
@QueryParam("action") String action)
throws IllegalArgumentException, NdexException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
if ( ! action.equalsIgnoreCase("disable") && ! action.equalsIgnoreCase("enable"))
throw new NdexException("Value of 'action' paramter can only be 'disable' or 'enable'");
try (NetworkDAO dao = new NetworkDAO()) {
if ( ! dao.isAdmin(networkId, getLoggedInUserId()))
throw new UnauthorizedOperationException("User is not admin of this network.");
String key = null;
if ( action.equalsIgnoreCase("disable"))
dao.disableNetworkAccessKey(networkId);
else
key = dao.enableNetworkAccessKey(networkId);
dao.commit();
return key;
}
}
@PUT
@Path("/{networkid}/sample")
@ApiDoc("This method enables an application to set the sample network as a CX " +
"structure. The sample network should be small ( no more than 500 edges normally)")
public void setSampleNetwork( @PathParam("networkid") final String networkId,
String CXString)
throws IllegalArgumentException, NdexException, SQLException {
logger.info("[start: Getting sample network {}]", networkId);
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO dao = new NetworkDAO()) {
if ( ! dao.isAdmin(networkUUID, getLoggedInUserId()))
throw new UnauthorizedOperationException("User is not admin of this network.");
if ( !dao.networkIsLocked(networkUUID))
throw new NetworkConcurrentModificationException();
if ( !dao.networkIsValid(networkUUID))
throw new InvalidNetworkException();
}
String cxFilePath = Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/sample.cx";
try (FileWriter w = new FileWriter(cxFilePath)){
w.write(CXString);
} catch ( IOException e) {
throw new NdexException("Failed to write sample network of " + networkId + ": " + e.getMessage(), e);
}
}
/*
private class CXNetworkWriterThread extends Thread {
private OutputStream o;
private String networkId;
public CXNetworkWriterThread (OutputStream out, String networkUUIDStr) {
o = out;
networkId = networkUUIDStr;
}
public void run() {
try (CXNetworkExporter dao = new CXNetworkExporter (networkId) ) {
dao.writeNetworkInCX(o, true);
} catch (IOException e) {
logger.error("IOException in CXNetworkWriterThread: " + e.getMessage());
e.printStackTrace();
} catch (NdexException e1) {
logger.error("Ndex error: " + e1.getMessage());
e1.printStackTrace();
} catch (Exception e1) {
logger.error("Ndex excption: " + e1.getMessage());
e1.printStackTrace();
} finally {
try {
o.flush();
o.close();
} catch (IOException e) {
e.printStackTrace();
logger.error("Failed to close outputstream in CXNetworkWriterThread.");
}
}
}
} */
/* private class CXNetworkQueryWriterThread extends Thread {
private OutputStream o;
private String networkId;
private CXSimplePathQuery parameters;
public CXNetworkQueryWriterThread (OutputStream out, String networkUUIDStr, CXSimplePathQuery query) {
o = out;
networkId = networkUUIDStr;
this.parameters = query;
}
public void run() {
try (CXNetworkExporter dao = new CXNetworkExporter (networkId) ) {
dao.exportSubnetworkInCX(o, parameters,true);
} catch (IOException e) {
logger.error("IOException in CXNetworkWriterThread: " + e.getMessage());
e.printStackTrace();
} catch (NdexException e1) {
logger.error("Ndex error: " + e1.getMessage());
e1.printStackTrace();
} catch (Exception e1) {
logger.error("Ndex excption: " + e1.getMessage());
e1.printStackTrace();
} finally {
try {
o.flush();
o.close();
} catch (IOException e) {
e.printStackTrace();
logger.error("Failed to close outputstream in CXNetworkWriterThread.");
}
}
}
}
*/
private class CXAspectElementsWriterThread extends Thread {
private OutputStream o;
// private String networkId;
private FileInputStream in;
// private String aspect;
private int limit;
public CXAspectElementsWriterThread (OutputStream out, FileInputStream inputStream, String aspectName, int limit) {
o = out;
// this.networkId = networkId;
// aspect = aspectName;
this.limit = limit;
in = inputStream;
}
public void run() {
try {
OpaqueAspectIterator asi = new OpaqueAspectIterator(in);
try (CXAspectWriter wtr = new CXAspectWriter (o)) {
for ( int i = 0 ; i < limit && asi.hasNext() ; i++) {
wtr.writeCXElement(asi.next());
}
}
} catch (IOException e) {
logger.error("IOException in CXAspectElementWriterThread: " + e.getMessage());
} catch (Exception e1) {
logger.error("Ndex exception: " + e1.getMessage());
} finally {
try {
o.flush();
o.close();
} catch (IOException e) {
logger.error("Failed to close outputstream in CXElementWriterWriterThread");
e.printStackTrace();
}
}
}
}
/*
private class CXNetworkAspectsWriterThread extends Thread {
private OutputStream o;
private String networkId;
private Set<String> aspects;
public CXNetworkAspectsWriterThread (OutputStream out, String networkId, Set<String> aspectNames) {
o = out;
this.networkId = networkId;
this.aspects = aspectNames;
}
public void run() {
try (CXNetworkExporter dao = new CXNetworkExporter (networkId)) {
dao.writeAspectsInCX(o, aspects, true);
} catch (IOException e) {
logger.error("IOException in CXNetworkAspectsWriterThread: " + e.getMessage());
e.printStackTrace();
} catch (NdexException e1) {
logger.error("Ndex error: " + e1.getMessage());
e1.printStackTrace();
} catch (Exception e1) {
logger.error("Ndex exception: " + e1.getMessage());
e1.printStackTrace();
} finally {
try {
o.flush();
o.close();
} catch (IOException e) {
e.printStackTrace();
logger.error("Failed to close outputstream in CXNetworkAspectsWriterThread. " + e.getMessage());
}
}
}
} */
/* private class CXNetworkLoadThread extends Thread {
private UUID networkId;
public CXNetworkLoadThread (UUID networkUUID ) {
this.networkId = networkUUID;
}
public void run() {
}
} */
/*
private ProvenanceEntity getProvenanceEntityFromMultiPart(Map<String, List<InputPart>> uploadForm) throws NdexException, IOException {
List<InputPart> parts = uploadForm.get("provenance");
if (parts == null)
return null;
StringBuffer sb = new StringBuffer();
for (InputPart inputPart : parts) {
org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl p =
(org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl) inputPart;
sb.append(p.getBodyAsString());
}
ObjectMapper mapper = new ObjectMapper();
ProvenanceEntity entity = mapper.readValue(sb.toString(), ProvenanceEntity.class);
if (entity == null || entity.getUri() == null)
throw new NdexException ("Malformed provenance parameter found in posted form data.");
return entity;
} */
/* Note: Will be implemented in services
@PermitAll
@GET
@Path("/export/{networkId}/{format}")
@Produces("application/json")
@ApiDoc("Retrieve an entire network specified by 'networkId' as a Network object. (Compare this method to " +
"getCompleteNetworkAsPropertyGraph).")
public String exportNetwork( @PathParam("networkId") final String networkId,
@PathParam("format") final String format)
throws NdexException {
logger.info("[start: request to export network {}]", networkId);
if ( isReadable(networkId) ) {
String networkName =null;
try (NetworkDAO networkdao = new NetworkDAO(NdexDatabase.getInstance().getAConnection())){
networkName = networkdao.getNetworkSummaryById(networkId).getName();
}
Task exportNetworkTask = new Task();
exportNetworkTask.setTaskType(TaskType.EXPORT_NETWORK_TO_FILE);
exportNetworkTask.setPriority(Priority.LOW);
exportNetworkTask.setResource(networkId);
exportNetworkTask.setStatus(Status.QUEUED);
exportNetworkTask.setDescription("Export network \""+ networkName + "\" in " + format + " format");
try {
exportNetworkTask.setFormat(FileFormat.valueOf(format));
} catch ( Exception e) {
logger.error("[end: Exception caught:]{}", e);
throw new NdexException ("Invalid network format for network export.");
}
try (TaskDAO taskDAO = new TaskDAO(NdexDatabase.getInstance().getAConnection()) ){
exportNetworkTask.setTaskOwnerId(getLoggedInUser().getExternalId());
UUID taskId = taskDAO.createTask(exportNetworkTask);
taskDAO.commit();
logger.info("[start: task created to export network {}]", networkId);
return taskId.toString();
} catch (Exception e) {
logger.error("[end: Exception caught:]{}", e);
throw new NdexException(e.getMessage());
}
}
logger.error("[end: User doesn't have read access network {}. Throwing UnauthorizedOperationException]", networkId);
throw new UnauthorizedOperationException("User doesn't have read access to this network.");
}
*/
/**************************************************************************
* Retrieves array of user membership objects
*
* @param networkId
* The network ID.
* @throws IllegalArgumentException
* Bad input.
* @throws ObjectNotFoundException
* The group doesn't exist.
* @throws NdexException
* Failed to query the database.
* @throws SQLException
**************************************************************************/
@GET
@Path("/{networkid}/permission")
@Produces("application/json")
@ApiDoc("Retrieves a list of Membership objects which specify user permissions for the network specified by " +
"'networkId'. The value of the 'permission' parameter constrains the type of the returned Membership " +
"objects and may take the following set of values: READ, WRITE, and ADMIN. READ, WRITE, and ADMIN are mutually exclusive. Memberships of all types can " +
"be retrieved by permission = 'ALL'. The maximum number of Membership objects to retrieve in the query " +
"is set by 'blockSize' (which may be any number chosen by the user) while 'skipBlocks' specifies the " +
"number of blocks that have already been read.")
public Map<String, String> getNetworkUserMemberships(
@PathParam("networkid") final String networkId,
@QueryParam("type") String sourceType,
@QueryParam("permission") final String permissions ,
@DefaultValue("0") @QueryParam("start") int skipBlocks,
@DefaultValue("100") @QueryParam("size") int blockSize) throws NdexException, SQLException {
logger.info("[start: Get {} accounts on network {}, skipBlocks {}, blockSize {}]",
permissions, networkId, skipBlocks, blockSize);
Permissions permission = null;
if ( permissions != null ){
permission = Permissions.valueOf(permissions.toUpperCase());
}
UUID networkUUID = UUID.fromString(networkId);
boolean returnUsers = true;
if ( sourceType != null ) {
if ( sourceType.toLowerCase().equals("group"))
returnUsers = false;
else if ( !sourceType.toLowerCase().equals("user"))
throw new NdexException("Invalid parameter 'type' " + sourceType + " received, it can only be 'user' or 'group'.");
} else
throw new NdexException("Parameter 'type' is required in this function.");
try (NetworkDAO networkDao = new NetworkDAO()) {
if ( !networkDao.isAdmin(networkUUID, getLoggedInUserId()) )
throw new UnauthorizedOperationException("Authenticate user is not the admin of this network.");
Map<String,String> result = returnUsers?
networkDao.getNetworkUserPermissions(networkUUID, permission, skipBlocks, blockSize):
networkDao.getNetworkGroupPermissions(networkUUID,permission,skipBlocks,blockSize);
logger.info("[end: Got {} members returned for network {}]",
result.size(), networkId);
return result;
}
}
@DELETE
@Path("/{networkid}/permission")
@Produces("application/json")
@ApiDoc("Removes any permission for the network specified by 'networkId' for the user specified by 'userUUID': it" +
" deletes any Membership object that specifies a permission for the user-network combination. This method" +
" will return an error if the authenticated user making the request does not have sufficient permissions " +
"to make the deletion or if the network or user is not found. Removal is also denied if it would leave " +
"the network without any user having ADMIN permissions: NDEx does not permit networks to become 'orphans'" +
" without any owner.")
public int deleteNetworkPermission(
@PathParam("networkid") final String networkIdStr,
@QueryParam("userid") String userIdStr,
@QueryParam("groupid") String groupIdStr
)
throws IllegalArgumentException, NdexException, SolrServerException, IOException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
UUID userId = null;
if ( userIdStr != null)
userId = UUID.fromString(userIdStr);
UUID groupId = null;
if ( groupIdStr != null)
groupId = UUID.fromString(groupIdStr);
if ( userId == null && groupId == null)
throw new NdexException ("Either userid or groupid parameter need to be set for this function.");
if ( userId !=null && groupId != null)
throw new NdexException ("userid and gorupid can't both be set for this function.");
try (NetworkDAO networkDao = new NetworkDAO()){
// User user = getLoggedInUser();
// networkDao.checkPermissionOperationCondition(networkId, user.getExternalId());
if (!networkDao.isAdmin(networkId,getLoggedInUserId())) {
if ( userId != null && !userId.equals(getLoggedInUserId())) {
throw new UnauthorizedOperationException("Unable to delete network permisison: user need to be admin of this network or grantee of this permission.");
}
if ( groupId!=null ) {
throw new UnauthorizedOperationException("Unable to delete network permission: user is not an admin of this network.");
}
}
if( !networkDao.networkIsValid(networkId))
throw new InvalidNetworkException();
int count;
if ( userId !=null)
count = networkDao.revokeUserPrivilege(networkId, userId);
else
count = networkDao.revokeGroupPrivilege(networkId, groupId);
// update the solr Index
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,true,false));
return count;
}
}
/*
*
* Operations on Network permissions
*
*/
@PUT
@Path("/{networkid}/permission")
@Produces("application/json")
@ApiDoc("POSTs a Membership object to update the permission of a user specified by userUUID for the network " +
"specified by networkUUID. The permission is updated to the value specified in the 'permission' field of " +
"the Membership. This method returns 1 if the update is performed and 0 if the update is redundant, " +
"where the user already has the specified permission. It also returns an error if the authenticated user " +
"making the request does not have sufficient permissions or if the network or user is not found. It also " +
"returns an error if it would leave the network without any user having ADMIN permissions: NDEx does not " +
"permit networks to become 'orphans' without any owner. Because we only allow user to be the administrator of a network, "
+ "Granting ADMIN permission to another user will move the admin privilege (ownership) from the network's"
+ " previous administrator (owner) to the new user.")
public int updateNetworkPermission(
@PathParam("networkid") final String networkIdStr,
@QueryParam("userid") String userIdStr,
@QueryParam("groupid") String groupIdStr,
@QueryParam("permission") final String permissions
)
throws IllegalArgumentException, NdexException, SolrServerException, IOException, SQLException {
logger.info("[start: Updating membership for network {}]", networkIdStr);
UUID networkId = UUID.fromString(networkIdStr);
UUID userId = null;
if ( userIdStr != null)
userId = UUID.fromString(userIdStr);
UUID groupId = null;
if ( groupIdStr != null)
groupId = UUID.fromString(groupIdStr);
if ( userId == null && groupId == null)
throw new NdexException ("Either userid or groupid parameter need to be set for this function.");
if ( userId !=null && groupId != null)
throw new NdexException ("userid and gorupid can't both be set for this function.");
if ( permissions == null)
throw new NdexException ("permission parameter is required in this function.");
Permissions p = Permissions.valueOf(permissions.toUpperCase());
try (NetworkDAO networkDao = new NetworkDAO()){
User user = getLoggedInUser();
if (!networkDao.isAdmin(networkId,user.getExternalId())) {
throw new UnauthorizedOperationException("Unable to update network permission: user is not an admin of this network.");
}
if ( !networkDao.networkIsValid(networkId))
throw new InvalidNetworkException();
int count;
if ( userId!=null) {
count = networkDao.grantPrivilegeToUser(networkId, userId, p);
} else
count = networkDao.grantPrivilegeToGroup(networkId, groupId, p);
//networkDao.commit();
// update the solr Index
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,true,false));
logger.info("[end: Updated permission for network {}]", networkId);
return count;
}
}
@PUT
@Path("/{networkid}/profile")
@Produces("application/json")
@ApiDoc("This method updates the profile information of the network specified by networkId based on a " +
"POSTed JSON object specifying the attributes to update. Any profile attributes specified will be " +
"updated but attributes that are not specified will have no effect - omission of an attribute does " +
"not mean deletion of that attribute. The network profile attributes that can be updated by this " +
"method are: 'name', 'description', 'version'. visibility are no longer updated by this function. It is managed by setNetworkFlag function from 2.0")
public void updateNetworkProfile(
@PathParam("networkid") final String networkId,
final NetworkSummary partialSummary
)
throws NdexException, SQLException , IOException, IllegalArgumentException
{
// logger.info("[start: Updating profile information of network {}]", networkId);
try (NetworkDAO networkDao = new NetworkDAO()){
User user = getLoggedInUser();
UUID networkUUID = UUID.fromString(networkId);
if(networkDao.isReadOnly(networkUUID)) {
// logger.info("[end: Can't modify readonly network {}]", networkId);
throw new NdexException ("Can't update readonly network.");
}
if ( !networkDao.isWriteable(networkUUID, user.getExternalId())) {
logger.error("[end: No write permissions for user account {} on network {}]",
user.getUserName(), networkId);
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
Map<String,String> newValues = new HashMap<> ();
List<SimplePropertyValuePair> entityProperties = new ArrayList<>();
if ( partialSummary.getName() != null) {
newValues.put(NdexClasses.Network_P_name, partialSummary.getName());
entityProperties.add( new SimplePropertyValuePair("dc:title", partialSummary.getName()) );
}
if ( partialSummary.getDescription() != null) {
newValues.put( NdexClasses.Network_P_desc, partialSummary.getDescription());
entityProperties.add( new SimplePropertyValuePair("description", partialSummary.getDescription()) );
}
if ( partialSummary.getVersion()!=null ) {
newValues.put( NdexClasses.Network_P_version, partialSummary.getVersion());
entityProperties.add( new SimplePropertyValuePair("version", partialSummary.getVersion()) );
}
if ( newValues.size() > 0 ) {
if (!networkDao.networkIsValid(networkUUID))
throw new InvalidNetworkException();
try {
if ( networkDao.networkIsLocked(networkUUID,10)) {
throw new NetworkConcurrentModificationException ();
}
} catch (InterruptedException e2) {
e2.printStackTrace();
throw new NdexException("Failed to check network lock: " + e2.getMessage());
}
try {
networkDao.lockNetwork(networkUUID);
networkDao.updateNetworkProfile(networkUUID, newValues);
//DW: Handle provenance
//Special Logic. Test whether we should record provenance at all.
//If the only thing that has changed is the visibility, we should not add a provenance
//event.
ProvenanceEntity oldProv = networkDao.getProvenance(networkUUID);
String oldName = "", oldDescription = "", oldVersion ="";
if ( oldProv != null ) {
for( SimplePropertyValuePair oldProperty : oldProv.getProperties() ) {
if( oldProperty.getName() == null )
continue;
if( oldProperty.getName().equals("dc:title") )
oldName = oldProperty.getValue().trim();
else if( oldProperty.getName().equals("description") )
oldDescription = oldProperty.getValue().trim();
else if( oldProperty.getName().equals("version") )
oldVersion = oldProperty.getValue().trim();
}
}
//Treat all summary values that are null like ""
String summaryName = partialSummary.getName() == null ? "" : partialSummary.getName().trim();
String summaryDescription = partialSummary.getDescription() == null ? "" : partialSummary.getDescription().trim();
String summaryVersion = partialSummary.getVersion() == null ? "" : partialSummary.getVersion().trim();
ProvenanceEntity newProv = new ProvenanceEntity();
if( !oldName.equals(summaryName) || !oldDescription.equals(summaryDescription) || !oldVersion.equals(summaryVersion) )
{
if ( oldProv !=null ) //TODO: initialize the URI properly when there is null.
newProv.setUri(oldProv.getUri());
newProv.setProperties(entityProperties);
ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.UPDATE_NETWORK_PROFILE, partialSummary.getModificationTime());
List<SimplePropertyValuePair> eventProperties = new ArrayList<>();
Helper.addUserInfoToProvenanceEventProperties(eventProperties, user);
if (partialSummary.getName() != null)
eventProperties.add(new SimplePropertyValuePair("dc:title", partialSummary.getName()));
if (partialSummary.getDescription() != null)
eventProperties.add(new SimplePropertyValuePair("description", partialSummary.getDescription()));
if (partialSummary.getVersion() != null)
eventProperties.add(new SimplePropertyValuePair("version", partialSummary.getVersion()));
event.setProperties(eventProperties);
List<ProvenanceEntity> oldProvList = new ArrayList<>();
oldProvList.add(oldProv);
event.setInputs(oldProvList);
newProv.setCreationEvent(event);
networkDao.setProvenance(networkUUID, newProv);
}
NetworkSummary fullSummary = networkDao.getNetworkSummaryById(networkUUID);
//update the networkProperty aspect
List<NetworkAttributesElement> attrs = getNetworkAttributeAspectsFromSummary(fullSummary);
if ( attrs.size() > 0 ) {
try (CXAspectWriter writer = new CXAspectWriter(Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/aspects/"
+ NetworkAttributesElement.ASPECT_NAME) ) {
for ( NetworkAttributesElement e : attrs) {
writer.writeCXElement(e);
writer.flush();
}
}
}
//update metadata
MetaDataCollection metadata = networkDao.getMetaDataCollection(networkUUID);
MetaDataElement elmt = metadata.getMetaDataElement(NetworkAttributesElement.ASPECT_NAME);
if ( elmt == null) {
elmt = new MetaDataElement();
}
elmt.setElementCount(Long.valueOf(attrs.size()));
networkDao.updateMetadataColleciton(networkUUID, metadata);
//Recreate the CX file
CXNetworkFileGenerator g = new CXNetworkFileGenerator(networkUUID, fullSummary, metadata, newProv);
g.reCreateCXFile();
networkDao.unlockNetwork(networkUUID);
// update the solr Index
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,true,false));
} catch ( SQLException | IOException | IllegalArgumentException |NdexException e ) {
networkDao.rollback();
try {
networkDao.unlockNetwork(networkUUID);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
throw e;
}
}
} finally {
logger.info("[end: Updated profile information of network {}]", networkId);
}
}
@PUT
@Path("/{networkid}")
@Consumes("multipart/form-data")
@Produces("application/json")
@ApiDoc("This method updates an existing network with new content. The method takes a Network CX " +
"document as the PUT data. The Network's UUID is specified in the URL if this function. " +
" This method errors if the Network object is not " +
"provided or if its UUID does not correspond to an existing network on the NDEx Server. It also " +
"errors if the Network object is larger than a maximum size for network creation set in the NDEx " +
"server configuration. Network UUID is returned. This function also takes an optional 'provenance' field in the posted form."
+ " See createCXNetwork function for more details of this parameter.")
public void updateCXNetwork(final @PathParam("networkid") String networkIdStr,
MultipartFormDataInput input) throws Exception
{
// logger.info("[start: Updating network {} using CX data]", networkIdStr);
UUID networkId = UUID.fromString(networkIdStr);
String ownerAccName = null;
try ( NetworkDAO daoNew = new NetworkDAO() ) {
User user = getLoggedInUser();
try {
if( daoNew.isReadOnly(networkId)) {
logger.info("[end: Can't modify readonly network {}]", networkId);
throw new NdexException ("Can't update readonly network.");
}
if ( !daoNew.isWriteable(networkId, user.getExternalId())) {
logger.error("[end: No write permissions for user account {} on network {}]",
user.getUserName(), networkId);
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if ( daoNew.networkIsLocked(networkId)) {
daoNew.close();
throw new NetworkConcurrentModificationException ();
}
daoNew.lockNetwork(networkId);
ownerAccName = daoNew.getNetworkOwnerAcc(networkId);
UUID tmpNetworkId = storeRawNetwork (input);
String cxFileName = Configuration.getInstance().getNdexRoot() + "/data/" + tmpNetworkId.toString() + "/network.cx";
long fileSize = new File(cxFileName).length();
daoNew.clearNetworkSummary(networkId, fileSize);
java.nio.file.Path src = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + tmpNetworkId);
java.nio.file.Path tgt = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + networkId);
FileUtils.deleteDirectory(new File(Configuration.getInstance().getNdexRoot() + "/data/" + networkId));
Files.move(src, tgt, StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);
String urlStr = Configuration.getInstance().getHostURI() +
Configuration.getInstance().getRestAPIPrefix()+"/network/"+ networkIdStr;
ProvenanceEntity entity = new ProvenanceEntity();
entity.setUri(urlStr + "/summary");
ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.CX_NETWORK_UPDATE, new Timestamp(System.currentTimeMillis()));
List<SimplePropertyValuePair> eventProperties = new ArrayList<>();
Helper.addUserInfoToProvenanceEventProperties( eventProperties, this.getLoggedInUser());
event.setProperties(eventProperties);
ProvenanceEntity inputEntity =daoNew.getProvenance(networkId);
event.addInput(inputEntity);
entity.setCreationEvent(event);
daoNew.setProvenance(networkId, entity);
daoNew.commit();
// daoNew.unlockNetwork(networkId);
} catch (SQLException | NdexException | IOException e) {
// e.printStackTrace();
daoNew.rollback();
daoNew.unlockNetwork(networkId);
throw e;
}
}
NdexServerQueue.INSTANCE.addSystemTask(new CXNetworkLoadingTask(networkId, ownerAccName, true));
// return networkIdStr;
}
@DELETE
@Path("/{networkid}")
@Produces("application/json")
@ApiDoc("Deletes the network specified by networkId. There is no method to undo a deletion, so care " +
"should be exercised. A user can only delete networks that they own.")
public void deleteNetwork(final @PathParam("networkid") String id) throws NdexException, SQLException {
try (NetworkDAO networkDao = new NetworkDAO()) {
UUID networkId = UUID.fromString(id);
UUID userId = getLoggedInUser().getExternalId();
if(networkDao.isAdmin(networkId, userId) ) {
if (!networkDao.isReadOnly(networkId) ) {
if ( !networkDao.networkIsLocked(networkId)) {
/*
NetworkGlobalIndexManager globalIdx = new NetworkGlobalIndexManager();
globalIdx.deleteNetwork(id);
try (SingleNetworkSolrIdxManager idxManager = new SingleNetworkSolrIdxManager(id)) {
idxManager.dropIndex();
}
*/
networkDao.deleteNetwork(UUID.fromString(id), getLoggedInUser().getExternalId());
networkDao.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskDeleteNetwork(networkId));
return;
}
throw new NetworkConcurrentModificationException ();
}
throw new NdexException("Can't delete a read-only network.");
}
throw new NdexException("Only network owner can delete a network.");
} catch ( IOException e ) {
throw new NdexException ("Error occurred when deleting network: " + e.getMessage(), e);
}
}
/**************************************************************************
* Saves an uploaded network file. Determines the type of file uploaded,
* saves the file, and creates a task.
*
* @param uploadedNetwork
* The uploaded network file.
* @throws IllegalArgumentException
* Bad input.
* @throws NdexException
* Failed to parse the file, or create the network in the
* database.
* @throws IOException
**************************************************************************/
/*
* refactored to support non-transactional database operations
*/
@POST
@Path("/upload")
@Consumes("multipart/form-data")
@Produces("application/json")
@ApiDoc("Upload a network file into the current users NDEx account. This can take some time while background " +
"processing converts the data from the file into the common NDEx format. This method errors if the " +
"network is missing or if it has no filename or no file data.")
public Task uploadNetwork( MultipartFormDataInput input)
//@MultipartForm UploadedFile uploadedNetwork)
throws IllegalArgumentException, SecurityException, NdexException, IOException {
logger.info("[start: Uploading network file]");
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
List<InputPart> foo = uploadForm.get("filename");
String fname = "";
for (InputPart inputPart : foo)
{
// convert the uploaded file to inputstream and write it to disk
fname += inputPart.getBodyAsString();
}
if (fname.length() <1) {
throw new NdexException ("");
}
String ext = FilenameUtils.getExtension(fname).toLowerCase();
if ( !ext.equals("sif") && !ext.equals("xbel") && !ext.equals("xgmml") && !ext.equals("owl") && !ext.equals("cx")
&& !ext.equals("xls") && ! ext.equals("xlsx")) {
logger.error("[end: The uploaded file type is not supported; must be Excel, XGMML, SIF, BioPAX cx, or XBEL. Throwing NdexException...]");
throw new NdexException(
"The uploaded file type is not supported; must be Excel, XGMML, SIF, BioPAX, cx or XBEL.");
}
UUID taskId = NdexUUIDFactory.INSTANCE.createNewNDExUUID();
final File uploadedNetworkPath = new File(Configuration.getInstance().getNdexRoot() +
"/uploaded-networks");
if (!uploadedNetworkPath.exists())
uploadedNetworkPath.mkdir();
String fileFullPath = uploadedNetworkPath.getAbsolutePath() + "/" + taskId + "." + ext;
//Get file data to save
List<InputPart> inputParts = uploadForm.get("fileUpload");
final File uploadedNetworkFile = new File(fileFullPath);
if (!uploadedNetworkFile.exists())
try {
uploadedNetworkFile.createNewFile();
} catch (IOException e1) {
logger.error("[end: Failed to create file {} on server when uploading {}. Exception caught:]{}",
fileFullPath, fname, e1);
throw new NdexException ("Failed to create file " + fileFullPath + " on server when uploading " +
fname + ": " + e1.getMessage());
}
byte[] bytes = new byte[2048];
for (InputPart inputPart : inputParts)
{
// convert the uploaded file to inputstream and write it to disk
InputStream inputStream = inputPart.getBody(InputStream.class, null);
OutputStream out = new FileOutputStream(new File(fileFullPath));
int read = 0;
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
}
Task processNetworkTask = new Task();
processNetworkTask.setExternalId(taskId);
processNetworkTask.setDescription(fname); //uploadedNetwork.getFilename());
processNetworkTask.setTaskType(TaskType.PROCESS_UPLOADED_NETWORK);
processNetworkTask.setPriority(Priority.LOW);
processNetworkTask.setProgress(0);
processNetworkTask.setResource(fileFullPath);
processNetworkTask.setStatus(Status.QUEUED);
processNetworkTask.setTaskOwnerId(this.getLoggedInUser().getExternalId());
try (TaskDAO dao = new TaskDAO()){
dao.createTask(processNetworkTask);
dao.commit();
} catch (IllegalArgumentException iae) {
logger.error("[end: Exception caught:]{}", iae);
throw iae;
} catch (Exception e) {
logger.error("[end: Exception caught:]{}", e);
throw new NdexException(e.getMessage());
}
logger.info("[end: Uploading network file. Task for uploading network is created.]");
return processNetworkTask;
}
@PUT
@Path("/{networkid}/systemproperty")
@Produces("application/json")
@ApiDoc("Set the system flag specified by ‘parameter’ to ‘value’ for the network with id ‘networkId’. As of " +
"NDEx v1.2, the only supported parameter is readOnly={true|false}. In 2.0, we added visibility={PUBLIC|PRIVATE}")
public void setNetworkFlag(
@PathParam("networkid") final String networkIdStr,
final Map<String,Object> parameters)
throws IllegalArgumentException, NdexException, SQLException, IOException {
try (NetworkDAO networkDao = new NetworkDAO()) {
UUID networkId = UUID.fromString(networkIdStr);
UUID userId = getLoggedInUser().getExternalId();
// if ( !networkDao.networkIsLocked(networkId)) {
if ( !networkDao.networkIsValid(networkId))
throw new InvalidNetworkException();
if ( parameters.containsKey(readOnlyParameter)) {
if (!networkDao.isAdmin(networkId, userId))
throw new UnauthorizedOperationException("Only network owner can set readOnly Parameter.");
boolean bv = ((Boolean)parameters.get(readOnlyParameter)).booleanValue();
networkDao.setFlag(networkId, "readonly",bv);
}
if ( parameters.containsKey("visibility")) {
if (!networkDao.isAdmin(networkId, userId))
throw new UnauthorizedOperationException("Only network owner can set visibility Parameter.");
networkDao.updateNetworkVisibility(networkId, VisibilityType.valueOf((String)parameters.get("visibility")));
// update the solr Index
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,true,false));
}
if ( parameters.containsKey("showcase")) {
boolean bv = ((Boolean)parameters.get("showcase")).booleanValue();
networkDao.setShowcaseFlag(networkId, userId, bv);
}
networkDao.commit();
return;
// }
// throw new NetworkConcurrentModificationException ();
}
}
@POST
// @PermitAll
@Path("")
@Produces("text/plain")
@Consumes("multipart/form-data")
@ApiDoc("Create a network from the uploaded CX stream. The input cx data is expected to be in the CXNetworkStream field of posted multipart/form-data. "
+ "There is an optional 'provenance' field in the form. Users can use this field to pass in a JSON string of ProvenanceEntity object. When a user pass"
+ " in this object, NDEx server will add this object to the provenance history of the CX network. Otherwise NDEx server will create a ProvenanceEntity "
+ "object and add it to the provenance history of the CX network.")
public Response createCXNetwork( MultipartFormDataInput input
) throws Exception
{
// logger.info("[start: Creating a new network based on a POSTed CX stream.]");
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
UUID uuid = storeRawNetwork ( input);
String uuidStr = uuid.toString();
String urlStr = Configuration.getInstance().getHostURI() +
Configuration.getInstance().getRestAPIPrefix()+"/network/"+ uuidStr;
ProvenanceEntity entity = new ProvenanceEntity();
entity.setUri(urlStr + "/summary");
String cxFileName = Configuration.getInstance().getNdexRoot() + "/data/" + uuidStr + "/network.cx";
long fileSize = new File(cxFileName).length();
// create entry in db.
try (NetworkDAO dao = new NetworkDAO()) {
NetworkSummary summary = dao.CreateEmptyNetworkEntry(uuid, getLoggedInUser().getExternalId(), getLoggedInUser().getUserName(), fileSize);
ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.CX_CREATE_NETWORK, summary.getModificationTime());
List<SimplePropertyValuePair> eventProperties = new ArrayList<>();
Helper.addUserInfoToProvenanceEventProperties( eventProperties, this.getLoggedInUser());
event.setProperties(eventProperties);
entity.setCreationEvent(event);
dao.setProvenance(summary.getExternalId(), entity);
dao.commit();
}
NdexServerQueue.INSTANCE.addSystemTask(new CXNetworkLoadingTask(uuid, getLoggedInUser().getUserName(), false));
logger.info("[end: Created a new network based on a POSTed CX stream.]");
URI l = new URI (urlStr);
return Response.created(l).entity(l).build();
}
private static UUID storeRawNetwork (MultipartFormDataInput input) throws IOException {
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
// ProvenanceEntity entity = this.getProvenanceEntityFromMultiPart(uploadForm);
//Get file data to save
List<InputPart> inputParts = uploadForm.get("CXNetworkStream");
byte[] bytes = new byte[8192];
UUID uuid = NdexUUIDFactory.INSTANCE.createNewNDExUUID();
String pathPrefix = Configuration.getInstance().getNdexRoot() + "/data/" + uuid.toString();
//Create dir
java.nio.file.Path dir = Paths.get(pathPrefix);
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rwxrwxr-x");
FileAttribute<Set<PosixFilePermission>> attr =
PosixFilePermissions.asFileAttribute(perms);
Files.createDirectory(dir,attr);
//write content to file
String cxFilePath = pathPrefix + "/network.cx";
try (FileOutputStream out = new FileOutputStream (cxFilePath ) ){
for (InputPart inputPart : inputParts) {
// convert the uploaded file to inputstream and write it to disk
org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl p =
(org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl) inputPart;
try (InputStream inputStream = p.getBody()) {
int read = 0;
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
}
}
}
return uuid;
}
private static List<NetworkAttributesElement> getNetworkAttributeAspectsFromSummary(NetworkSummary summary)
throws JsonParseException, JsonMappingException, IOException {
List<NetworkAttributesElement> result = new ArrayList<>();
if ( summary.getName() !=null)
result.add(new NetworkAttributesElement(null, NdexClasses.Network_P_name, summary.getName()));
if ( summary.getDescription() != null)
result.add(new NetworkAttributesElement(null, NdexClasses.Network_P_desc, summary.getDescription()));
if ( summary.getVersion() !=null)
result.add(new NetworkAttributesElement(null, NdexClasses.Network_P_version, summary.getVersion()));
if ( summary.getProperties() != null) {
for ( NdexPropertyValuePair p : summary.getProperties()) {
result.add(NetworkAttributesElement.createInstanceWithJsonValue(p.getSubNetworkId(), p.getPredicateString(),
p.getValue(), ATTRIBUTE_DATA_TYPE.fromCxLabel(p.getDataType())));
}
}
return result;
}
@POST
@Path("/{networkid}/copy")
@Produces("text/plain")
public Response cloneNetwork( @PathParam("networkid") final String srcNetworkUUIDStr) throws Exception
{
// logger.info("[start: Creating a new network based on a POSTed CX stream.]");
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
UUID srcNetUUID = UUID.fromString(srcNetworkUUIDStr);
try ( NetworkDAO dao = new NetworkDAO ()) {
if ( ! dao.isReadable(srcNetUUID, getLoggedInUserId()) )
throw new UnauthorizedOperationException("User doesn't have read access to this network.");
if (!dao.networkIsValid(srcNetUUID)) {
throw new NdexException ("Invalid networks can not be copied.");
}
}
UUID uuid = NdexUUIDFactory.INSTANCE.createNewNDExUUID();
String uuidStr = uuid.toString();
// java.nio.file.Path src = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + srcNetUUID.toString());
java.nio.file.Path tgt = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + uuidStr);
//Create dir
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rwxrwxr-x");
FileAttribute<Set<PosixFilePermission>> attr =
PosixFilePermissions.asFileAttribute(perms);
Files.createDirectory(tgt,attr);
File srcAspectDir = new File ( Configuration.getInstance().getNdexRoot() + "/data/" + srcNetUUID.toString() + "/aspects");
File tgtAspectDir = new File ( Configuration.getInstance().getNdexRoot() + "/data/" + uuidStr + "/aspects");
FileUtils.copyDirectory(srcAspectDir, tgtAspectDir);
String urlStr = Configuration.getInstance().getHostURI() +
Configuration.getInstance().getRestAPIPrefix()+"/network/"+ uuidStr;
// ProvenanceEntity entity = new ProvenanceEntity();
// entity.setUri(urlStr + "/summary");
String cxFileName = Configuration.getInstance().getNdexRoot() + "/data/" + srcNetUUID.toString() + "/network.cx";
long fileSize = new File(cxFileName).length();
// copy sample
java.nio.file.Path srcSample = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + srcNetUUID.toString() + "/sample.cx");
if ( Files.exists(srcSample, LinkOption.NOFOLLOW_LINKS)) {
java.nio.file.Path tgtSample = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + uuidStr + "/sample.cx");
Files.copy(srcSample, tgtSample);
}
// create entry in db.
try (NetworkDAO dao = new NetworkDAO()) {
NetworkSummary summary = dao.CreateCloneNetworkEntry(uuid, getLoggedInUser().getExternalId(), getLoggedInUser().getUserName(), fileSize, srcNetUUID);
ProvenanceEntity sourceProvenanceEntity = dao.getProvenance(srcNetUUID);
ProvenanceEntity copyProv = ProvenanceHelpers.createProvenanceHistory(
summary,
Configuration.getInstance().getHostURI(),
NdexProvenanceEventType.CX_NETWORK_CLONE,
new Timestamp(Calendar.getInstance().getTimeInMillis()),
sourceProvenanceEntity
);
dao.setProvenance(uuid, copyProv);
CXNetworkFileGenerator g = new CXNetworkFileGenerator(uuid, dao, new Provenance(copyProv));
g.reCreateCXFile();
dao.commit();
}
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(uuid,true,true));
logger.info("[end: Created a new network based on a POSTed CX stream.]");
URI l = new URI (urlStr);
return Response.created(l).entity(l).build();
}
@POST
@PermitAll
@Path("/properties/score")
@Produces("application/json")
public static int getScoresFromProperties(
final List<NdexPropertyValuePair> properties)
throws Exception {
return Util.getNetworkScores (properties, true);
}
@POST
@PermitAll
@Path("/summary/score")
@Produces("application/json")
public static int getScoresFromNetworkSummary(
final NetworkSummary summary)
throws Exception {
return Util.getNdexScoreFromSummary(summary);
}
}
|
finish the change to network service.
|
src/main/java/org/ndexbio/rest/services/NetworkServiceV2.java
|
finish the change to network service.
|
|
Java
|
bsd-3-clause
|
623299e620c5ca02e69b7e3d412467b0c6ce2656
| 0
|
mosauter/Battleship
|
package de.htwg.battleship.aview.gui;
import de.htwg.battleship.controller.IMasterController;
import de.htwg.battleship.model.IPlayer;
import de.htwg.battleship.model.IShip;
import de.htwg.battleship.observer.IObserver;
import static de.htwg.battleship.util.StatCollection.createMap;
import static de.htwg.battleship.util.StatCollection.fillMap;
import static de.htwg.battleship.util.StatCollection.heightLenght;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import java.util.Set;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
/**
* Graphical User Interface for the Game
*
* @version 1.00
* @since 2014-12-20
*/
@SuppressWarnings("serial")
public final class GUI extends JFrame implements IObserver {
/**
* Constant that indicates how long the JPopupDialogs should be shown before
* they close automatically.
*/
private static final long DISPLAYTIME = 1000L;
/**
* width/height for the description labels.
*/
private static final int DESCRIPTION_WIDTH_HEIGHT = 40;
/**
* space for yAxis.
*/
private static final int Y_AXIS_GAP = 30;
/**
* space for xAxis.
*/
private static final int X_AXIS_GAP = 10;
/**
* height of the bottom label.
*/
private static final int BOTTOM_HEIGHT = 50;
/**
* width of the east label.
*/
private static final int EAST_WIDTH = 100;
/**
* width of the mainframe.
*/
private static final int FRAME_WIDTH = 1000;
/**
* height of the mainframe.
*/
private static final int FRAME_HEIGHT = 610;
/**
* Dimension for Buttons in the JLabel east.
*/
private static final Dimension EAST_BUTTONS = new Dimension(90, 30);
/**
* Dimension for playername frame.
*/
private static final Dimension PLAYER_FRAME = new Dimension(300, 150);
/**
* Dimension for the menuFrame.
*/
private static final Dimension MENU_FRAME_SIZE = new Dimension(800, 500);
/**
* set Bound for playerframe button.
*/
private static final Rectangle PLAYER_FRAME_BUTTON
= new Rectangle(75, 80, 150, 30);
/**
* set Bounds for playerframe label.
*/
private static final Rectangle PLAYER_FRAME_LABEL
= new Rectangle(25, 5, 250, 30);
/**
* set Bounds for playerframe textfield.
*/
private static final Rectangle PLAYER_FRAME_TEXT
= new Rectangle(25, 40, 250, 30);
/**
* set Bounds for menuframe startbutton.
*/
private static final Rectangle MENU_FRAME_START_BUTTON
= new Rectangle(300, 240, 200, 50);
/**
* set Bounds for menuframe exitbutton.
*/
private static final Rectangle MENU_FRAME_EXIT_BUTTON
= new Rectangle(300, 310, 200, 50);
/**
* default Font.
*/
private static final Font FONT = new Font("Helvetica", Font.BOLD, 12);
/**
* Border for selected Field.
*/
private static final LineBorder SELECTED = new LineBorder(Color.RED, 4);
/**
* JButton to start or later to restart the Game.
*/
private final JButton start = new JButton("Start Game");
/**
* JButton to exit the whole game right at the beginning or at the end.
*/
private final JButton exit = new JButton("Exit");
/**
* JButton to show the Gamefield of player1 after the Game.
*/
private final JButton endPlayer1 = new JButton();
/**
* JButton to show the Gamefield of player2 after the Game.
*/
private final JButton endPlayer2 = new JButton();
/**
* Button to place a ship in horizontal direction.
*/
private final JButton hor = new JButton("horizontal");
/**
* Button to place a ship in vertical direction.
*/
private final JButton ver = new JButton("vertical");
/**
* JButton[][] for the Field. Button named with: 'x + " " + y'
*/
private final JButton[][] buttonField
= new JButton[heightLenght][heightLenght];
/**
* default Background for mainframe.
*/
private final ImageIcon background
= new ImageIcon(getClass().getResource("background.jpg"));
/**
* default background for the menuframe.
*/
private final ImageIcon backgroundMenu
= new ImageIcon(getClass().getResource("background_menu.jpg"));
/**
* default ImageIcon for non-hitted fields.
*/
private final ImageIcon wave
= new ImageIcon(getClass().getResource("wave.jpg"));
/**
* ImageIcon for missed shots.
*/
private final ImageIcon miss
= new ImageIcon(getClass().getResource("miss.jpg"));
/**
* ImageIcon for ship placed fields.
*/
private final ImageIcon ship
= new ImageIcon(getClass().getResource("ship.jpg"));
/**
* ImageIcon for hitted fields with ship.
*/
private final ImageIcon hit
= new ImageIcon(getClass().getResource("ship_hit.jpg"));
/**
* ImageIcon for JLabels with invisible background.
*/
private final ImageIcon invisible
= new ImageIcon(getClass().getResource("invisible.png"));
/**
* To save the MasterController for all of the several UIs.
*/
private final IMasterController master;
/**
* Container which contains all object of the mainframe.
*/
private final Container container;
/**
* JLabel for the center of the mainframe.
*/
private JLabel center;
/**
* JLabel for the east side of the mainframe.
*/
private JLabel east;
/**
* JLabel for the x-Axis description.
*/
private JLabel xAxis;
/**
* JLabel for the y-Axis description.
*/
private JLabel yAxis;
/**
* JLabel to send out instructions.
*/
private JLabel ausgabe;
/**
* JButton where the Ship should be placed.
*/
private JButton shipPlacePosition;
/**
* JDialog which has to be saved that the program can dispose them after its
* not in use anymore.
*/
private JDialog notifyframe;
/**
* JTextField where the player should input his name.
*/
private JTextField player;
/**
* JFrame for the menu.
*/
private JFrame menuFrame;
/**
* Public Contructor to create a GUI.
*
* @param master MasterController which is the same for all UI
*/
public GUI(final IMasterController master) {
master.addObserver(this);
this.master = master;
//Initialize mainFrame
this.setTitle("Battleship");
this.setIconImage(new ImageIcon(
getClass().getResource("frame_icon.jpg")).getImage());
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.container = new JLabel(background);
this.add(container);
//Initialize Menu
this.menuFrame();
//start Game
this.newGame();
}
/**
* Method build the menuframe.
*/
private void menuFrame() {
this.menuFrame = new JFrame("Battleship");
this.menuFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
//build Buttons
this.start.setBounds(MENU_FRAME_START_BUTTON);
this.exit.setBounds(MENU_FRAME_EXIT_BUTTON);
this.start.setIcon(new ImageIcon(
getClass().getResource("menubutton_1.jpg")));
this.start.setRolloverIcon(new ImageIcon(
getClass().getResource("menubutton_1_mouseover.jpg")));
this.start.setBorder(null);
this.exit.setIcon(new ImageIcon(
getClass().getResource("menubutton_2.jpg")));
this.exit.setRolloverIcon(new ImageIcon(
getClass().getResource("menubutton_2_mouseover.jpg")));
this.exit.setBorder(null);
this.start.addActionListener(new MenuListener());
this.exit.addActionListener(new MenuListener());
//Container setup
JLabel startContainer = new JLabel(backgroundMenu);
startContainer.setLayout(null);
startContainer.add(start);
startContainer.add(exit);
//Frame setup
this.menuFrame.add(startContainer);
this.menuFrame.setSize(MENU_FRAME_SIZE);
this.menuFrame.setResizable(false);
this.menuFrame.setLocationRelativeTo(null);
this.menuFrame.setIconImage(new ImageIcon(
getClass().getResource("frame_icon.jpg")).getImage());
this.menuFrame.setVisible(true);
}
/**
* Method to initialize the GUI for the fields.
*/
public void newGame() {
//new Layout
container.setLayout(new BorderLayout(0, 0));
//panel for the left description
JLabel left = new JLabel();
left.setPreferredSize(new Dimension(DESCRIPTION_WIDTH_HEIGHT,
FRAME_HEIGHT
- BOTTOM_HEIGHT
- DESCRIPTION_WIDTH_HEIGHT));
left.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
yAxis = new JLabel();
yAxis.setPreferredSize(new Dimension(DESCRIPTION_WIDTH_HEIGHT,
FRAME_HEIGHT
- BOTTOM_HEIGHT
- DESCRIPTION_WIDTH_HEIGHT
- Y_AXIS_GAP));
yAxis.setLayout(new GridLayout(heightLenght, 1));
yAxis.setVerticalTextPosition(SwingConstants.CENTER);
left.add(yAxis);
container.add(left, BorderLayout.WEST);
//panel for top description
JLabel top = new JLabel();
top.setPreferredSize(
new Dimension(FRAME_WIDTH, DESCRIPTION_WIDTH_HEIGHT));
top.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
xAxis = new JLabel();
xAxis.setLayout(new GridLayout(1, heightLenght));
xAxis.setPreferredSize(new Dimension(
FRAME_WIDTH
- DESCRIPTION_WIDTH_HEIGHT
- EAST_WIDTH
- X_AXIS_GAP,
DESCRIPTION_WIDTH_HEIGHT));
//panel for the place in the higher left corner
JLabel leftHigherCorner = new JLabel();
leftHigherCorner.setPreferredSize(
new Dimension(DESCRIPTION_WIDTH_HEIGHT,
DESCRIPTION_WIDTH_HEIGHT));
// adding components
top.add(leftHigherCorner);
top.add(xAxis);
container.add(top, BorderLayout.NORTH);
//build gameField
center = new JLabel();
buildGameField();
container.add(center, BorderLayout.CENTER);
//bottom
JLabel bottom = new JLabel();
bottom.setPreferredSize(new Dimension(FRAME_WIDTH, BOTTOM_HEIGHT));
bottom.setLayout(new FlowLayout());
ausgabe = new JLabel();
ausgabe.setHorizontalTextPosition(SwingConstants.CENTER);
ausgabe.setVerticalTextPosition(SwingConstants.CENTER);
ausgabe.setPreferredSize(new Dimension(FRAME_WIDTH, BOTTOM_HEIGHT));
ausgabe.setHorizontalAlignment(SwingConstants.CENTER);
ausgabe.setFont(GUI.FONT);
ausgabe.setForeground(Color.WHITE);
ausgabe.setIcon(new ImageIcon(
getClass().getResource("invisible_ausgabe.png")));
bottom.add(ausgabe);
this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
this.setLocationRelativeTo(null);
container.add(bottom, BorderLayout.SOUTH);
//right
east = new JLabel();
east.setPreferredSize(new Dimension(EAST_WIDTH, 1));
east.setLayout(new FlowLayout(FlowLayout.LEFT));
container.add(east, BorderLayout.EAST);
}
/**
* Utility-Method to Build the main Gamefield.
*/
private void buildGameField() {
GridLayout gl = new GridLayout(heightLenght, heightLenght);
center.setLayout(gl);
for (int y = 0; y < heightLenght; y++) {
JLabel xLabel = new JLabel();
JLabel yLabel = new JLabel();
xLabel.setHorizontalTextPosition(SwingConstants.CENTER);
xLabel.setVerticalTextPosition(SwingConstants.CENTER);
yLabel.setHorizontalTextPosition(SwingConstants.CENTER);
yLabel.setVerticalTextPosition(SwingConstants.CENTER);
xLabel.setForeground(Color.WHITE);
yLabel.setForeground(Color.WHITE);
xLabel.setText("" + (y + 1));
yLabel.setText("" + (char) ('A' + y));
yAxis.add(yLabel);
xAxis.add(xLabel);
for (int x = 0; x < heightLenght; x++) {
String name = x + " " + y;
this.buttonField[x][y] = new JButton();
this.buttonField[x][y].setName(name);
this.buttonField[x][y].setIcon(wave);
center.add(buttonField[x][y]);
}
}
}
/**
* Utility-Method to create a JDialog where the user should insert his name.
*
* @param playernumber indicates the player number
*/
private void getPlayername(final int playernumber) {
PlayerListener pl = new PlayerListener();
JLabel icon = new JLabel(background);
icon.setPreferredSize(PLAYER_FRAME);
JLabel text = new JLabel(invisible);
text.setHorizontalTextPosition(SwingConstants.CENTER);
text.setForeground(Color.WHITE);
text.setText("please insert playername " + playernumber);
text.setBounds(PLAYER_FRAME_LABEL);
player = new JTextField();
player.setBorder(new LineBorder(Color.BLACK, 1));
player.setFont(this.FONT);
player.setBounds(PLAYER_FRAME_TEXT);
JButton submit = new JButton("OK");
submit.setIcon(new ImageIcon(
getClass().getResource("playername_button.jpg")));
submit.setRolloverIcon(new ImageIcon(
getClass().getResource("playername_button_mouseover.jpg")));
submit.setBorder(null);
submit.setBounds(PLAYER_FRAME_BUTTON);
submit.addActionListener(pl);
notifyframe = new JDialog();
notifyframe.add(icon);
notifyframe.setModal(true);
notifyframe.setSize(PLAYER_FRAME);
icon.setLayout(null);
icon.add(text);
icon.add(player);
icon.add(submit);
notifyframe.setResizable(false);
notifyframe.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
notifyframe.setLocationRelativeTo(getParent());
notifyframe.getRootPane().setDefaultButton(submit);
notifyframe.setVisible(true);
}
/**
* Utility-Method to add the 'place'-Button and a ComboBox to the main
* frame.
*/
private void placeShip() {
this.setVisible(false);
east.remove(hor);
east.remove(ver);
hor.addActionListener(new PlaceListener());
ver.addActionListener(new PlaceListener());
resetPlaceButton();
this.ver.setPreferredSize(EAST_BUTTONS);
this.ver.setIcon(new ImageIcon(getClass().getResource("vertical.jpg")));
this.ver.setRolloverIcon(new ImageIcon(
getClass().getResource("vertical_mouseover.jpg")));
this.ver.setBorder(null);
this.hor.setPreferredSize(EAST_BUTTONS);
this.hor.setIcon(new ImageIcon(
getClass().getResource("horizontal.jpg")));
this.hor.setRolloverIcon(new ImageIcon(
getClass().getResource("horizontal_mouseover.jpg")));
this.hor.setBorder(null);
east.add(hor);
east.add(ver);
this.setVisible(true);
}
/**
* Utility-Method to update the image-icons of the gamefield buttons.
* @param player current player
* @param hideShips boolean
*/
private void updateGameField(final IPlayer player,
final boolean hideShips) {
IShip[] shipList = player.getOwnBoard().getShipList();
Map<Integer, Set<Integer>> map = createMap();
fillMap(shipList, map, player.getOwnBoard().getShips());
for (int y = 0; y < heightLenght; y++) {
for (int x = 0; x < heightLenght; x++) {
boolean isShip = false;
this.buttonField[x][y].setBorder(new JButton().getBorder());
for (Integer value : map.get(y)) {
if (value == x) {
if (player.getOwnBoard().isHit(x, y)) {
this.buttonField[x][y].setIcon(hit);
} else {
if (hideShips) {
this.buttonField[x][y].setIcon(wave);
} else {
this.buttonField[x][y].setIcon(ship);
}
}
isShip = true;
}
}
if (!isShip) {
if (player.getOwnBoard().isHit(x, y)) {
this.buttonField[x][y].setIcon(miss);
} else {
this.buttonField[x][y].setIcon(wave);
}
}
}
}
}
/**
* Utility-Method to reset the selected button in the place states.
*/
private void resetPlaceButton() {
if (shipPlacePosition != null) {
shipPlacePosition.setBorder(new JButton().getBorder());
shipPlacePosition = null;
}
}
/**
* Utility-Method to show the Gamefield after the Game.
*/
private void endGame() {
this.setVisible(false);
for (JButton[] buttonArray : buttonField) {
for (JButton button : buttonArray) {
removeListener(button);
}
}
this.endPlayer1.setPreferredSize(EAST_BUTTONS);
this.endPlayer2.setPreferredSize(EAST_BUTTONS);
this.endPlayer1.setBorder(null);
this.endPlayer2.setBorder(null);
this.endPlayer1.setIcon(new ImageIcon(
getClass().getResource("end_playername.jpg")));
this.endPlayer2.setIcon(new ImageIcon(
getClass().getResource("end_playername.jpg")));
this.endPlayer1.setRolloverIcon(new ImageIcon(
getClass().getResource("end_playername_mouseover.jpg")));
this.endPlayer2.setRolloverIcon(new ImageIcon(
getClass().getResource("end_playername_mouseover.jpg")));
this.endPlayer1.setVerticalTextPosition(SwingConstants.CENTER);
this.endPlayer2.setVerticalTextPosition(SwingConstants.CENTER);
this.endPlayer1.setHorizontalTextPosition(SwingConstants.CENTER);
this.endPlayer2.setHorizontalTextPosition(SwingConstants.CENTER);
this.endPlayer1.setText(master.getPlayer1().getName());
this.endPlayer2.setText(master.getPlayer2().getName());
this.endPlayer1.setFont(GUI.FONT);
this.endPlayer2.setFont(GUI.FONT);
this.endPlayer1.setForeground(Color.WHITE);
this.endPlayer2.setForeground(Color.WHITE);
this.endPlayer1.addActionListener(new WinListener());
this.endPlayer2.addActionListener(new WinListener());
JButton finish = new JButton();
finish.setBorder(null);
finish.setPreferredSize(EAST_BUTTONS);
finish.setIcon(new ImageIcon(getClass().getResource("finish.jpg")));
finish.setRolloverIcon(new ImageIcon(
getClass().getResource("finish_mouseover.jpg")));
finish.addActionListener(new WinListener());
east.add(this.endPlayer1);
east.add(this.endPlayer2);
east.add(finish);
this.setVisible(true);
}
/**
* Utility-Method to set the mainframe invisible.
*/
private void setInvisible() {
this.setVisible(false);
}
@Override
public void update() {
switch (master.getCurrentState()) {
case START:
break;
case GETNAME1:
menuFrame.dispose();
getPlayername(1);
break;
case GETNAME2:
notifyframe.dispose();
getPlayername(2);
break;
case PLACE1:
notifyframe.dispose();
resetPlaceButton();
activateListener(new PlaceListener());
updateGameField(master.getPlayer1(), false);
placeShip();
ausgabe.setText(master.getPlayer1().getName()
+ " now place the ship with the length of "
+ (master.getPlayer1().getOwnBoard().getShips() + 2));
break;
case PLACE2:
resetPlaceButton();
activateListener(new PlaceListener());
updateGameField(master.getPlayer2(), false);
placeShip();
ausgabe.setText(master.getPlayer2().getName()
+ " now place the ship with the length of "
+ (master.getPlayer2().getOwnBoard().getShips() + 2));
break;
case FINALPLACE1:
updateGameField(master.getPlayer1(), false);
resetPlaceButton();
break;
case FINALPLACE2:
updateGameField(master.getPlayer2(), false);
resetPlaceButton();
break;
case PLACEERR:
new JPopupDialog(this, "Placement error",
"Cannot place a ship there due to a collision or "
+ "the ship is out of the field!",
DISPLAYTIME, false);
break;
case SHOOT1:
this.setVisible(false);
east.remove(hor);
east.remove(ver);
this.setVisible(true);
activateListener(new ShootListener());
updateGameField(master.getPlayer2(), true);
ausgabe.setText(master.getPlayer1().getName()
+ " is now at the turn to shoot");
break;
case SHOOT2:
activateListener(new ShootListener());
updateGameField(master.getPlayer1(), true);
ausgabe.setText(master.getPlayer2().getName()
+ " is now at the turn to shoot");
break;
case HIT:
new JPopupDialog(this, "Shot Result",
"Your shot was a Hit!!", DISPLAYTIME, false);
break;
case MISS:
new JPopupDialog(this, "Shot Result",
"Your shot was a Miss!!", DISPLAYTIME, false);
break;
case WIN1:
updateGameField(master.getPlayer2(), false);
String msg = master.getPlayer1().getName() + " has won!!";
ausgabe.setText(msg);
new JPopupDialog(this, "Winner!", msg,
DISPLAYTIME, false);
break;
case WIN2:
updateGameField(master.getPlayer1(), false);
msg = master.getPlayer2().getName() + " has won!!";
ausgabe.setText(msg);
new JPopupDialog(this, "Winner!", msg,
DISPLAYTIME, false);
break;
case END:
endGame();
break;
case WRONGINPUT:
// isn't needed in the GUI, help-state for a UI where you
// can give input at the false states
break;
default:
break;
}
}
/**
* Method to activate a new Action Listener to the JButton[][]-Matrix. uses
* the removeListener-Method
*
* @param newListener the new Listener of the button matrix
*/
private void activateListener(final ActionListener newListener) {
for (JButton[] buttonArray : buttonField) {
for (JButton button : buttonArray) {
removeListener(button);
button.addActionListener(newListener);
}
}
}
/**
* Method which removes all Listener from a button.
* @param button specified button
*/
private void removeListener(final JButton button) {
if (button == null) {
return;
}
ActionListener[] actionList = button.getActionListeners();
for (ActionListener acLst : actionList) {
button.removeActionListener(acLst);
}
}
/**
* ActionListener for the State of the Game in which the Player has to set
* his Ships on the field. PLACE1 / PLACE2 / FINALPLACE1 / FINALPLACE2
*/
private class PlaceListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.equals(hor) || button.equals(ver)) {
if (shipPlacePosition != null) {
String[] parts = shipPlacePosition.getName().split(" ");
if (button.equals(hor)) {
master.placeShip(Integer.valueOf(parts[0]),
Integer.valueOf(parts[1]), true);
} else {
master.placeShip(Integer.valueOf(parts[0]),
Integer.valueOf(parts[1]), false);
}
} else {
new JPopupDialog(null, "Placement error",
"Please choose a field to place the ship",
DISPLAYTIME, false);
}
} else {
if (shipPlacePosition != null
&& !shipPlacePosition.equals(button)) {
switchColor(shipPlacePosition);
}
String[] parts = button.getName().split(" ");
JButton select = buttonField
[Integer.valueOf(parts[0])][Integer.valueOf(parts[1])];
switchColor(select);
}
}
/**
* Method to switch the colour of a button.
*
* @param select specified Button
*/
private void switchColor(final JButton select) {
if (!select.getBorder().equals(SELECTED)) {
select.setBorder(SELECTED);
shipPlacePosition = select;
} else {
select.setBorder(new JButton().getBorder());
shipPlacePosition = null;
}
}
}
/**
* ActionListener for the State of the Game in which the Player has to shoot
* on the other Players board. SHOOT1 / SHOOT2
*/
private class ShootListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
JButton button = (JButton) e.getSource();
String[] name = button.getName().split(" ");
int x = Integer.parseInt(name[0]);
int y = Integer.parseInt(name[1]);
master.shoot(x, y);
}
}
/**
* ActionListener for the State of the game where the game is over and the
* game starts. START / END
*/
private class MenuListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
menuFrame.setVisible(false);
JButton target = (JButton) e.getSource();
switch (target.getText()) {
case "Start Game":
master.startGame();
setVisible(true);
break;
case "Exit":
System.exit(0);
break;
case "Start a new Game":
setVisible(true);
master.startGame();
break;
default:
break;
}
}
}
/**
* ActionListener for the GETNAME 1 / 2 - States.
*/
private class PlayerListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
notifyframe.setVisible(false);
master.setPlayerName(player.getText());
notifyframe.dispose();
}
}
/**
* ActionListener for the WIN 1 / 2 - States.
*/
private class WinListener implements ActionListener {
@Override
public final void actionPerformed(final ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.equals(endPlayer1)) {
updateGameField(master.getPlayer2(), false);
} else if (button.equals(endPlayer2)) {
updateGameField(master.getPlayer1(), false);
} else {
setInvisible();
east.removeAll();
menuFrame.setVisible(true);
menuFrame.toBack();
menuFrame.toFront();
}
}
}
}
|
Battleship/src/main/java/de/htwg/battleship/aview/gui/GUI.java
|
package de.htwg.battleship.aview.gui;
import static de.htwg.battleship.util.StatCollection.createMap;
import static de.htwg.battleship.util.StatCollection.fillMap;
import static de.htwg.battleship.util.StatCollection.heightLenght;
import de.htwg.battleship.controller.IMasterController;
import de.htwg.battleship.model.IPlayer;
import de.htwg.battleship.model.IShip;
import de.htwg.battleship.observer.IObserver;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import java.util.Set;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
/**
* Graphical User Interface for the Game
*
* @version 1.00
* @since 2014-12-20
*/
@SuppressWarnings("serial")
public final class GUI extends JFrame implements IObserver {
/**
* Constant that indicates how long the JPopupDialogs should be shown before
* they close automatically.
*/
private static final long DISPLAYTIME = 1000L;
/**
* width/height for the description labels
*/
private final int descriptionWidthHeight = 40;
/**
* space for yAxis
*/
private final int yAxisGap = 30;
/**
* space for xAxis
*/
private final int xAxisGap = 10;
/**
* height of the bottom label
*/
private final int bottomHeight = 50;
/**
* width of the east label
*/
private final int eastWidth = 100;
/**
* width of the mainframe
*/
private final int frameWidth = 1000;
/**
* height of the mainframe
*/
private final int frameHeight = 610;
/**
* Dimension for Buttons in the JLabel east
*/
private final Dimension eastButtons = new Dimension(90, 30);
/**
* Dimension for playername frame
*/
private final Dimension playerframe = new Dimension(300, 150);
/**
* Dimension for the menuFrame
*/
private final Dimension menuFrameSize = new Dimension(800, 500);
/**
* set Bound for playerframe button
*/
private final Rectangle playerframeButton = new Rectangle(75, 80, 150, 30);
/**
* set Bounds for playerframe label
*/
private final Rectangle playerframeLabel = new Rectangle(25, 5, 250, 30);
/**
* set Bounds for playerframe textfield
*/
private final Rectangle playerframeText = new Rectangle(25, 40, 250, 30);
/**
* set Bounds for menuframe startbutton
*/
private final Rectangle menuFrameStartbutton = new Rectangle(300, 240, 200, 50);
/**
* set Bounds for menuframe exitbutton
*/
private final Rectangle menuFrameExitbutton = new Rectangle(300, 310, 200, 50);
/**
* default Font
*/
private final Font font = new Font("Helvetica", Font.BOLD, 12);
/**
* Border for selected Field
*/
private final LineBorder selected = new LineBorder(Color.RED, 4);
/**
* JButton to start or later to restart the Game.
*/
private final JButton start = new JButton("Start Game");
/**
* JButton to exit the whole game right at the beginning or at the end.
*/
private final JButton exit = new JButton("Exit");
/**
* JButton to show the Gamefield of player1 after the Game
*/
private final JButton endPlayer1 = new JButton();
/**
* JButton to show the Gamefield of player2 after the Game
*/
private final JButton endPlayer2 = new JButton();
/**
* Button to place a ship in horizontal direction
*/
private final JButton hor = new JButton("horizontal");
/**
* Button to place a ship in vertical direction
*/
private final JButton ver = new JButton("vertical");
/**
* JButton[][] for the Field. Button named with: 'x + " " + y'
*/
private final JButton[][] buttonField
= new JButton[heightLenght][heightLenght];
/**
* default Background for mainframe
*/
private final ImageIcon background = new ImageIcon(getClass().getResource("background.jpg"));
/**
* default background for the menuframe
*/
private final ImageIcon backgroundMenu = new ImageIcon(getClass().getResource("background_menu.jpg"));
/**
* default ImageIcon for non-hitted fields
*/
private final ImageIcon wave = new ImageIcon(getClass().getResource("wave.jpg"));
/**
* ImageIcon for missed shots
*/
private final ImageIcon miss = new ImageIcon(getClass().getResource("miss.jpg"));
/**
* ImageIcon for ship placed fields
*/
private final ImageIcon ship = new ImageIcon(getClass().getResource("ship.jpg"));
/**
* ImageIcon for hitted fields with ship
*/
private final ImageIcon hit = new ImageIcon(getClass().getResource("ship_hit.jpg"));
/**
* ImageIcon for JLabels with invisible background
*/
private final ImageIcon invisible = new ImageIcon(getClass().getResource("invisible.png"));
/**
* To save the MasterController for all of the several UIs.
*/
private final IMasterController master;
/**
* Container which contains all object of the mainframe
*/
private final Container container;
/**
* JLabel for the center of the mainframe
*/
private JLabel center;
/**
* JLabel for the east side of the mainframe.
*/
private JLabel east;
/**
* JLabel for the x-Axis description
*/
private JLabel xAxis;
/**
* JLabel for the y-Axis description
*/
private JLabel yAxis;
/**
* JLabel to send out instructions
*/
private JLabel ausgabe;
/**
* JButton where the Ship should be placed.
*/
private JButton shipPlacePosition;
/**
* JDialog which has to be saved that the program can dispose them after its
* not in use anymore.
*/
private JDialog notifyframe;
/**
* JTextField where the player should input his name.
*/
private JTextField player;
/**
* JFrame for the menu
*/
private JFrame menuFrame;
/**
* Public Contructor to create a GUI.
*
* @param master MasterController which is the same for all UI
*/
public GUI(final IMasterController master) {
master.addObserver(this);
this.master = master;
//Initialize mainFrame
this.setTitle("Battleship");
this.setIconImage(new ImageIcon(getClass().getResource("frame_icon.jpg")).getImage());
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.container = new JLabel(background);
this.add(container);
//Initialize Menu
this.menuFrame();
//start Game
this.newGame();
}
/**
* Method build the menuframe
*/
private void menuFrame() {
this.menuFrame = new JFrame("Battleship");
this.menuFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
//build Buttons
this.start.setBounds(menuFrameStartbutton);
this.exit.setBounds(menuFrameExitbutton);
this.start.setIcon(new ImageIcon(getClass().getResource("menubutton_1.jpg")));
this.start.setRolloverIcon(new ImageIcon(getClass().getResource("menubutton_1_mouseover.jpg")));
this.start.setBorder(null);
this.exit.setIcon(new ImageIcon(getClass().getResource("menubutton_2.jpg")));
this.exit.setRolloverIcon(new ImageIcon(getClass().getResource("menubutton_2_mouseover.jpg")));
this.exit.setBorder(null);
this.start.addActionListener(new MenuListener());
this.exit.addActionListener(new MenuListener());
//Container setup
JLabel startContainer = new JLabel(backgroundMenu);
startContainer.setLayout(null);
startContainer.add(start);
startContainer.add(exit);
//Frame setup
this.menuFrame.add(startContainer);
this.menuFrame.setSize(menuFrameSize);
this.menuFrame.setResizable(false);
this.menuFrame.setLocationRelativeTo(null);
this.menuFrame.setIconImage(new ImageIcon(getClass().getResource("frame_icon.jpg")).getImage());
this.menuFrame.setVisible(true);
}
/**
* Method to initialize the GUI for the fields.
*/
public void newGame() {
//new Layout
container.setLayout(new BorderLayout(0, 0));
//panel for the left description
JLabel left = new JLabel();
left.setPreferredSize(new Dimension(descriptionWidthHeight,
frameHeight - bottomHeight - descriptionWidthHeight));
left.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
yAxis = new JLabel();
yAxis.setPreferredSize(new Dimension(descriptionWidthHeight,
frameHeight - bottomHeight - descriptionWidthHeight - yAxisGap));
yAxis.setLayout(new GridLayout(heightLenght, 1));
yAxis.setVerticalTextPosition(SwingConstants.CENTER);
left.add(yAxis);
container.add(left, BorderLayout.WEST);
//panel for top description
JLabel top = new JLabel();
top.setPreferredSize(new Dimension(frameWidth, descriptionWidthHeight));
top.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
xAxis = new JLabel();
xAxis.setLayout(new GridLayout(1, heightLenght));
xAxis.setPreferredSize(new Dimension(
frameWidth - descriptionWidthHeight - eastWidth - xAxisGap,
descriptionWidthHeight));
//panel for the place in the higher left corner
JLabel leftHigherCorner = new JLabel();
leftHigherCorner.setPreferredSize(new Dimension(descriptionWidthHeight, descriptionWidthHeight));
// adding components
top.add(leftHigherCorner);
top.add(xAxis);
container.add(top, BorderLayout.NORTH);
//build gameField
center = new JLabel();
buildGameField();
container.add(center, BorderLayout.CENTER);
//bottom
JLabel bottom = new JLabel();
bottom.setPreferredSize(new Dimension(frameWidth, bottomHeight));
bottom.setLayout(new FlowLayout());
ausgabe = new JLabel();
ausgabe.setHorizontalTextPosition(SwingConstants.CENTER);
ausgabe.setVerticalTextPosition(SwingConstants.CENTER);
ausgabe.setPreferredSize(new Dimension(frameWidth, bottomHeight));
ausgabe.setHorizontalAlignment(SwingConstants.CENTER);
ausgabe.setFont(this.font);
ausgabe.setForeground(Color.WHITE);
ausgabe.setIcon(new ImageIcon(getClass().getResource("invisible_ausgabe.png")));
bottom.add(ausgabe);
this.setSize(frameWidth, frameHeight);
this.setLocationRelativeTo(null);
container.add(bottom, BorderLayout.SOUTH);
//right
east = new JLabel();
east.setPreferredSize(new Dimension(eastWidth, 1));
east.setLayout(new FlowLayout(FlowLayout.LEFT));
container.add(east, BorderLayout.EAST);
}
/**
* Utility-Method to Build the main Gamefield
*/
private void buildGameField() {
GridLayout gl = new GridLayout(heightLenght, heightLenght);
center.setLayout(gl);
for (int y = 0; y < heightLenght; y++) {
JLabel xLabel = new JLabel();
JLabel yLabel = new JLabel();
xLabel.setHorizontalTextPosition(SwingConstants.CENTER);
xLabel.setVerticalTextPosition(SwingConstants.CENTER);
yLabel.setHorizontalTextPosition(SwingConstants.CENTER);
yLabel.setVerticalTextPosition(SwingConstants.CENTER);
xLabel.setForeground(Color.WHITE);
yLabel.setForeground(Color.WHITE);
xLabel.setText("" + (y + 1));
yLabel.setText("" + (char) ('A' + y));
yAxis.add(yLabel);
xAxis.add(xLabel);
for (int x = 0; x < heightLenght; x++) {
String name = x + " " + y;
this.buttonField[x][y] = new JButton();
this.buttonField[x][y].setName(name);
this.buttonField[x][y].setIcon(wave);
center.add(buttonField[x][y]);
}
}
}
/**
* Utility-Method to create a JDialog where the user should insert his name.
*
* @param playernumber
*/
private void getPlayername(final int playernumber) {
PlayerListener pl = new PlayerListener();
JLabel icon = new JLabel(background);
icon.setPreferredSize(playerframe);
JLabel text = new JLabel(invisible);
text.setHorizontalTextPosition(SwingConstants.CENTER);
text.setForeground(Color.WHITE);
text.setText("please insert playername " + playernumber);
text.setBounds(playerframeLabel);
player = new JTextField();
player.setBorder(new LineBorder(Color.BLACK, 1));
player.setFont(this.font);
player.setBounds(playerframeText);
JButton submit = new JButton("OK");
submit.setIcon(new ImageIcon(getClass().getResource("playername_button.jpg")));
submit.setRolloverIcon(new ImageIcon(getClass().getResource("playername_button_mouseover.jpg")));
submit.setBorder(null);
submit.setBounds(playerframeButton);
submit.addActionListener(pl);
notifyframe = new JDialog();
notifyframe.add(icon);
notifyframe.setModal(true);
notifyframe.setSize(playerframe);
icon.setLayout(null);
icon.add(text);
icon.add(player);
icon.add(submit);
notifyframe.setResizable(false);
notifyframe.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
notifyframe.setLocationRelativeTo(getParent());
notifyframe.getRootPane().setDefaultButton(submit);
notifyframe.setVisible(true);
}
/**
* Utility-Method to add the 'place'-Button and a ComboBox to the main
* frame.
*/
private void placeShip() {
this.setVisible(false);
east.remove(hor);
east.remove(ver);
hor.addActionListener(new PlaceListener());
ver.addActionListener(new PlaceListener());
resetPlaceButton();
this.ver.setPreferredSize(eastButtons);
this.ver.setIcon(new ImageIcon(getClass().getResource("vertical.jpg")));
this.ver.setRolloverIcon(new ImageIcon(getClass().getResource("vertical_mouseover.jpg")));
this.ver.setBorder(null);
this.hor.setPreferredSize(eastButtons);
this.hor.setIcon(new ImageIcon(getClass().getResource("horizontal.jpg")));
this.hor.setRolloverIcon(new ImageIcon(getClass().getResource("horizontal_mouseover.jpg")));
this.hor.setBorder(null);
east.add(hor);
east.add(ver);
this.setVisible(true);
}
/**
* Utility-Method to update the image-icons of the gamefield buttons
*
* @param player current player
* @param hideShip boolean
*/
private void updateGameField(IPlayer player, boolean hideShips) {
IShip[] shipList = player.getOwnBoard().getShipList();
Map<Integer, Set<Integer>> map = createMap();
fillMap(shipList, map, player.getOwnBoard().getShips());
for (int y = 0; y < heightLenght; y++) {
for (int x = 0; x < heightLenght; x++) {
boolean isShip = false;
this.buttonField[x][y].setBorder(new JButton().getBorder());
for (Integer value : map.get(y)) {
if (value == x) {
if (player.getOwnBoard().isHit(x, y)) {
this.buttonField[x][y].setIcon(hit);
} else {
if (hideShips) {
this.buttonField[x][y].setIcon(wave);
} else {
this.buttonField[x][y].setIcon(ship);
}
}
isShip = true;
}
}
if (!isShip) {
if (player.getOwnBoard().isHit(x, y)) {
this.buttonField[x][y].setIcon(miss);
} else {
this.buttonField[x][y].setIcon(wave);
}
}
}
}
}
/**
* Utility-Method to reset the selected button in the place states.
*/
private void resetPlaceButton() {
if (shipPlacePosition != null) {
shipPlacePosition.setBorder(new JButton().getBorder());
shipPlacePosition = null;
}
}
/**
* Utility-Method to show the Gamefield after the Game
*/
private void endGame() {
this.setVisible(false);
for (JButton[] buttonArray : buttonField) {
for (JButton button : buttonArray) {
removeListener(button);
}
}
this.endPlayer1.setPreferredSize(eastButtons);
this.endPlayer2.setPreferredSize(eastButtons);
this.endPlayer1.setBorder(null);
this.endPlayer2.setBorder(null);
this.endPlayer1.setIcon(new ImageIcon(getClass().getResource("end_playername.jpg")));
this.endPlayer2.setIcon(new ImageIcon(getClass().getResource("end_playername.jpg")));
this.endPlayer1.setRolloverIcon(new ImageIcon(getClass().getResource("end_playername_mouseover.jpg")));
this.endPlayer2.setRolloverIcon(new ImageIcon(getClass().getResource("end_playername_mouseover.jpg")));
this.endPlayer1.setVerticalTextPosition(SwingConstants.CENTER);
this.endPlayer2.setVerticalTextPosition(SwingConstants.CENTER);
this.endPlayer1.setHorizontalTextPosition(SwingConstants.CENTER);
this.endPlayer2.setHorizontalTextPosition(SwingConstants.CENTER);
this.endPlayer1.setText(master.getPlayer1().getName());
this.endPlayer2.setText(master.getPlayer2().getName());
this.endPlayer1.setFont(this.font);
this.endPlayer2.setFont(this.font);
this.endPlayer1.setForeground(Color.WHITE);
this.endPlayer2.setForeground(Color.WHITE);
this.endPlayer1.addActionListener(new WinListener());
this.endPlayer2.addActionListener(new WinListener());
JButton finish = new JButton();
finish.setBorder(null);
finish.setPreferredSize(eastButtons);
finish.setIcon(new ImageIcon(getClass().getResource("finish.jpg")));
finish.setRolloverIcon(new ImageIcon(getClass().getResource("finish_mouseover.jpg")));
finish.addActionListener(new WinListener());
east.add(this.endPlayer1);
east.add(this.endPlayer2);
east.add(finish);
this.setVisible(true);
}
/**
* Utility-Method to set the mainframe invisible
*/
private void setInvisible() {
this.setVisible(false);
}
@Override
public void update() {
switch (master.getCurrentState()) {
case START:
break;
case GETNAME1:
menuFrame.dispose();
getPlayername(1);
break;
case GETNAME2:
notifyframe.dispose();
getPlayername(2);
break;
case PLACE1:
notifyframe.dispose();
resetPlaceButton();
activateListener(new PlaceListener());
updateGameField(master.getPlayer1(), false);
placeShip();
ausgabe.setText(master.getPlayer1().getName()
+ " now place the ship with the length of "
+ (master.getPlayer1().getOwnBoard().getShips() + 2));
break;
case PLACE2:
resetPlaceButton();
activateListener(new PlaceListener());
updateGameField(master.getPlayer2(), false);
placeShip();
ausgabe.setText(master.getPlayer2().getName()
+ " now place the ship with the length of "
+ (master.getPlayer2().getOwnBoard().getShips() + 2));
break;
case FINALPLACE1:
updateGameField(master.getPlayer1(), false);
resetPlaceButton();
break;
case FINALPLACE2:
updateGameField(master.getPlayer2(), false);
resetPlaceButton();
break;
case PLACEERR:
new JPopupDialog(this, "Placement error",
"Cannot place a ship there due to a collision or "
+ "the ship is out of the field!",
DISPLAYTIME, false);
break;
case SHOOT1:
this.setVisible(false);
east.remove(hor);
east.remove(ver);
this.setVisible(true);
activateListener(new ShootListener());
updateGameField(master.getPlayer2(), true);
ausgabe.setText(master.getPlayer1().getName()
+ " is now at the turn to shoot");
break;
case SHOOT2:
activateListener(new ShootListener());
updateGameField(master.getPlayer1(), true);
ausgabe.setText(master.getPlayer2().getName()
+ " is now at the turn to shoot");
break;
case HIT:
new JPopupDialog(this, "Shot Result",
"Your shot was a Hit!!", DISPLAYTIME, false);
break;
case MISS:
new JPopupDialog(this, "Shot Result",
"Your shot was a Miss!!", DISPLAYTIME, false);
break;
case WIN1:
updateGameField(master.getPlayer2(), false);
String msg = master.getPlayer1().getName() + " has won!!";
ausgabe.setText(msg);
new JPopupDialog(this, "Winner!", msg,
DISPLAYTIME, false);
break;
case WIN2:
updateGameField(master.getPlayer1(), false);
msg = master.getPlayer2().getName() + " has won!!";
ausgabe.setText(msg);
new JPopupDialog(this, "Winner!", msg,
DISPLAYTIME, false);
break;
case END:
endGame();
break;
case WRONGINPUT:
// isn't needed in the GUI, help-state for a UI where you
// can give input at the false states
break;
default:
break;
}
}
/**
* Method to activate a new Action Listener to the JButton[][]-Matrix. uses
* the removeListener-Method
*
* @param newListener the new Listener of the button matrix
*/
private void activateListener(final ActionListener newListener) {
for (JButton[] buttonArray : buttonField) {
for (JButton button : buttonArray) {
removeListener(button);
button.addActionListener(newListener);
}
}
}
/**
* Method which removes all Listener from a button.
*
* @param button specified button
*/
private void removeListener(final JButton button) {
if (button == null) {
return;
}
ActionListener[] actionList = button.getActionListeners();
for (ActionListener acLst : actionList) {
button.removeActionListener(acLst);
}
}
/**
* ActionListener for the State of the Game in which the Player has to set
* his Ships on the field. PLACE1 / PLACE2 / FINALPLACE1 / FINALPLACE2
*/
private class PlaceListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.equals(hor) || button.equals(ver)) {
if (shipPlacePosition != null) {
String[] parts = shipPlacePosition.getName().split(" ");
if (button.equals(hor)) {
master.placeShip(Integer.valueOf(parts[0]),
Integer.valueOf(parts[1]), true);
} else {
master.placeShip(Integer.valueOf(parts[0]),
Integer.valueOf(parts[1]), false);
}
} else {
new JPopupDialog(null, "Placement error",
"Please choose a field to place the ship",
DISPLAYTIME, false);
}
} else {
if (shipPlacePosition != null && !shipPlacePosition.equals(button)) {
switchColor(shipPlacePosition);
}
String[] parts = button.getName().split(" ");
JButton select = buttonField[Integer.valueOf(parts[0])][Integer.valueOf(parts[1])];
switchColor(select);
}
}
/**
* Method to switch the colour of a button.
*
* @param select specified Button
*/
private void switchColor(final JButton select) {
if (!select.getBorder().equals(selected)) {
select.setBorder(selected);
shipPlacePosition = select;
} else {
select.setBorder(new JButton().getBorder());
shipPlacePosition = null;
}
}
}
/**
* ActionListener for the State of the Game in which the Player has to shoot
* on the other Players board. SHOOT1 / SHOOT2
*/
private class ShootListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
JButton button = (JButton) e.getSource();
String[] name = button.getName().split(" ");
int x = Integer.parseInt(name[0]);
int y = Integer.parseInt(name[1]);
master.shoot(x, y);
}
}
/**
* ActionListener for the State of the game where the game is over and the
* game starts. START / END
*/
private class MenuListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
menuFrame.setVisible(false);
JButton target = (JButton) e.getSource();
switch (target.getText()) {
case "Start Game":
master.startGame();
setVisible(true);
break;
case "Exit":
System.exit(0);
break;
case "Start a new Game":
setVisible(true);
master.startGame();
break;
default:
break;
}
}
}
/**
* ActionListener for the GETNAME 1 / 2 - States.
*/
private class PlayerListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
notifyframe.setVisible(false);
master.setPlayerName(player.getText());
notifyframe.dispose();
}
}
private class WinListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.equals(endPlayer1)) {
updateGameField(master.getPlayer2(), false);
} else if (button.equals(endPlayer2)) {
updateGameField(master.getPlayer1(), false);
} else {
setInvisible();
east.removeAll();
menuFrame.setVisible(true);
menuFrame.toBack();
menuFrame.toFront();
}
}
}
}
|
refactored constants and formated code
|
Battleship/src/main/java/de/htwg/battleship/aview/gui/GUI.java
|
refactored constants and formated code
|
|
Java
|
bsd-3-clause
|
4f7d322f693a5e77161001dccaf54d258075bdfd
| 0
|
Clashsoft/Dyvil,Clashsoft/Dyvil
|
package dyvil.tools.compiler.ast.access;
import dyvil.tools.compiler.ast.context.IContext;
import dyvil.tools.compiler.ast.expression.IValue;
import dyvil.tools.compiler.ast.parameter.IArguments;
import dyvil.tools.compiler.config.Formatting;
import dyvil.tools.compiler.transform.Names;
import dyvil.tools.compiler.transform.SideEffectHelper;
import dyvil.tools.parsing.Name;
import dyvil.tools.parsing.marker.MarkerList;
import dyvil.tools.parsing.position.ICodePosition;
public class SubscriptAccess extends AbstractCall
{
public SubscriptAccess(ICodePosition position)
{
this.position = position;
}
public SubscriptAccess(ICodePosition position, IValue instance)
{
this.position = position;
this.receiver = instance;
}
public SubscriptAccess(ICodePosition position, IValue instance, IArguments arguments)
{
this.position = position;
this.receiver = instance;
this.arguments = arguments;
}
@Override
public int valueTag()
{
return SUBSCRIPT_GET;
}
@Override
public Name getName()
{
return Names.subscript;
}
@Override
protected Name getReferenceName()
{
return Names.subscript_$amp;
}
@Override
public IValue toAssignment(IValue rhs, ICodePosition position)
{
return new SubscriptAssignment(this.position.to(position), this.receiver, this.arguments, rhs);
}
@Override
public IValue toCompoundAssignment(IValue rhs, ICodePosition position, MarkerList markers, IContext context,
SideEffectHelper helper)
{
// x[y...] op= z
// -> x[y...] = x[y...].op(z)
// -> x.subscript_=(y..., x.subscript(y...).op(z))
final IValue subscriptReceiver = helper.processValue(this.receiver);
final IArguments subscriptArguments = helper.processArguments(this.arguments);
this.receiver = subscriptReceiver;
this.arguments = subscriptArguments;
return new SubscriptAssignment(position, subscriptReceiver, subscriptArguments, rhs)
.resolveCall(markers, context, true);
}
@Override
public void toString(String prefix, StringBuilder buffer)
{
if (this.receiver != null)
{
this.receiver.toString(prefix, buffer);
}
Formatting.appendSeparator(buffer, "method.subscript.open_bracket", '[');
int count = this.arguments.size();
if (count > 0)
{
this.arguments.getValue(0, null).toString(prefix, buffer);
for (int i = 1; i < count; i++)
{
Formatting.appendSeparator(buffer, "method.subscript.separator", ',');
this.arguments.getValue(i, null).toString(prefix, buffer);
}
}
if (Formatting.getBoolean("method.subscript.close_bracket.space_before"))
{
buffer.append(' ');
}
buffer.append(']');
}
}
|
src/compiler/dyvil/tools/compiler/ast/access/SubscriptAccess.java
|
package dyvil.tools.compiler.ast.access;
import dyvil.tools.compiler.ast.context.IContext;
import dyvil.tools.compiler.ast.expression.ArrayExpr;
import dyvil.tools.compiler.ast.expression.IValue;
import dyvil.tools.compiler.ast.parameter.IArguments;
import dyvil.tools.compiler.config.Formatting;
import dyvil.tools.compiler.transform.Names;
import dyvil.tools.compiler.transform.SideEffectHelper;
import dyvil.tools.parsing.Name;
import dyvil.tools.parsing.marker.MarkerList;
import dyvil.tools.parsing.position.ICodePosition;
public class SubscriptAccess extends AbstractCall
{
public SubscriptAccess(ICodePosition position)
{
this.position = position;
}
public SubscriptAccess(ICodePosition position, IValue instance)
{
this.position = position;
this.receiver = instance;
}
public SubscriptAccess(ICodePosition position, IValue instance, IArguments arguments)
{
this.position = position;
this.receiver = instance;
this.arguments = arguments;
}
@Override
public int valueTag()
{
return SUBSCRIPT_GET;
}
@Override
public Name getName()
{
return Names.subscript;
}
@Override
protected Name getReferenceName()
{
return Names.subscript_$amp;
}
@Override
public IValue toAssignment(IValue rhs, ICodePosition position)
{
return new SubscriptAssignment(this.position.to(position), this.receiver, this.arguments, rhs);
}
@Override
public IValue toCompoundAssignment(IValue rhs, ICodePosition position, MarkerList markers, IContext context,
SideEffectHelper helper)
{
// x[y...] op= z
// -> x[y...] = x[y...].op(z)
// -> x.subscript_=(y..., x.subscript(y...).op(z))
final IValue subscriptReceiver = helper.processValue(this.receiver);
final IArguments subscriptArguments = helper.processArguments(this.arguments);
this.receiver = subscriptReceiver;
this.arguments = subscriptArguments;
return new SubscriptAssignment(position, subscriptReceiver, subscriptArguments, rhs)
.resolveCall(markers, context, true);
}
@Override
public IValue resolve(MarkerList markers, IContext context)
{
if (this.receiver instanceof ICall)
// false if receiver == null
{
ICall call = (ICall) this.receiver;
// Resolve Receiver if necessary
call.resolveReceiver(markers, context);
call.resolveArguments(markers, context);
IArguments oldArgs = call.getArguments();
ArrayExpr array = new ArrayExpr(this.position, this.arguments.size());
for (IValue v : this.arguments)
{
array.addValue(v);
}
call.setArguments(oldArgs.withLastValue(Names.subscript, array));
IValue resolvedCall = call.resolveCall(markers, context, false);
if (resolvedCall != null)
{
return resolvedCall;
}
// Revert
call.setArguments(oldArgs);
this.receiver = call.resolveCall(markers, context, true);
return this.resolveCall(markers, context, true);
}
return super.resolve(markers, context);
}
@Override
public void toString(String prefix, StringBuilder buffer)
{
if (this.receiver != null)
{
this.receiver.toString(prefix, buffer);
}
Formatting.appendSeparator(buffer, "method.subscript.open_bracket", '[');
int count = this.arguments.size();
if (count > 0)
{
this.arguments.getValue(0, null).toString(prefix, buffer);
for (int i = 1; i < count; i++)
{
Formatting.appendSeparator(buffer, "method.subscript.separator", ',');
this.arguments.getValue(i, null).toString(prefix, buffer);
}
}
if (Formatting.getBoolean("method.subscript.close_bracket.space_before"))
{
buffer.append(' ');
}
buffer.append(']');
}
}
|
Remove Subscript Access Special Case
comp: Removed a special case where a Subscript Access would be
converted to an Array automatically.
|
src/compiler/dyvil/tools/compiler/ast/access/SubscriptAccess.java
|
Remove Subscript Access Special Case
|
|
Java
|
mit
|
5213e09f343d64ff9f64bbd54998fa7b37c881b7
| 0
|
thandomy/foodie
|
app/src/main/java/com/team3009/foodie/Profile3.java
|
package com.team3009.foodie;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.braintreepayments.api.BraintreeFragment;
import com.braintreepayments.api.dropin.DropInActivity;
import com.braintreepayments.api.dropin.DropInRequest;
import com.braintreepayments.api.dropin.DropInResult;
import com.braintreepayments.api.exceptions.InvalidArgumentException;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.util.Map;
/**
* A simple {@link Fragment} subclass.
*/
public class Profile3 extends Fragment {
String key,amount;
private Button mOrder;
private TextView mIngredients, mUserName,mTitle;
private ImageView mProfilepic;
// [START define_database_reference]
private DatabaseReference mDatabase;
private DatabaseReference mCustomer;
// [END define_database_reference]
BraintreeFragment mBraintreeFragment;
String mAuthorization = "sandbox_bc77j8r3_n27kq9hxz3s2wqqt";
final int REQUEST_CODE = 1;
String token = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiJjOTM3Yzc3ZmIwMzc3MDIyZjI4ZjJlYjkwMWQxMTI1NGJlZGNiNmYxMDZhMDJmMWU4NTAyZTkxYTZhMWU0YTc4fGNyZWF0ZWRfYXQ9MjAxNy0xMC0xNVQxMzoxODowNy4yNjIwNTkwNjErMDAwMFx1MDAyNm1lcmNoYW50X2lkPTM0OHBrOWNnZjNiZ3l3MmJcdTAwMjZwdWJsaWNfa2V5PTJuMjQ3ZHY4OWJxOXZtcHIiLCJjb25maWdVcmwiOiJodHRwczovL2FwaS5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tOjQ0My9tZXJjaGFudHMvMzQ4cGs5Y2dmM2JneXcyYi9jbGllbnRfYXBpL3YxL2NvbmZpZ3VyYXRpb24iLCJjaGFsbGVuZ2VzIjpbXSwiZW52aXJvbm1lbnQiOiJzYW5kYm94IiwiY2xpZW50QXBpVXJsIjoiaHR0cHM6Ly9hcGkuc2FuZGJveC5icmFpbnRyZWVnYXRld2F5LmNvbTo0NDMvbWVyY2hhbnRzLzM0OHBrOWNnZjNiZ3l3MmIvY2xpZW50X2FwaSIsImFzc2V0c1VybCI6Imh0dHBzOi8vYXNzZXRzLmJyYWludHJlZWdhdGV3YXkuY29tIiwiYXV0aFVybCI6Imh0dHBzOi8vYXV0aC52ZW5tby5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tIiwiYW5hbHl0aWNzIjp7InVybCI6Imh0dHBzOi8vY2xpZW50LWFuYWx5dGljcy5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tLzM0OHBrOWNnZjNiZ3l3MmIifSwidGhyZWVEU2VjdXJlRW5hYmxlZCI6dHJ1ZSwicGF5cGFsRW5hYmxlZCI6dHJ1ZSwicGF5cGFsIjp7ImRpc3BsYXlOYW1lIjoiQWNtZSBXaWRnZXRzLCBMdGQuIChTYW5kYm94KSIsImNsaWVudElkIjpudWxsLCJwcml2YWN5VXJsIjoiaHR0cDovL2V4YW1wbGUuY29tL3BwIiwidXNlckFncmVlbWVudFVybCI6Imh0dHA6Ly9leGFtcGxlLmNvbS90b3MiLCJiYXNlVXJsIjoiaHR0cHM6Ly9hc3NldHMuYnJhaW50cmVlZ2F0ZXdheS5jb20iLCJhc3NldHNVcmwiOiJodHRwczovL2NoZWNrb3V0LnBheXBhbC5jb20iLCJkaXJlY3RCYXNlVXJsIjpudWxsLCJhbGxvd0h0dHAiOnRydWUsImVudmlyb25tZW50Tm9OZXR3b3JrIjp0cnVlLCJlbnZpcm9ubWVudCI6Im9mZmxpbmUiLCJ1bnZldHRlZE1lcmNoYW50IjpmYWxzZSwiYnJhaW50cmVlQ2xpZW50SWQiOiJtYXN0ZXJjbGllbnQzIiwiYmlsbGluZ0FncmVlbWVudHNFbmFibGVkIjp0cnVlLCJtZXJjaGFudEFjY291bnRJZCI6ImFjbWV3aWRnZXRzbHRkc2FuZGJveCIsImN1cnJlbmN5SXNvQ29kZSI6IlVTRCJ9LCJtZXJjaGFudElkIjoiMzQ4cGs5Y2dmM2JneXcyYiIsInZlbm1vIjoib2ZmIn0=";
public Profile3() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_profile2, container, false);
try {
mBraintreeFragment = BraintreeFragment.newInstance(getActivity(),mAuthorization);
// mBraintreeFragment is ready to use!
} catch (InvalidArgumentException e) {
// There was an issue with your authorization string.
}
String key = getArguments().getString("key");
String userId = getArguments().getString("userId");
amount = getArguments().getString("amount");
Toast.makeText(getActivity(),userId,Toast.LENGTH_SHORT).show();
mDatabase = FirebaseDatabase.getInstance().getReference("Serving").child(key);
mCustomer= FirebaseDatabase.getInstance().getReference("Users").child(userId);
mCustomer.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("name") != null){
((TextView) view.findViewById(R.id.userName)).setText(map.get("name").toString());
}
if(map.get("profileImageUrl")!=null) {
Picasso.with(getActivity())
.load(map.get("profileImageUrl").toString())
.error(R.drawable.common_google_signin_btn_text_light_disabled)
.into((ImageView) view.findViewById(R.id.profilePic));
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
ValueEventListener valueEventListener = mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Serve model = dataSnapshot.getValue(Serve.class);
//((TextView) view.findViewById(R.id.foodDesc)).setText(model.description);
((TextView) view.findViewById(R.id.title)).setText(model.title);
Picasso.with(getActivity())
.load(model.downloadUrl)
.error(R.drawable.common_google_signin_btn_text_light_disabled)
.into((ImageView) view.findViewById(R.id.userPic));
((TextView) view.findViewById(R.id.ingredientslist)).setText(model.description);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
view.findViewById(R.id.profileTab).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Life Sucks",Toast.LENGTH_SHORT).show();
profileTab ProfileTab = new profileTab();
Bundle args = new Bundle();
args.putString("userId",getArguments().getString("userId"));
ProfileTab.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(((ViewGroup)(getView().getParent())).getId(), ProfileTab,ProfileTab.getTag()).addToBackStack(null)
.commit();
}
});
mOrder = (Button) view.findViewById(R.id.Order);
mOrder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBraintreeSubmit(v);
}
});
return view;
}
public void onBraintreeSubmit(View v) {
DropInRequest dropInRequest = new DropInRequest()
.clientToken(token/*clientToken*/).amount(amount);
startActivityForResult(dropInRequest.getIntent(getActivity()), REQUEST_CODE);
removeFragment();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
DropInResult result = data.getParcelableExtra(DropInResult.EXTRA_DROP_IN_RESULT);
//CardBuilder cardBuilder = new CardBuilder().
//Card.tokenize(mBraintreeFragment, cardBuilder);
// use the result to update your UI and send the payment method nonce to your server
} else if (resultCode == Activity.RESULT_CANCELED) {
// the user canceled
} else {
// handle errors here, an exception may be available in
Exception error = (Exception) data.getSerializableExtra(DropInActivity.EXTRA_ERROR);
}
}
}
public void removeFragment(){
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.remove(this);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
ft.commit();
}
}
|
Delete Profile3.java
|
app/src/main/java/com/team3009/foodie/Profile3.java
|
Delete Profile3.java
|
||
Java
|
mit
|
e3a8f02d48a4a98fb6b05c183a41546a536ac66f
| 0
|
c2nes/ircbot
|
package com.brewtab.ircbot;
import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import com.brewtab.irc.IRCChannel;
import com.brewtab.irc.IRCClient;
import com.brewtab.irc.IRCMessageHandler;
import com.brewtab.irc.messages.IRCMessage;
import com.brewtab.irc.messages.filter.IRCMessageFilters;
import com.brewtab.ircbot.applets.BashApplet;
import com.brewtab.ircbot.applets.CalcApplet;
import com.brewtab.ircbot.applets.EightBallApplet;
import com.brewtab.ircbot.applets.GoogleSuggestsApplet;
import com.brewtab.ircbot.applets.GroupHugApplet;
import com.brewtab.ircbot.applets.SpellApplet;
import com.brewtab.ircbot.applets.StatsApplet;
import com.brewtab.ircbot.applets.TextsFromLastNightApplet;
import com.brewtab.ircbot.applets.TumblrApplet;
import com.brewtab.ircbot.applets.UrbanDictionaryApplet;
import com.brewtab.ircbot.applets.WeatherApplet;
import com.brewtab.ircbot.applets.WikiApplet;
import com.brewtab.ircbot.applets.WolframAlphaApplet;
import com.brewtab.ircbot.util.SQLProperties;
import com.brewtab.irclog.IRCLogger;
public class Bot {
public static void main(String[] args) throws Exception {
InetSocketAddress addr = new InetSocketAddress("irc.brewtab.com", 6667);
/* Create IRC client */
IRCClient client = new IRCClient(addr);
/* Create logger */
Class.forName("org.h2.Driver");
Connection connection = DriverManager.getConnection("jdbc:h2:brewtab", "sa", "");
IRCLogger logger = new IRCLogger(connection);
/* Create channel listener */
BotChannelListener botChannelListener = new BotChannelListener();
/* Simple key-value store for persistent settings/properties */
SQLProperties properties = new SQLProperties(connection);
/* Register applets with the bot */
botChannelListener.registerApplet(new GroupHugApplet(), "gh", "grouphug");
botChannelListener.registerApplet(new TextsFromLastNightApplet(), "tfln", "texts");
botChannelListener.registerApplet(new CalcApplet(), "m", "math", "calc");
botChannelListener.registerApplet(new WeatherApplet(properties), "w", "weather");
botChannelListener.registerApplet(new StatsApplet(logger), "last", "bored", "tired");
botChannelListener.registerApplet(new BashApplet(), "bash");
botChannelListener.registerApplet(new WikiApplet(), "wiki");
botChannelListener.registerApplet(new TumblrApplet(), "tumblr");
botChannelListener.registerApplet(new WolframAlphaApplet("XXXX"), "a", "alpha");
botChannelListener.registerApplet(new SpellApplet(), "sp", "spell");
botChannelListener.registerApplet(new EightBallApplet(), "8ball");
botChannelListener.registerApplet(new UrbanDictionaryApplet(), "urban");
botChannelListener.registerApplet(new GoogleSuggestsApplet(), "gs");
/* Listener for ++ and -- */
PlusPlus plusPlus = new PlusPlus(properties);
/* Will block until connection process is complete */
client.connect("testbot", "bot", "kitimat", "Mr. Bot");
/*
* We can add a message handler for the client to print all messages
* from the server if we needed to for debugging
*/
client.addHandler(IRCMessageFilters.PASS, new IRCMessageHandler() {
@Override
public void handleMessage(IRCMessage message) {
System.out.println("root>>> " + message.toString().trim());
}
});
/*
* Join a channel. Channels can also be directly instantiated and
* separately joined
*/
IRCChannel c = client.join("#bot");
/* We add a handler for channel messages */
c.addListener(botChannelListener);
c.addListener(plusPlus);
c.addListener(logger);
/* Wait for client object's connection to exit and close */
client.getConnection().awaitClosed();
System.out.println("Exiting");
}
}
|
brewtab-ircbot/src/main/java/com/brewtab/ircbot/Bot.java
|
package com.brewtab.ircbot;
import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import com.brewtab.irc.IRCChannel;
import com.brewtab.irc.IRCClient;
import com.brewtab.irc.IRCMessageHandler;
import com.brewtab.irc.messages.IRCMessage;
import com.brewtab.irc.messages.filter.IRCMessageFilters;
import com.brewtab.ircbot.applets.BashApplet;
import com.brewtab.ircbot.applets.CalcApplet;
import com.brewtab.ircbot.applets.EightBallApplet;
import com.brewtab.ircbot.applets.GoogleSuggestsApplet;
import com.brewtab.ircbot.applets.GroupHugApplet;
import com.brewtab.ircbot.applets.SpellApplet;
import com.brewtab.ircbot.applets.StatsApplet;
import com.brewtab.ircbot.applets.TestProperties;
import com.brewtab.ircbot.applets.TextsFromLastNightApplet;
import com.brewtab.ircbot.applets.TumblrApplet;
import com.brewtab.ircbot.applets.UrbanDictionaryApplet;
import com.brewtab.ircbot.applets.WeatherApplet;
import com.brewtab.ircbot.applets.WikiApplet;
import com.brewtab.ircbot.applets.WolframAlphaApplet;
import com.brewtab.ircbot.util.SQLProperties;
import com.brewtab.irclog.IRCLogger;
public class Bot {
public static void main(String[] args) throws Exception {
InetSocketAddress addr = new InetSocketAddress("irc.brewtab.com", 6667);
/* Create IRC client */
IRCClient client = new IRCClient(addr);
/* Create logger */
Class.forName("org.h2.Driver");
Connection connection = DriverManager.getConnection("jdbc:h2:brewtab", "sa", "");
IRCLogger logger = new IRCLogger(connection);
/* Create channel listener */
BotChannelListener botChannelListener = new BotChannelListener();
/* Simple key-value store for persistent settings/properties */
SQLProperties properties = new SQLProperties(connection);
/* Register applets with the bot */
botChannelListener.registerApplet(new GroupHugApplet(), "gh", "grouphug");
botChannelListener.registerApplet(new TextsFromLastNightApplet(), "tfln", "texts");
botChannelListener.registerApplet(new CalcApplet(), "m", "math", "calc");
botChannelListener.registerApplet(new WeatherApplet(properties), "w", "weather");
botChannelListener.registerApplet(new StatsApplet(logger), "last", "bored", "tired");
botChannelListener.registerApplet(new BashApplet(), "bash");
botChannelListener.registerApplet(new WikiApplet(), "wiki");
botChannelListener.registerApplet(new TumblrApplet(), "tumblr");
botChannelListener.registerApplet(new WolframAlphaApplet("XXXX"), "a", "alpha");
botChannelListener.registerApplet(new SpellApplet(), "sp", "spell");
botChannelListener.registerApplet(new EightBallApplet(), "8ball");
botChannelListener.registerApplet(new UrbanDictionaryApplet(), "urban");
botChannelListener.registerApplet(new GoogleSuggestsApplet(), "gs");
botChannelListener.registerApplet(new TestProperties(properties), "get", "set");
/* Listener for ++ and -- */
PlusPlus plusPlus = new PlusPlus(properties);
/* Will block until connection process is complete */
client.connect("testbot", "bot", "kitimat", "Mr. Bot");
/*
* We can add a message handler for the client to print all messages
* from the server if we needed to for debugging
*/
client.addHandler(IRCMessageFilters.PASS, new IRCMessageHandler() {
@Override
public void handleMessage(IRCMessage message) {
System.out.println("root>>> " + message.toString().trim());
}
});
/*
* Join a channel. Channels can also be directly instantiated and
* separately joined
*/
IRCChannel c = client.join("#bot");
/* We add a handler for channel messages */
c.addListener(botChannelListener);
c.addListener(plusPlus);
c.addListener(logger);
/* Wait for client object's connection to exit and close */
client.getConnection().awaitClosed();
System.out.println("Exiting");
}
}
|
Remove testing code
|
brewtab-ircbot/src/main/java/com/brewtab/ircbot/Bot.java
|
Remove testing code
|
|
Java
|
mit
|
c69002905434b2cae9cdef40f068eedcfc96ca1a
| 0
|
UCSB-CS56-W14/W14-lab05
|
package edu.ucsb.cs56.w14.lab05.alecharrell;
public class Boxer {
private int SSN; // SSN: Social security number, Boxer's unique
//identification number
private String name;//stores the last name of the Boxerr
/**
Two-arg constructor
@param SSN social security number of boxer, e.g. 123456789
@param name last name of the boxer, e.g. "Foreman"
*/
public Boxer(int SSN, String name) {
this.SSN = SSN;
this.name = name;
}
/**
Getter for SSN
@return SSN, boxer's unique identification number, e.g. 123456789
*/
public int getSSN () { return this.SSN; }
/**
Getter for name
@return name of the Boxer, e.g "Ali"
*/
public String getName () {return this.name; }
/**
convert to String representation in format [SSN,name]
e.g. <code>[123456789,"Ali"]</code>
@return formatted string, [SSN,name]
*/
@Override
public String toString() {
return "[" + getSSN() + "," + getName() + "]";
}
/** hashcode to be used for hash tables, etc.
based only on the SSN value.
*/
@Override
public int hashCode() {
final int prime = 31; /* could use any prime number */
int result = 1;
result = (prime * result) + this.SSN;
return result;
}
/** compare for equality based on SSN
@return true if parameter is a Boxer with same SSN, otherwise false
*/
@Override
public boolean equals(Object o) {
if (o==null) return false;
if (! (o instanceof Boxer) ) return false;
Boxer b = (Boxer) o;
return (b.getSSN() == this.getSSN());
}
public static void main(String [] args) {
Boxer b = new Boxer(123456789, "Ali");
System.out.println("b="+b);
}
}
|
src/edu/ucsb/cs56/w14/lab05/alecharrell/Boxer.java
|
package edu.ucsb.cs56.w14.lab05.alecharrell;
public class Boxer {
private int SSN; // SSN: Social security number, Boxer's unique
//identification number
private String name;//stores the last name of the Boxerr
/**
Two-arg constructor
@param SSN social security number of boxer, e.g. 123456789
@param name last name of the boxer, e.g. "Foreman"
*/
public Boxer(int SSN, String name) {
this.SSN = SSN;
this.name = name;
}
/**
Getter for SSN
@return SSN, boxer's unique identification number, e.g. 123456789
*/
public int getSSN () { return this.SSN; }
/**
Getter for name
@return name of the Boxer, e.g "Ali"
*/
public String getName () {return this.name; }
/**
convert to String representation in format [SSN,name]
e.g. <code>[123456789,"Ali"]</code>
@return formatted string, [SSN,name]
*/
@Override
public String toString() {
return "[" + getSSN() + "," + getName() + "]";
}
/** hashcode to be used for hash tables, etc.
based only on the SSN value.
*/
@Override
public int hashCode() {
final int prime = 31; /* could use any prime number */
int result = 1;
result = (prime * result) + this.SSN;
return result;
}
/** compare for equality based on SSN
@return true if parameter is a Boxer with same SSN, otherwise false
*/
@Override
public boolean equals(Object o) {
if (o==null) return false;
if (! (o instanceof Boxer) ) return false;
Boxer b = (Boxer) o;
return (b.getSSN() == this.getSSN());
}
}
|
Added main to Boxer.java, step 5
|
src/edu/ucsb/cs56/w14/lab05/alecharrell/Boxer.java
|
Added main to Boxer.java, step 5
|
|
Java
|
mit
|
428c5df99c4d169e821c2d4da63b6b524e936604
| 0
|
JavaCCSF2016/RockPaperScissorsGame
|
package com.github.javaccsf2016.rockpaperscissorsgame;
import java.util.Random;
public class RPSGame {
public static final int ROCK = 0;
public static final int PAPER = 1;
public static final int SCISSOR = 2;
private int numberOfTies;
private int numberOfWins;
private int numberOfLoses;
private int move;
public RPSGame() {
numberOfTies = 0;
numberOfWins = 0;
numberOfLoses = 0;
}
public void generateComputerPlay() {
Random rand = new Random();
this.move = rand.nextInt(3);
}
public int findWinner(int userMove) {
if (userMove >= 0 && userMove <= 2) {
if (userMove == this.move) {
this.numberOfTies++;
return 1;
} else if(userMove - this.move == 1 || userMove - this.move == -2) {
this.numberOfWins++;
return 2;
} else {
this.numberOfLoses++;
return 0;
}
} else {
return -1;
}
}
public int getLoses() {
return this.numberOfLoses;
}
public int getWins() {
return this.numberOfWins;
}
public int getTies() {
return this.numberOfTies;
}
}
|
src/com/github/javaccsf2016/rockpaperscissorsgame/RPSGame.java
|
package com.github.javaccsf2016.rockpaperscissorsgame;
import java.util.Random;
public class RPSGame {
public static final int ROCK = 0;
public static final int PAPER = 1;
public static final int SCISSOR = 2;
private int numberOfTies;
private int numberOfWins;
private int numberOfLoses;
private int move;
public RPSGame() {
numberOfTies = 0;
numberOfWins = 0;
numberOfLoses = 0;
}
public void generateComputerPlay() {
Random rand = new Random();
this.move = rand.nextInt(3);
}
public int findWinner(int userMove) {
if (userMove == this.move && userMove >= 0 && userMove <= 2) {
this.numberOfTies++;
return 1;
} else if(userMove - this.move == 1 || userMove - this.move == -2) {
this.numberOfWins++;
return 2;
} else if(userMove - this.move == -1 || userMove - this.move == 2){
this.numberOfLoses++;
return 0;
} else {
return -1;
}
}
public int getLoses() {
return this.numberOfLoses;
}
public int getWins() {
return this.numberOfWins;
}
public int getTies() {
return this.numberOfTies;
}
}
|
validating userMove
|
src/com/github/javaccsf2016/rockpaperscissorsgame/RPSGame.java
|
validating userMove
|
|
Java
|
epl-1.0
|
e8d93d8661f5b8af7d16d0e571c060cc5a02d83e
| 0
|
schemeway/SchemeScript,schemeway/SchemeScript
|
/*
* Copyright (c) 2004 Nu Echo Inc.
*
* This is free software. For terms and warranty disclaimer, see ./COPYING
*/
package org.schemeway.plugins.schemescript.editor;
import java.util.*;
import org.eclipse.jface.text.*;
import org.eclipse.jface.text.source.*;
import org.eclipse.ui.texteditor.*;
import org.schemeway.plugins.schemescript.dictionary.*;
public class SchemeTextHover implements ITextHover {
private SchemeEditor mEditor;
public SchemeTextHover(SchemeEditor editor) {
super();
mEditor = editor;
}
protected SchemeEditor getEditor() {
return mEditor;
}
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
if (hoverRegion == null)
return null;
String[] infoMessages = findDefinitions(textViewer.getDocument(), getEditor().getSymbolDictionary(),
hoverRegion);
if (infoMessages == null || infoMessages.length == 0) {
infoMessages = findAnnotations(textViewer, hoverRegion);
}
if (infoMessages == null || infoMessages.length == 0) {
return null;
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < infoMessages.length; i++) {
if (i > 0)
buffer.append('\n');
buffer.append(infoMessages[i]);
}
return buffer.toString();
}
private String[] findDefinitions(IDocument document, ISymbolDictionary dictionary, IRegion hoverRegion) {
List defs = new ArrayList();
try {
String symbol = document.get(hoverRegion.getOffset(), hoverRegion.getLength());
SymbolEntry[] entries = getEditor().getSymbolDictionary().findSymbol(symbol);
for (int i = 0; i < entries.length; i++) {
String description = entries[i].getDescription();
if (!defs.contains(description)) {
defs.add(description);
}
}
}
catch (BadLocationException e) {
}
return (String[]) defs.toArray(new String[defs.size()]);
}
private String[] findAnnotations(ITextViewer textViewer, IRegion hoverRegion) {
List messages = new ArrayList();
if (textViewer instanceof ISourceViewer) {
ISourceViewer sourceViewer = (ISourceViewer) textViewer;
IAnnotationModel model = sourceViewer.getAnnotationModel();
Iterator iterator = model.getAnnotationIterator();
while (iterator.hasNext()) {
Annotation annotation = (Annotation) iterator.next();
Position position = model.getPosition(annotation);
if (position.offset <= hoverRegion.getOffset()
&& hoverRegion.getOffset() <= position.offset + position.length
&& annotation instanceof MarkerAnnotation) {
messages.add(annotation.getText());
}
}
}
return (String[]) messages.toArray(new String[messages.size()]);
}
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
try {
IRegion result = SchemeTextUtilities.findSymbolRegionAroundPoint(textViewer.getDocument(), offset);
if (result == null) {
result = findAnnotationRegion(textViewer, offset);
}
return result;
}
catch (BadLocationException exception) {
return null;
}
}
private IRegion findAnnotationRegion(ITextViewer textViewer, int offset) {
if (textViewer instanceof ISourceViewer) {
ISourceViewer sourceViewer = (ISourceViewer) textViewer;
IAnnotationModel model = sourceViewer.getAnnotationModel();
Iterator iterator = model.getAnnotationIterator();
while (iterator.hasNext()) {
Annotation annotation = (Annotation) iterator.next();
Position position = model.getPosition(annotation);
if (position.offset <= offset && offset <= position.offset + position.length) {
return new Region(position.offset, position.length);
}
}
}
return null;
}
}
|
src/org/schemeway/plugins/schemescript/editor/SchemeTextHover.java
|
/*
* Copyright (c) 2004 Nu Echo Inc.
*
* This is free software. For terms and warranty disclaimer, see ./COPYING
*/
package org.schemeway.plugins.schemescript.editor;
import java.util.*;
import org.eclipse.jface.text.*;
import org.schemeway.plugins.schemescript.dictionary.*;
public class SchemeTextHover implements ITextHover {
private SchemeEditor mEditor;
public SchemeTextHover(SchemeEditor editor) {
super();
mEditor = editor;
}
protected SchemeEditor getEditor() {
return mEditor;
}
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
if (hoverRegion == null)
return null;
try {
String symbol = textViewer.getDocument().get(hoverRegion.getOffset(), hoverRegion.getLength());
SymbolEntry[] entries = getEditor().getSymbolDictionary().findSymbol(symbol);
if (entries.length == 0) {
return null;
}
Set descriptionSet = new HashSet();
StringBuffer buffer = new StringBuffer();
buffer.append(entries[0].getDescription());
descriptionSet.add(entries[0].getDescription());
for (int i=1; i<entries.length; i++) {
String description = entries[i].getDescription();
if (!descriptionSet.contains(description)) {
buffer.append('\n');
buffer.append(description);
descriptionSet.add(description);
}
}
return buffer.toString();
}
catch (BadLocationException exception) {
return null;
}
}
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
try {
return SchemeTextUtilities.findSymbolRegionAroundPoint(textViewer.getDocument(), offset);
}
catch (BadLocationException exception) {
return null;
}
}
}
|
Added text hovers for annotations
|
src/org/schemeway/plugins/schemescript/editor/SchemeTextHover.java
|
Added text hovers for annotations
|
|
Java
|
agpl-3.0
|
51ce01404a73e7340e5851bbe7f1915f517d1eba
| 0
|
VietOpenCPS/opencps-v2,VietOpenCPS/opencps-v2
|
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* 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.
*/
package org.opencps.dossiermgt.service.impl;
import com.liferay.counter.kernel.service.CounterLocalServiceUtil;
import com.liferay.document.library.kernel.service.DLAppLocalServiceUtil;
import com.liferay.petra.string.StringPool;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.exception.NoSuchUserException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageBusUtil;
import com.liferay.portal.kernel.model.Company;
import com.liferay.portal.kernel.model.Role;
import com.liferay.portal.kernel.model.User;
import com.liferay.portal.kernel.repository.model.FileEntry;
import com.liferay.portal.kernel.search.Field;
import com.liferay.portal.kernel.search.SearchException;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.service.SubscriptionLocalServiceUtil;
import com.liferay.portal.kernel.service.UserLocalServiceUtil;
import com.liferay.portal.kernel.servlet.HttpMethods;
import com.liferay.portal.kernel.transaction.Isolation;
import com.liferay.portal.kernel.transaction.Propagation;
import com.liferay.portal.kernel.transaction.Transactional;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ListUtil;
import com.liferay.portal.kernel.util.LocaleUtil;
import com.liferay.portal.kernel.util.PwdGenerator;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.uuid.PortalUUIDUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.activation.DataHandler;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.opencps.adminconfig.model.DynamicReport;
import org.opencps.adminconfig.service.DynamicReportLocalServiceUtil;
import org.opencps.auth.api.BackendAuth;
import org.opencps.auth.api.BackendAuthImpl;
import org.opencps.auth.api.exception.UnauthenticationException;
import org.opencps.auth.api.keys.NotificationType;
import org.opencps.auth.utils.APIDateTimeUtils;
import org.opencps.cache.actions.CacheActions;
import org.opencps.cache.actions.impl.CacheActionsImpl;
import org.opencps.communication.constants.NotificationTemplateTerm;
import org.opencps.communication.model.NotificationQueue;
import org.opencps.communication.model.Notificationtemplate;
import org.opencps.communication.model.ServerConfig;
import org.opencps.communication.service.NotificationQueueLocalServiceUtil;
import org.opencps.communication.service.NotificationtemplateLocalServiceUtil;
import org.opencps.communication.service.ServerConfigLocalServiceUtil;
import org.opencps.datamgt.model.DictCollection;
import org.opencps.datamgt.model.DictItem;
import org.opencps.datamgt.service.DictCollectionLocalServiceUtil;
import org.opencps.datamgt.service.DictItemLocalServiceUtil;
import org.opencps.datamgt.util.BetimeUtils;
import org.opencps.datamgt.util.DueDatePhaseUtil;
import org.opencps.datamgt.util.DueDateUtils;
import org.opencps.dossiermgt.action.DossierActions;
import org.opencps.dossiermgt.action.DossierUserActions;
import org.opencps.dossiermgt.action.impl.DVCQGIntegrationActionImpl;
import org.opencps.dossiermgt.action.impl.DossierActionsImpl;
import org.opencps.dossiermgt.action.impl.DossierPermission;
import org.opencps.dossiermgt.action.impl.DossierUserActionsImpl;
import org.opencps.dossiermgt.action.util.AutoFillFormData;
import org.opencps.dossiermgt.action.util.ConfigCounterNumberGenerator;
import org.opencps.dossiermgt.action.util.ConstantUtils;
import org.opencps.dossiermgt.action.util.DocumentTypeNumberGenerator;
import org.opencps.dossiermgt.action.util.DossierActionUtils;
import org.opencps.dossiermgt.action.util.DossierMgtUtils;
import org.opencps.dossiermgt.action.util.DossierNumberGenerator;
import org.opencps.dossiermgt.action.util.DossierPaymentUtils;
import org.opencps.dossiermgt.action.util.KeyPay;
import org.opencps.dossiermgt.action.util.NotificationUtil;
import org.opencps.dossiermgt.action.util.OpenCPSConfigUtil;
import org.opencps.dossiermgt.action.util.PaymentUrlGenerator;
import org.opencps.dossiermgt.action.util.ReadFilePropertiesUtils;
import org.opencps.dossiermgt.constants.ActionConfigTerm;
import org.opencps.dossiermgt.constants.CInvoiceTerm;
import org.opencps.dossiermgt.constants.CacheTerm;
import org.opencps.dossiermgt.constants.DossierActionTerm;
import org.opencps.dossiermgt.constants.DossierActionUserTerm;
import org.opencps.dossiermgt.constants.DossierDocumentTerm;
import org.opencps.dossiermgt.constants.DossierFileTerm;
import org.opencps.dossiermgt.constants.DossierPartTerm;
import org.opencps.dossiermgt.constants.DossierSyncTerm;
import org.opencps.dossiermgt.constants.DossierTerm;
import org.opencps.dossiermgt.constants.KeyPayTerm;
import org.opencps.dossiermgt.constants.NotarizationTerm;
import org.opencps.dossiermgt.constants.PaymentFileTerm;
import org.opencps.dossiermgt.constants.ProcessActionTerm;
import org.opencps.dossiermgt.constants.PublishQueueTerm;
import org.opencps.dossiermgt.constants.ServerConfigTerm;
import org.opencps.dossiermgt.constants.ServiceInfoTerm;
import org.opencps.dossiermgt.constants.StepConfigTerm;
import org.opencps.dossiermgt.constants.VTPayTerm;
import org.opencps.dossiermgt.constants.VnpostCollectionTerm;
import org.opencps.dossiermgt.exception.DataConflictException;
import org.opencps.dossiermgt.exception.NoSuchDossierUserException;
import org.opencps.dossiermgt.exception.NoSuchPaymentFileException;
import org.opencps.dossiermgt.input.model.DossierInputModel;
import org.opencps.dossiermgt.input.model.DossierMultipleInputModel;
import org.opencps.dossiermgt.input.model.PaymentFileInputModel;
import org.opencps.dossiermgt.model.ActionConfig;
import org.opencps.dossiermgt.model.ConfigCounter;
import org.opencps.dossiermgt.model.Deliverable;
import org.opencps.dossiermgt.model.DocumentType;
import org.opencps.dossiermgt.model.Dossier;
import org.opencps.dossiermgt.model.DossierAction;
import org.opencps.dossiermgt.model.DossierActionUser;
import org.opencps.dossiermgt.model.DossierDocument;
import org.opencps.dossiermgt.model.DossierFile;
import org.opencps.dossiermgt.model.DossierMark;
import org.opencps.dossiermgt.model.DossierPart;
import org.opencps.dossiermgt.model.DossierTemplate;
import org.opencps.dossiermgt.model.DossierUser;
import org.opencps.dossiermgt.model.Notarization;
import org.opencps.dossiermgt.model.PaymentConfig;
import org.opencps.dossiermgt.model.PaymentFile;
import org.opencps.dossiermgt.model.ProcessAction;
import org.opencps.dossiermgt.model.ProcessOption;
import org.opencps.dossiermgt.model.ProcessSequence;
import org.opencps.dossiermgt.model.ProcessStep;
import org.opencps.dossiermgt.model.ProcessStepRole;
import org.opencps.dossiermgt.model.PublishQueue;
import org.opencps.dossiermgt.model.ServiceConfig;
import org.opencps.dossiermgt.model.ServiceInfo;
import org.opencps.dossiermgt.model.ServiceProcess;
import org.opencps.dossiermgt.model.ServiceProcessRole;
import org.opencps.dossiermgt.model.StepConfig;
import org.opencps.dossiermgt.rest.utils.ExecuteOneActionTerm;
import org.opencps.dossiermgt.rest.utils.SyncServerTerm;
import org.opencps.dossiermgt.scheduler.InvokeREST;
import org.opencps.dossiermgt.scheduler.RESTFulConfiguration;
import org.opencps.dossiermgt.service.ActionConfigLocalServiceUtil;
import org.opencps.dossiermgt.service.ConfigCounterLocalServiceUtil;
import org.opencps.dossiermgt.service.DocumentTypeLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierActionLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierActionUserLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierDocumentLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierFileLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierMarkLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierPartLocalServiceUtil;
import org.opencps.dossiermgt.service.NotarizationLocalServiceUtil;
import org.opencps.dossiermgt.service.PaymentFileLocalServiceUtil;
import org.opencps.dossiermgt.service.ProcessActionLocalServiceUtil;
import org.opencps.dossiermgt.service.ProcessSequenceLocalServiceUtil;
import org.opencps.dossiermgt.service.ProcessStepLocalServiceUtil;
import org.opencps.dossiermgt.service.PublishQueueLocalServiceUtil;
import org.opencps.dossiermgt.service.ServiceInfoLocalServiceUtil;
import org.opencps.dossiermgt.service.ServiceProcessLocalServiceUtil;
import org.opencps.dossiermgt.service.StepConfigLocalServiceUtil;
import org.opencps.dossiermgt.service.base.CPSDossierBusinessLocalServiceBaseImpl;
import org.opencps.dossiermgt.service.persistence.DossierActionUserPK;
import org.opencps.dossiermgt.service.persistence.DossierUserPK;
import org.opencps.dossiermgt.service.persistence.ServiceProcessRolePK;
import org.opencps.usermgt.constants.ApplicantDataTerm;
import org.opencps.usermgt.constants.ApplicantTerm;
import org.opencps.usermgt.model.Applicant;
import org.opencps.usermgt.model.Employee;
import org.opencps.usermgt.model.EmployeeJobPos;
import org.opencps.usermgt.model.FileItem;
import org.opencps.usermgt.model.JobPos;
import org.opencps.usermgt.model.WorkingUnit;
import org.opencps.usermgt.service.ApplicantDataLocalServiceUtil;
import org.opencps.usermgt.service.ApplicantLocalServiceUtil;
import org.opencps.usermgt.service.EmployeeJobPosLocalServiceUtil;
import org.opencps.usermgt.service.EmployeeLocalServiceUtil;
import org.opencps.usermgt.service.FileItemLocalServiceUtil;
import org.opencps.usermgt.service.JobPosLocalServiceUtil;
import org.opencps.usermgt.service.WorkingUnitLocalServiceUtil;
import backend.auth.api.exception.NotFoundException;
/**
* The implementation of the cps dossier business local service.
*
* <p>
* All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {@link org.opencps.dossiermgt.service.CPSDossierBusinessLocalService} interface.
*
* <p>
* This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM.
* </p>
*
* @author huymq
* @see CPSDossierBusinessLocalServiceBaseImpl
* @see org.opencps.dossiermgt.service.CPSDossierBusinessLocalServiceUtil
*/
@Transactional(isolation = Isolation.PORTAL, rollbackFor = {
PortalException.class, SystemException.class
})
public class CPSDossierBusinessLocalServiceImpl
extends CPSDossierBusinessLocalServiceBaseImpl {
/*
* NOTE FOR DEVELOPERS:
*
* Never reference this class directly. Always use {@link org.opencps.dossiermgt.service.CPSDossierBusinessLocalServiceUtil} to access the cps dossier business local service.
*/
private static final String BN_TELEPHONE = "BN_telephone";
private static final String BN_ADDRESS = "BN_address";
private static final String BN_EMAIL = "BN_email";
public static final String DOSSIER_SATUS_DC_CODE = "DOSSIER_STATUS";
public static final String DOSSIER_SUB_SATUS_DC_CODE = "DOSSIER_SUB_STATUS";
public static final String DEFAULT_DATE_FORMAT = "dd/MM/yyyy";
public static final String PAYLOAD_KEY_COMPLEMENT_DATE = "complementDate";
public static final String PAYLOAD_KEY_dOSSIER_DOCUMENT = "dossierDocument";
public static final String CACHE_NOTIFICATION_TEMPLATE = "NotificationTemplate";
CacheActions cache = new CacheActionsImpl();
int ttl = OpenCPSConfigUtil.getCacheTTL();
private Dossier createCrossDossier(long groupId, ProcessAction proAction, ProcessStep curStep, DossierAction previousAction, Employee employee, Dossier dossier, User user,
JSONObject payloadObj,
ServiceContext context)
throws PortalException {
if (Validator.isNotNull(proAction.getCreateDossiers())) {
//Create new HSLT
String GOVERNMENT_AGENCY = ReadFilePropertiesUtils.get(ConstantUtils.GOVERNMENT_AGENCY);
String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, proAction.getCreateDossiers());
String createDossiers = proAction.getCreateDossiers();
String govAgencyCode = StringPool.BLANK;
String serviceCode = dossier.getServiceCode();
String dossierTemplateNo = dossier.getDossierTemplateNo();
if (createDossiers.contains(StringPool.POUND)) {
String[] splitCDs = createDossiers.split(StringPool.POUND);
if (splitCDs.length == 2) {
govAgencyCode = splitCDs[0];
if (splitCDs[1].contains(StringPool.AT)) {
if (splitCDs[1].split(StringPool.AT).length != 2) {
throw new PortalException(ReadFilePropertiesUtils.get(ConstantUtils.MSG_ERROR));
}
else {
dossierTemplateNo = splitCDs[1].split(StringPool.AT)[0];
serviceCode = splitCDs[1].split(StringPool.AT)[1];
}
}
else {
govAgencyCode = splitCDs[0];
dossierTemplateNo = splitCDs[1];
}
}
}
else {
if (createDossiers.contains(StringPool.AT)) {
if (createDossiers.split(StringPool.AT).length != 2) {
throw new PortalException(ReadFilePropertiesUtils.get(ConstantUtils.MSG_ERROR));
}
else {
govAgencyCode = createDossiers.split(StringPool.AT)[0];
serviceCode = createDossiers.split(StringPool.AT)[1];
}
}
else {
govAgencyCode = createDossiers;
}
}
// ServiceConfig serviceConfig = serviceConfigLocalService.getBySICodeAndGAC(groupId, dossier.getServiceCode(), govAgencyCode);
ServiceConfig serviceConfig = serviceConfigLocalService.getBySICodeAndGAC(groupId, serviceCode, govAgencyCode);
if (serviceConfig != null) {
List<ProcessOption> lstOptions = processOptionLocalService.getByServiceProcessId(serviceConfig.getServiceConfigId());
//
ProcessOption foundOption = null;
if (createDossiers.contains(StringPool.POUND)) {
for (ProcessOption po : lstOptions) {
DossierTemplate dt = dossierTemplateLocalService.fetchDossierTemplate(po.getDossierTemplateId());
if (dt.getTemplateNo().equals(dossierTemplateNo)) {
foundOption = po;
break;
}
}
}
else {
if (lstOptions.size() > 0) {
foundOption = lstOptions.get(0);
}
}
if (foundOption != null) {
ServiceProcess ltProcess = serviceProcessLocalService.fetchServiceProcess(foundOption.getServiceProcessId());
DossierTemplate dossierTemplate = dossierTemplateLocalService.fetchDossierTemplate(foundOption.getDossierTemplateId());
// String delegateName = dossier.getDelegateName();
//String delegateName = dossier.getGovAgencyName();
//String delegateAddress = dossier.getDelegateAddress();
//String delegateTelNo = dossier.getDelegateTelNo();
//String delegateEmail = dossier.getDelegateEmail();
//String delegateIdNo = dossier.getGovAgencyCode();
JSONObject crossDossierObj = JSONFactoryUtil.createJSONObject();
crossDossierObj.put(DossierTerm.DOSSIER_TEMPLATE_NO, dossierTemplate.getTemplateNo());
crossDossierObj.put(DossierTerm.GOV_AGENCY_CODE, govAgencyCode);
crossDossierObj.put(DossierTerm.SERVICE_CODE, serviceCode);
payloadObj.put(DossierTerm.CROSS_DOSSIER, crossDossierObj);
// Dossier oldHslt = DossierLocalServiceUtil.getByG_AN_SC_GAC_DTNO_ODID(groupId, dossier.getApplicantIdNo(), dossier.getServiceCode(), govAgencyCode, dossierTemplate.getTemplateNo(), dossier.getDossierId());
Dossier oldHslt = DossierLocalServiceUtil.getByG_AN_SC_GAC_DTNO_ODID(groupId, dossier.getApplicantIdNo(), serviceCode, govAgencyCode, dossierTemplate.getTemplateNo(), dossier.getDossierId());
Dossier hsltDossier = null;
if (oldHslt != null) {
if (oldHslt.getOriginality() < 0) {
oldHslt.setOriginality(-oldHslt.getOriginality());
}
hsltDossier = oldHslt;
}
if (hsltDossier == null) {
// hsltDossier = dossierLocalService.initDossier(groupId, 0l, UUID.randomUUID().toString(),
// dossier.getCounter(), dossier.getServiceCode(),
// dossier.getServiceName(), govAgencyCode, govAgencyName, dossier.getApplicantName(),
// dossier.getApplicantIdType(), dossier.getApplicantIdNo(), dossier.getApplicantIdDate(),
// dossier.getAddress(), dossier.getCityCode(), dossier.getCityName(), dossier.getDistrictCode(),
// dossier.getDistrictName(), dossier.getWardCode(), dossier.getWardName(), dossier.getContactName(),
// dossier.getContactTelNo(), dossier.getContactEmail(), dossierTemplate.getTemplateNo(),
// dossier.getPassword(), dossier.getViaPostal(), dossier.getPostalAddress(), dossier.getPostalCityCode(),
// dossier.getPostalCityName(), dossier.getPostalTelNo(),
// dossier.getOnline(), dossier.getNotification(), dossier.getApplicantNote(), DossierTerm.ORIGINALITY_DVCTT, context);
hsltDossier = dossierLocalService.initDossier(groupId, 0l, UUID.randomUUID().toString(),
dossier.getCounter(), serviceCode,
dossier.getServiceName(), govAgencyCode, govAgencyName, dossier.getApplicantName(),
dossier.getApplicantIdType(), dossier.getApplicantIdNo(), dossier.getApplicantIdDate(),
dossier.getAddress(), dossier.getCityCode(), dossier.getCityName(), dossier.getDistrictCode(),
dossier.getDistrictName(), dossier.getWardCode(), dossier.getWardName(), dossier.getContactName(),
dossier.getContactTelNo(), dossier.getContactEmail(), dossierTemplate.getTemplateNo(),
dossier.getPassword(), dossier.getViaPostal(), dossier.getPostalAddress(), dossier.getPostalCityCode(),
dossier.getPostalCityName(), dossier.getPostalTelNo(),
dossier.getOnline(), dossier.getNotification(), dossier.getApplicantNote(), DossierTerm.ORIGINALITY_DVCTT, context);
}
WorkingUnit wu = WorkingUnitLocalServiceUtil.fetchByF_govAgencyCode(dossier.getGroupId(), dossier.getGovAgencyCode());
String delegateName = null;
String delegateAddress = null;
String delegateTelNo = null;
String delegateEmail = null;
String delegateIdNo = null;
delegateIdNo = dossier.getGovAgencyCode();
if (wu != null) {
delegateName = wu.getName();
delegateAddress = wu.getAddress();
delegateTelNo = wu.getTelNo();
delegateEmail = wu.getEmail();
//new 3.0 comment
// delegateIdNo = wu.getGovAgencyCode();
}
else if (user != null && employee != null) {
delegateName = employee.getFullName();
delegateAddress = dossier.getGovAgencyName();
delegateTelNo = employee.getTelNo();
delegateEmail = employee.getEmail();
}
if (hsltDossier != null) {
hsltDossier.setDelegateName(delegateName != null ? delegateName : StringPool.BLANK);
hsltDossier.setDelegateAddress(delegateAddress != null ? delegateAddress : StringPool.BLANK);
hsltDossier.setDelegateTelNo(delegateTelNo != null ? delegateTelNo : StringPool.BLANK);
hsltDossier.setDelegateEmail(delegateEmail != null ? delegateEmail : StringPool.BLANK);
hsltDossier.setDelegateIdNo(delegateIdNo != null ? delegateIdNo : StringPool.BLANK);
hsltDossier.setNew(false);
hsltDossier = dossierLocalService.updateDossier(hsltDossier);
}
//
String dossierNote = StringPool.BLANK;
if (previousAction != null) {
dossierNote = previousAction.getActionNote();
if (Validator.isNotNull(dossierNote)) {
dossierNote = previousAction.getStepInstruction();
}
}
if (hsltDossier != null) {
//Set HSLT dossierId to origin dossier
hsltDossier.setOriginDossierId(dossier.getDossierId());
if (ltProcess.getServerNo().contains(StringPool.COMMA)) {
if (!serviceCode.equals(dossier.getServiceCode())) {
String serverNoProcess = ltProcess.getServerNo().split(StringPool.COMMA)[0];
hsltDossier.setServerNo(serverNoProcess + StringPool.AT + serviceCode + StringPool.COMMA + ltProcess.getServerNo().split(StringPool.COMMA)[1]);
hsltDossier = dossierLocalService.updateDossier(hsltDossier);
}
}
else {
hsltDossier.setServerNo(ltProcess.getServerNo());
}
//Update DossierName
hsltDossier.setDossierName(dossier.getDossierName());
hsltDossier.setOriginDossierNo(dossier.getDossierNo());
dossierLocalService.updateDossier(hsltDossier);
JSONObject jsonDataStatusText = getStatusText(groupId, ReadFilePropertiesUtils.get(ConstantUtils.DOSSIER_STATUS), ReadFilePropertiesUtils.get(ConstantUtils.STATUS_NEW), StringPool.BLANK);
hsltDossier = dossierLocalService.updateStatus(groupId, hsltDossier.getDossierId(), hsltDossier.getReferenceUid(),
ReadFilePropertiesUtils.get(ConstantUtils.STATUS_NEW),
jsonDataStatusText != null ? jsonDataStatusText.getString(ReadFilePropertiesUtils.get(ConstantUtils.STATUS_NEW)) : StringPool.BLANK, StringPool.BLANK,
StringPool.BLANK, StringPool.BLANK, dossierNote, context);
}
else {
return null;
}
JSONObject jsonDataStatusText = getStatusText(groupId, ReadFilePropertiesUtils.get(ConstantUtils.DOSSIER_STATUS), DossierTerm.DOSSIER_STATUS_INTEROPERATING, StringPool.BLANK);
if (curStep != null) {
dossier = dossierLocalService.updateStatus(groupId, dossier.getDossierId(),
dossier.getReferenceUid(), DossierTerm.DOSSIER_STATUS_INTEROPERATING,
jsonDataStatusText != null ? jsonDataStatusText.getString(DossierTerm.DOSSIER_STATUS_INTEROPERATING) : StringPool.BLANK, StringPool.BLANK,
StringPool.BLANK, curStep.getLockState(), dossierNote, context);
dossier.setDossierStatus(DossierTerm.DOSSIER_STATUS_INTEROPERATING);
dossier.setDossierStatusText(jsonDataStatusText != null ? jsonDataStatusText.getString(DossierTerm.DOSSIER_STATUS_INTEROPERATING) : StringPool.BLANK);
dossier.setDossierSubStatus(StringPool.BLANK);
dossier.setDossierSubStatusText(StringPool.BLANK);
if (dossier != null && !DossierTerm.PAUSE_OVERDUE_LOCK_STATE.equals(dossier.getLockState())) {
dossier.setLockState(curStep.getLockState());
}
dossier.setDossierNote(dossierNote);;
}
return hsltDossier;
}
else {
return null;
}
}
else {
return null;
}
}
else {
return null;
}
}
private void createDossierDocument(long groupId, long userId, ActionConfig actionConfig,
Dossier dossier, DossierAction dossierAction,
JSONObject payloadObject, Employee employee, User user,
ServiceContext context) throws com.liferay.portal.kernel.search.ParseException, JSONException, SearchException {
//Check if generate dossier document
ActionConfig ac = actionConfig;
if (ac != null) {
if (dossier.getOriginality() != DossierTerm.ORIGINALITY_DVCTT) {
if (Validator.isNotNull(ac.getDocumentType()) && !ac.getActionCode().startsWith(StringPool.AT)) {
//Generate document
String[] documentTypes = ac.getDocumentType().split(StringPool.COMMA);
for (String documentType : documentTypes) {
DocumentType dt = DocumentTypeLocalServiceUtil.getByTypeCode(groupId, documentType.trim());
if (dt != null) {
String documentCode = DocumentTypeNumberGenerator.generateDossierDocumentNumber(groupId,
dossier.getCompanyId(), dossier.getServiceCode(), dossier.getGovAgencyCode(),
dt.getCodePattern());
String refUid = UUID.randomUUID().toString();
if (Validator.isNotNull(dossier.getOriginDossierNo()) && dossier.getOriginDossierId() == 0) {
refUid = DossierTerm.PREFIX_UUID + refUid;
}
DossierDocument dossierDocument = DossierDocumentLocalServiceUtil.addDossierDoc(groupId,
dossier.getDossierId(), refUid, dossierAction.getDossierActionId(),
dt.getTypeCode(), dt.getDocumentName(), documentCode, 0L, dt.getDocSync(), context);
//Generate PDF
String formData = dossierAction.getPayload();
JSONObject payloadTmp = JSONFactoryUtil.createJSONObject(formData);
if (payloadTmp != null && payloadTmp.has(PAYLOAD_KEY_COMPLEMENT_DATE)) {
if (payloadTmp.getLong(PAYLOAD_KEY_COMPLEMENT_DATE) > 0) {
Timestamp ts = new Timestamp(payloadTmp.getLong(PAYLOAD_KEY_COMPLEMENT_DATE));
SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
payloadTmp.put(PAYLOAD_KEY_COMPLEMENT_DATE, format.format(ts));
}
}
JSONObject formDataObj = processMergeDossierFormData(dossier, payloadTmp);
formDataObj = processMergeDossierProcessRole(dossier, 1, formDataObj, dossierAction);
formDataObj.put(ConstantUtils.VALUE_URL, context.getPortalURL());
if (employee != null) {
formDataObj.put(Field.USER_NAME, employee.getFullName());
} else {
formDataObj.put(Field.USER_NAME, user.getFullName());
}
Message message = new Message();
// _log.info("Document script: " + dt.getDocumentScript());
JSONObject msgData = JSONFactoryUtil.createJSONObject();
msgData.put(ConstantUtils.CLASS_NAME, DossierDocument.class.getName());
msgData.put(Field.CLASS_PK, dossierDocument.getDossierDocumentId());
msgData.put(ConstantUtils.JRXML_TEMPLATE, dt.getDocumentScript());
msgData.put(ConstantUtils.FORM_DATA, formDataObj.toJSONString());
msgData.put(Field.USER_ID, userId);
message.put(ConstantUtils.MSG_ENG, msgData);
MessageBusUtil.sendMessage(ConstantUtils.JASPER_DESTINATION, message);
payloadObject.put(DossierDocumentTerm.DOSSIER_DOCUMENT_ID, dossierDocument.getDossierDocumentId());
}
}
}
}
}
}
private boolean createDossierDocumentPostAction(long groupId, long userId,
Dossier dossier, DossierAction dossierAction,
JSONObject payloadObject, Employee employee, User user, String documentTypeList,
ServiceContext context) throws com.liferay.portal.kernel.search.ParseException, JSONException, SearchException {
//Check if generate dossier document
if (dossier.getOriginality() != DossierTerm.ORIGINALITY_DVCTT) {
// Generate document
String[] documentTypes = documentTypeList.split(StringPool.COMMA);
for (String documentType : documentTypes) {
DocumentType dt = DocumentTypeLocalServiceUtil.getByTypeCode(groupId, documentType.trim());
if (dt != null) {
String documentCode = DocumentTypeNumberGenerator.generateDossierDocumentNumber(groupId,
dossier.getCompanyId(), dossier.getServiceCode(), dossier.getGovAgencyCode(),
dt.getCodePattern());
DossierDocument dossierDocument = DossierDocumentLocalServiceUtil.addDossierDoc(groupId,
dossier.getDossierId(), UUID.randomUUID().toString(), dossierAction.getDossierActionId(),
dt.getTypeCode(), dt.getDocumentName(), documentCode, 0L, dt.getDocSync(), context);
// Generate PDF
String formData = dossierAction.getPayload();
JSONObject payloadTmp = JSONFactoryUtil.createJSONObject(formData);
if (payloadTmp != null && payloadTmp.has(PAYLOAD_KEY_COMPLEMENT_DATE)) {
if (payloadTmp.getLong(PAYLOAD_KEY_COMPLEMENT_DATE) > 0) {
Timestamp ts = new Timestamp(payloadTmp.getLong(PAYLOAD_KEY_COMPLEMENT_DATE));
SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
payloadTmp.put(PAYLOAD_KEY_COMPLEMENT_DATE, format.format(ts));
}
}
JSONObject formDataObj = processMergeDossierFormData(dossier, payloadTmp);
formDataObj = processMergeDossierProcessRole(dossier, 1, formDataObj, dossierAction);
formDataObj.put(ConstantUtils.VALUE_URL, context.getPortalURL());
formDataObj.put(DossierDocumentTerm.DOCUMENT_CODE, documentCode);
if (employee != null) {
formDataObj.put(Field.USER_NAME, employee.getFullName());
} else {
formDataObj.put(Field.USER_NAME, user.getFullName());
}
Message message = new Message();
// _log.info("Document script: " + dt.getDocumentScript());
JSONObject msgData = JSONFactoryUtil.createJSONObject();
msgData.put(ConstantUtils.CLASS_NAME, DossierDocument.class.getName());
msgData.put(Field.CLASS_PK, dossierDocument.getDossierDocumentId());
msgData.put(ConstantUtils.JRXML_TEMPLATE, dt.getDocumentScript());
msgData.put(ConstantUtils.FORM_DATA, formDataObj.toJSONString());
msgData.put(Field.USER_ID, userId);
message.put(ConstantUtils.MSG_ENG, msgData);
MessageBusUtil.sendMessage(ConstantUtils.JASPER_DESTINATION, message);
payloadObject.put(PAYLOAD_KEY_dOSSIER_DOCUMENT, dossierDocument.getDossierDocumentId());
}
}
}
return true;
}
private void createDossierSync(long groupId, long userId, ActionConfig actionConfig, ProcessAction proAction, DossierAction dossierAction, Dossier dossier, int syncType,
ProcessOption option,
JSONObject payloadObject, Map<String, Boolean> flagChanged,
String actionCode, String actionUser, String actionNote, ServiceProcess serviceProcess,
ServiceContext context) throws PortalException {
//Create DossierSync
String dossierRefUid = dossier.getReferenceUid();
String syncRefUid = UUID.randomUUID().toString();
if (syncType > 0) {
int state = DossierActionUtils.getSyncState(syncType, dossier);
//If state = 1 set pending dossier
if (state == DossierSyncTerm.STATE_WAITING_SYNC) {
if (dossierAction != null) {
dossierAction.setPending(true);
dossierActionLocalService.updateDossierAction(dossierAction);
}
}
else {
if (dossierAction != null) {
dossierAction.setPending(false);
dossierActionLocalService.updateDossierAction(dossierAction);
}
}
//Update payload
JSONArray dossierFilesArr = JSONFactoryUtil.createJSONArray();
List<DossierFile> lstFiles = DossierFileLocalServiceUtil.findByDID(dossier.getDossierId());
if (actionConfig.getSyncType() == DossierSyncTerm.SYNCTYPE_REQUEST) {
if (dossier.getOriginDossierId() == 0) {
if (lstFiles.size() > 0) {
for (DossierFile df : lstFiles) {
JSONObject dossierFileObj = JSONFactoryUtil.createJSONObject();
dossierFileObj.put(DossierFileTerm.REFERENCE_UID, df.getReferenceUid());
dossierFilesArr.put(dossierFileObj);
}
}
}
else {
// ServiceConfig serviceConfig = ServiceConfigLocalServiceUtil.getBySICodeAndGAC(groupId, dossier.getServiceCode(), dossier.getGovAgencyCode());
// List<ProcessOption> lstOptions = ProcessOptionLocalServiceUtil.getByServiceProcessId(serviceConfig.getServiceConfigId());
// if (serviceConfig != null) {
// if (lstOptions.size() > 0) {
// ProcessOption processOption = lstOptions.get(0);
ProcessOption processOption = option;
DossierTemplate dossierTemplate = dossierTemplateLocalService.fetchDossierTemplate(processOption.getDossierTemplateId());
List<DossierPart> lstParts = dossierPartLocalService.getByTemplateNo(groupId, dossierTemplate.getTemplateNo());
List<DossierFile> lstOriginFiles = dossierFileLocalService.findByDID(dossier.getOriginDossierId());
if (lstOriginFiles.size() > 0) {
List<String> lstCheckParts = new ArrayList<String>();
if (payloadObject.has(DossierSyncTerm.PAYLOAD_SYNC_DOSSIER_PARTS)) {
try {
JSONArray partArrs = payloadObject.getJSONArray(DossierSyncTerm.PAYLOAD_SYNC_DOSSIER_PARTS);
for (int tempI = 0; tempI <= partArrs.length(); tempI++) {
JSONObject partObj = partArrs.getJSONObject(tempI);
lstCheckParts.add(partObj.getString(DossierPartTerm.PART_NO));
}
}
catch (Exception e) {
_log.debug(e);
}
}
for (DossierFile df : lstOriginFiles) {
boolean flagHslt = false;
for (DossierPart dp : lstParts) {
if (dp.getPartNo().equals(df.getDossierPartNo())
&& (lstCheckParts.size() == 0 || (lstCheckParts.size() > 0 && lstCheckParts.contains(dp.getPartNo())))) {
flagHslt = true;
break;
}
}
if (flagHslt) {
JSONObject dossierFileObj = JSONFactoryUtil.createJSONObject();
dossierFileObj.put(DossierFileTerm.REFERENCE_UID, df.getReferenceUid());
dossierFilesArr.put(dossierFileObj);
}
}
}
// }
// }
}
}
else {
//Sync result files
if (Validator.isNotNull(dossier.getDossierNo())) {
payloadObject.put(DossierTerm.DOSSIER_NO, dossier.getDossierNo());
}
}
if (actionConfig.getSyncType() == DossierSyncTerm.SYNCTYPE_REQUEST ||
actionConfig.getSyncType() == DossierSyncTerm.SYNCTYPE_INFORM) {
payloadObject.put(DossierTerm.CONSTANT_DOSSIER_FILES, dossierFilesArr);
if (Validator.isNotNull(proAction.getReturnDossierFiles())) {
List<DossierFile> lsDossierFile = lstFiles;
dossierFilesArr = JSONFactoryUtil.createJSONArray();
// check return file
List<String> returnDossierFileTemplateNos = ListUtil
.toList(StringUtil.split(proAction.getReturnDossierFiles()));
for (DossierFile dossierFile : lsDossierFile) {
if (returnDossierFileTemplateNos.contains(dossierFile.getFileTemplateNo())) {
JSONObject dossierFileObj = JSONFactoryUtil.createJSONObject();
dossierFileObj.put(DossierFileTerm.REFERENCE_UID, dossierFile.getReferenceUid());
dossierFilesArr.put(dossierFileObj);
}
}
payloadObject.put(DossierTerm.CONSTANT_DOSSIER_FILES, dossierFilesArr);
}
List<DossierDocument> lstDossierDocuments = dossierDocumentLocalService.getDossierDocumentList(dossier.getDossierId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS);
JSONArray dossierDocumentArr = JSONFactoryUtil.createJSONArray();
for (DossierDocument dossierDocument : lstDossierDocuments) {
JSONObject dossierDocumentObj = JSONFactoryUtil.createJSONObject();
dossierDocumentObj.put(DossierDocumentTerm.REFERENCE_UID, dossierDocument.getReferenceUid());
dossierDocumentArr.put(dossierDocumentObj);
}
payloadObject.put(DossierTerm.CONSTANT_DOSSIER_FILES, dossierFilesArr);
payloadObject.put(DossierTerm.CONSTANT_DOSSIER_DOC, dossierDocumentArr);
//Put dossier note
payloadObject.put(DossierTerm.DOSSIER_NOTE, dossier.getDossierNote());
//Put dossier note
payloadObject.put(DossierTerm.SUBMIT_DATE, dossier.getSubmitDate() != null ? dossier.getSubmitDate().getTime() : 0);
// _log.info("Flag changed: " + flagChanged);
payloadObject = DossierActionUtils.buildChangedPayload(payloadObject, flagChanged, dossier);
//Always inform due date
if (actionConfig.getSyncType() == DossierSyncTerm.SYNCTYPE_INFORM && Validator.isNotNull(dossier.getDueDate())) {
payloadObject.put(DossierTerm.DUE_DATE, dossier.getDueDate().getTime());
}
if (actionConfig.getSyncType() == DossierSyncTerm.SYNCTYPE_INFORM && Validator.isNotNull(dossier.getReceiveDate())) {
payloadObject.put(DossierTerm.RECEIVE_DATE, dossier.getReceiveDate().getTime());
}
if (Validator.isNotNull(dossier.getServerNo())
&& dossier.getServerNo().split(StringPool.COMMA).length > 1) {
String serverNo = dossier.getServerNo().split(StringPool.COMMA)[0].split(StringPool.AT)[0];
dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid,
dossierAction.getPrimaryKey(), actionCode, proAction.getActionName(), actionUser, actionNote,
syncType, actionConfig.getInfoType(), payloadObject.toJSONString(), serverNo, state);
}
else {
dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid,
dossierAction.getPrimaryKey(), actionCode, proAction.getActionName(), actionUser, actionNote,
syncType, actionConfig.getInfoType(), payloadObject.toJSONString(), dossier.getServerNo(), state);
}
//Gửi thông tin hồ sơ để tra cứu
if (state == DossierSyncTerm.STATE_NOT_SYNC
&& actionConfig != null && actionConfig.getEventType() == ActionConfigTerm.EVENT_TYPE_SENT
&& OpenCPSConfigUtil.isPublishEventEnable()) {
publishEvent(dossier, context, dossierAction.getDossierActionId());
}
}
else if (actionConfig.getSyncType() == DossierSyncTerm.SYNCTYPE_INFORM_DOSSIER) {
if (Validator.isNotNull(dossier.getDossierNo())) {
payloadObject.put(DossierTerm.DOSSIER_NO, dossier.getDossierNo());
}
//
payloadObject.put("dossierFiles", dossierFilesArr);
if (Validator.isNotNull(proAction.getReturnDossierFiles())) {
List<DossierFile> lsDossierFile = lstFiles;
dossierFilesArr = JSONFactoryUtil.createJSONArray();
// check return file
List<String> returnDossierFileTemplateNos = ListUtil
.toList(StringUtil.split(proAction.getReturnDossierFiles()));
for (DossierFile dossierFile : lsDossierFile) {
if (returnDossierFileTemplateNos.contains(dossierFile.getFileTemplateNo())) {
JSONObject dossierFileObj = JSONFactoryUtil.createJSONObject();
dossierFileObj.put(DossierFileTerm.REFERENCE_UID, dossierFile.getReferenceUid());
dossierFilesArr.put(dossierFileObj);
}
}
payloadObject.put("dossierFiles", dossierFilesArr);
}
payloadObject = DossierActionUtils.buildChangedPayload(payloadObject, flagChanged, dossier);
if (Validator.isNotNull(dossier.getServerNo())
&& dossier.getServerNo().split(StringPool.COMMA).length > 1) {
String serverNo = dossier.getServerNo().split(StringPool.COMMA)[0].split(StringPool.AT)[0];
dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid,
dossierAction.getPrimaryKey(), actionCode, proAction.getActionName(), actionUser, actionNote,
syncType, actionConfig.getInfoType(), payloadObject.toJSONString(), serverNo, state);
}
else {
dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid,
dossierAction.getPrimaryKey(), actionCode, proAction.getActionName(), actionUser, actionNote,
syncType, actionConfig.getInfoType(), payloadObject.toJSONString(), dossier.getServerNo(), state);
}
}
}
else if (actionConfig != null && actionConfig.getEventType() == ActionConfigTerm.EVENT_TYPE_SENT
&& OpenCPSConfigUtil.isPublishEventEnable()) {
publishEvent(dossier, context, dossierAction.getDossierActionId());
}
}
private void doMappingAction(long groupId, long userId, Employee employee, Dossier dossier,
ActionConfig actionConfig, String actionUser, String actionNote, String payload, String assignUsers,
String payment,ServiceContext context) throws PortalException, Exception {
if (Validator.isNotNull(actionConfig) && Validator.isNotNull(actionConfig.getMappingAction())) {
ActionConfig mappingConfig = actionConfigLocalService.getByCode(groupId, actionConfig.getMappingAction());
if (dossier.getOriginDossierId() != 0) {
Dossier hslt = dossierLocalService.fetchDossier(dossier.getOriginDossierId());
ProcessOption optionHslt = getProcessOption(hslt.getServiceCode(), hslt.getGovAgencyCode(),
hslt.getDossierTemplateNo(), groupId);
ProcessAction actionHslt = getProcessAction(groupId, hslt.getDossierId(), hslt.getReferenceUid(), actionConfig.getMappingAction(), optionHslt.getServiceProcessId());
String actionUserHslt = actionUser;
if (employee != null) {
actionUserHslt = actionUser;
}
if (DossierTerm.DOSSIER_STATUS_NEW.equals(hslt.getDossierStatus())) {
Date now = new Date();
hslt.setSubmitDate(now);
hslt = dossierLocalService.updateDossier(hslt);
try {
JSONObject payloadObj = JSONFactoryUtil.createJSONObject(payload);
payloadObj.put(DossierTerm.SUBMIT_DATE, now.getTime());
payload = payloadObj.toJSONString();
}
catch (JSONException e) {
_log.debug(e);
}
}
doAction(groupId, userId, hslt, optionHslt, actionHslt, actionConfig.getMappingAction(), actionUserHslt, actionNote, payload, assignUsers, payment, mappingConfig.getSyncType(), context);
}
else {
Dossier originDossier = dossierLocalService.getByOrigin(groupId, dossier.getDossierId());
if (originDossier != null) {
ProcessOption optionOrigin = getProcessOption(originDossier.getServiceCode(), originDossier.getGovAgencyCode(),
originDossier.getDossierTemplateNo(), groupId);
ProcessAction actionOrigin = getProcessAction(groupId, originDossier.getDossierId(), originDossier.getReferenceUid(), actionConfig.getMappingAction(), optionOrigin.getServiceProcessId());
doAction(groupId, userId, originDossier, optionOrigin, actionOrigin, actionConfig.getMappingAction(), actionUser, actionNote, payload, assignUsers, payment, mappingConfig.getSyncType(), context);
}
}
}
}
private DossierAction createActionAndAssignUser(long groupId, long userId, ProcessStep curStep,
ActionConfig actionConfig, DossierAction dossierAction, DossierAction previousAction,
ProcessAction proAction, Dossier dossier, String actionCode, String actionUser, String actionNote,
String payload, String assignUsers, String payment, ServiceProcess serviceProcess, ProcessOption option,
Map<String, Boolean> flagChanged, Integer dateOption, ServiceContext context) throws PortalException {
int actionOverdue = getActionDueDate(groupId, dossier.getDossierId(), dossier.getReferenceUid(), proAction.getProcessActionId());
String actionName = proAction.getActionName();
String prevStatus = dossier.getDossierStatus();
if (curStep != null) {
String curStatus = curStep.getDossierStatus();
String curSubStatus = curStep.getDossierSubStatus();
String stepCode = curStep.getStepCode();
String stepName = curStep.getStepName();
String stepInstruction = curStep.getStepInstruction();
String sequenceNo = curStep.getSequenceNo();
JSONObject jsonDataStatusText = getStatusText(groupId, DOSSIER_SATUS_DC_CODE, curStatus, curSubStatus);
String fromStepCode = previousAction != null ? previousAction.getStepCode() : StringPool.BLANK;
String fromStepName = previousAction != null ? previousAction.getStepName() : StringPool.BLANK;
String fromSequenceNo = previousAction != null ? previousAction.getSequenceNo() : StringPool.BLANK;
int state = DossierActionTerm.STATE_WAITING_PROCESSING;
int eventStatus = (actionConfig != null ? (actionConfig.getEventType() == ActionConfigTerm.EVENT_TYPE_NOT_SENT ? DossierActionTerm.EVENT_STATUS_NOT_CREATED : DossierActionTerm.EVENT_STATUS_WAIT_SENDING) : DossierActionTerm.EVENT_STATUS_NOT_CREATED);
boolean rollbackable = false;
if (actionConfig != null) {
if (actionConfig.getRollbackable()) {
rollbackable = true;
}
else {
}
}
else {
if (proAction.isRollbackable()) {
rollbackable = true;
}
else {
}
}
dossierAction = dossierActionLocalService.updateDossierAction(groupId, 0, dossier.getDossierId(),
serviceProcess.getServiceProcessId(), dossier.getDossierActionId(),
fromStepCode, fromStepName, fromSequenceNo,
actionCode, actionUser, actionName, actionNote, actionOverdue,
stepCode, stepName,
sequenceNo,
null, 0l, payload, stepInstruction,
state, eventStatus, rollbackable,
context);
dossier.setDossierActionId(dossierAction.getDossierActionId());
String dossierNote = StringPool.BLANK;
if (dossierAction != null) {
dossierNote = dossierAction.getActionNote();
if (Validator.isNotNull(dossierNote)) {
dossierNote = dossierAction.getStepInstruction();
}
}
//Update previous action nextActionId
Date now = new Date();
if (previousAction != null && dossierAction != null) {
previousAction.setNextActionId(dossierAction.getDossierActionId());
previousAction.setState(DossierActionTerm.STATE_ALREADY_PROCESSED);
previousAction.setModifiedDate(now);
previousAction = dossierActionLocalService.updateDossierAction(previousAction);
}
updateStatus(dossier, curStatus,
jsonDataStatusText != null ? jsonDataStatusText.getString(curStatus) : StringPool.BLANK, curSubStatus,
jsonDataStatusText != null ? jsonDataStatusText.getString(curSubStatus) : StringPool.BLANK, curStep.getLockState(), dossierNote, context);
//Cập nhật cờ đồng bộ ngày tháng sang các hệ thống khác
Map<String, Boolean> resultFlagChanged = updateProcessingDate(dossierAction, previousAction, curStep,
dossier, curStatus, curSubStatus, prevStatus,
dateOption != null ? dateOption : (actionConfig != null ? actionConfig.getDateOption() : 0), option, serviceProcess, context);
for (Map.Entry<String, Boolean> entry : resultFlagChanged.entrySet()) {
flagChanged.put(entry.getKey(), entry.getValue());
}
dossierAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId());
}
//Thiết lập quyền thao tác hồ sơ
int allowAssignUser = proAction.getAllowAssignUser();
JSONArray assignedUsersArray = JSONFactoryUtil.createJSONArray(assignUsers);
if (allowAssignUser != ProcessActionTerm.NOT_ASSIGNED) {
if (Validator.isNotNull(assignUsers) && assignedUsersArray.length() > 0) {
// JSONArray assignedUsersArray = JSONFactoryUtil.createJSONArray(assignUsers);
assignDossierActionUser(dossier, allowAssignUser,
dossierAction, userId, groupId, proAction.getAssignUserId(),
assignedUsersArray);
if (OpenCPSConfigUtil.isNotificationEnable()) {
createNotificationSMS(userId, groupId, dossier, assignedUsersArray, dossierAction, context);
}
} else {
initDossierActionUser(proAction, dossier, allowAssignUser, dossierAction, userId, groupId,
proAction.getAssignUserId());
}
} else {
//Process role as step
if (curStep != null && Validator.isNotNull(curStep.getRoleAsStep())) {
copyRoleAsStep(curStep, dossier);
}
else {
initDossierActionUser(proAction, dossier, allowAssignUser, dossierAction, userId, groupId,
proAction.getAssignUserId());
}
}
return dossierAction;
}
public static final String CACHE_ServiceProcess = "ServiceProcess";
public static final String CREATE_DOCUMENT = "CREATE_DOCUMENT";
public static final String CHANGE_DATE = "CHANGE_DATE";
public static final String CALL_API = "CALL_API";
private DossierAction doActionInsideProcess(long groupId, long userId, Dossier dossier, ActionConfig actionConfig, ProcessOption option, ProcessAction proAction,
String actionCode, String actionUser, String actionNote, String payload, String assignUsers,
String payment,
int syncType,
ServiceContext context) throws PortalException, SystemException, Exception {
context.setUserId(userId);
DossierAction dossierAction = null;
Map<String, Boolean> flagChanged = new HashMap<>();
JSONObject payloadObject = JSONFactoryUtil.createJSONObject();
User user = userLocalService.fetchUser(userId);
String dossierStatus = dossier.getDossierStatus().toLowerCase();
Employee employee = null;
Serializable employeeCache = cache.getFromCache(CacheTerm.MASTER_DATA_EMPLOYEE, groupId +StringPool.UNDERLINE+ userId);
// _log.info("EMPLOYEE CACHE: " + employeeCache);
if (employeeCache == null) {
employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId);
if (employee != null) {
cache.addToCache(CacheTerm.MASTER_DATA_EMPLOYEE,
groupId + StringPool.UNDERLINE + userId, (Serializable) employee,
ttl);
}
} else {
employee = (Employee) employeeCache;
}
try {
payloadObject = JSONFactoryUtil.createJSONObject(payload);
}
catch (JSONException e) {
_log.debug(e);
}
if (Validator.isNotNull(dossierStatus)) {
if(!ReadFilePropertiesUtils.get(ConstantUtils.STATUS_NEW).equals(dossierStatus)) {
} else if (dossier.getOriginality() == DossierTerm.ORIGINALITY_DVCTT) {
dossier.setSubmitDate(new Date());
}
}
long dossierId = dossier.getDossierId();
ServiceProcess serviceProcess = null;
DossierAction previousAction = null;
if (dossier.getDossierActionId() != 0) {
previousAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId());
}
//Cập nhật thông tin hồ sơ dựa vào payload truyền vào khi thực hiện thao tác
if (Validator.isNotNull(payload)) {
JSONObject pl = payloadObject;
updateDossierPayload(dossier, pl);
}
if ((option != null || previousAction != null) && proAction != null) {
long serviceProcessId = (option != null ? option.getServiceProcessId() : previousAction.getServiceProcessId());
Serializable serviceProcessCache = cache.getFromCache(CACHE_ServiceProcess, groupId +StringPool.UNDERLINE+ serviceProcessId);
if (serviceProcessCache == null) {
serviceProcess = serviceProcessLocalService.fetchServiceProcess(serviceProcessId);
if (serviceProcess != null) {
cache.addToCache(CACHE_ServiceProcess,
groupId +StringPool.UNDERLINE+ serviceProcessId, (Serializable) serviceProcess,
ttl);
}
} else {
serviceProcess = (ServiceProcess) serviceProcessCache;
}
String paymentFee = StringPool.BLANK;
String postStepCode = proAction.getPostStepCode();
String postAction = proAction.getPostAction();
boolean flagDocument = false;
Integer dateOption = null;
String documentTypeList = StringPool.BLANK;
if (Validator.isNotNull(postAction)) {
JSONObject jsonPostData = JSONFactoryUtil.createJSONObject(postAction);
if (jsonPostData != null) {
JSONObject jsonDocument = JSONFactoryUtil.createJSONObject(jsonPostData.getString(CREATE_DOCUMENT));
if (jsonDocument != null && jsonDocument.has(DossierDocumentTerm.DOCUMENT_TYPE)) {
documentTypeList = jsonDocument.getString(DossierDocumentTerm.DOCUMENT_TYPE);
flagDocument = true;
}
JSONObject jsonChangeDate = JSONFactoryUtil.createJSONObject(jsonPostData.getString(CHANGE_DATE));
if (jsonChangeDate != null && jsonChangeDate.has(DossierTerm.DATE_OPTION)) {
String strDateOption = jsonChangeDate.getString(DossierTerm.DATE_OPTION);
if (Validator.isNotNull(strDateOption)) {
dateOption = Integer.valueOf(strDateOption);
}
}
JSONObject jsonCallAPI = JSONFactoryUtil.createJSONObject(jsonPostData.getString(CALL_API));
if (jsonCallAPI != null && jsonCallAPI.has(DossierTerm.SERVER_NO)) {
String serverNo = jsonCallAPI.getString(DossierTerm.SERVER_NO);
if (Validator.isNotNull(serverNo)) {
ServerConfig serverConfig = ServerConfigLocalServiceUtil.getByCode(groupId, serverNo);
if (serverConfig != null) {
JSONObject configObj = JSONFactoryUtil.createJSONObject(serverConfig.getConfigs());
//
String method = StringPool.BLANK;
if (configObj != null && configObj.has(KeyPayTerm.METHOD)) {
method = configObj.getString(KeyPayTerm.METHOD);
System.out.println("method: "+method);
}
//params
JSONObject jsonParams = null;
if (configObj != null && configObj.has(KeyPayTerm.PARAMS)) {
jsonParams = JSONFactoryUtil.createJSONObject(configObj.getString(KeyPayTerm.PARAMS));
}
if (jsonParams != null) {
JSONObject jsonHeader = JSONFactoryUtil.createJSONObject(jsonParams.getString(KeyPayTerm.HEADER));
JSONObject jsonBody = JSONFactoryUtil.createJSONObject(jsonParams.getString(KeyPayTerm.BODY));
String authStrEnc = StringPool.BLANK;
String apiUrl = StringPool.BLANK;
StringBuilder sb = new StringBuilder();
try {
URL urlVal = null;
String groupIdRequest = StringPool.BLANK;
StringBuilder postData = new StringBuilder();
Iterator<?> keys = jsonBody.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (!StringPool.BLANK.equals(postData.toString())) {
postData.append(StringPool.AMPERSAND);
}
postData.append(key);
postData.append(StringPool.EQUAL);
postData.append(jsonBody.get(key));
}
if (configObj.has(SyncServerTerm.SERVER_USERNAME)
&& configObj.has(SyncServerTerm.SERVER_SECRET)
&& Validator.isNotNull(configObj.getString(SyncServerTerm.SERVER_USERNAME))
&& Validator.isNotNull(configObj.getString(SyncServerTerm.SERVER_SECRET))) {
authStrEnc = Base64.getEncoder()
.encodeToString((configObj.getString(SyncServerTerm.SERVER_USERNAME)
+ StringPool.COLON + configObj.getString(SyncServerTerm.SERVER_SECRET))
.getBytes());
}
if (configObj.has(SyncServerTerm.SERVER_URL)) {
apiUrl = configObj.getString(SyncServerTerm.SERVER_URL);
if (apiUrl.contains("{_dossierId}")) {
apiUrl = apiUrl.replace("{_dossierId}", String.valueOf(dossierId));
}
if (apiUrl.contains("{_dossierCounter}")) {
apiUrl = apiUrl.replace("{_dossierCounter}", String.valueOf(dossier.getDossierCounter()));
}
}
if (configObj.has(SyncServerTerm.SERVER_GROUP_ID)) {
groupIdRequest = configObj.getString(SyncServerTerm.SERVER_GROUP_ID);
}
if (jsonHeader != null && Validator.isNotNull(groupIdRequest)) {
if (jsonHeader.has(Field.GROUP_ID)) {
groupIdRequest = String.valueOf(jsonHeader.getLong(Field.GROUP_ID));
}
}
if (HttpMethods.GET.equals(method)) {
if (Validator.isNotNull(postData.toString())) {
urlVal = new URL(apiUrl + StringPool.QUESTION + postData.toString());
} else {
urlVal = new URL(apiUrl);
}
} else {
urlVal = new URL(apiUrl);
}
_log.debug("API URL: " + apiUrl);
java.net.HttpURLConnection conn = (java.net.HttpURLConnection) urlVal
.openConnection();
conn.setRequestProperty(Field.GROUP_ID, groupIdRequest);
conn.setRequestMethod(method);
conn.setRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
if (Validator.isNotNull(authStrEnc)) {
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, "Basic " + authStrEnc);
}
if (HttpMethods.POST.equals(method) || HttpMethods.PUT.equals(method)) {
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
conn.setRequestProperty(HttpHeaders.CONTENT_LENGTH,
StringPool.BLANK + Integer.toString(postData.toString().getBytes().length));
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
_log.debug("POST DATA: " + postData.toString());
OutputStream os = conn.getOutputStream();
os.write(postData.toString().getBytes());
os.close();
}
BufferedReader brf = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
int cp;
while ((cp = brf.read()) != -1) {
sb.append((char) cp);
}
_log.debug("RESULT PROXY: " + sb.toString());
} catch (IOException e) {
_log.debug(e);
// _log.debug("Something went wrong while reading/writing in stream!!");
}
}
}
}
}
}
}
//Xử lý phiếu thanh toán
processPaymentFile(groupId, userId, payment, option, proAction, previousAction, dossier, context);
//Bước sau không có thì mặc định quay lại bước trước đó
if (Validator.isNull(postStepCode)) {
postStepCode = previousAction.getFromStepCode();
ProcessStep backCurStep = processStepLocalService.fetchBySC_GID(postStepCode, groupId, serviceProcessId);
String curStatus = backCurStep.getDossierStatus();
String curSubStatus = backCurStep.getDossierSubStatus();
JSONObject jsonDataStatusText = getStatusText(groupId, ReadFilePropertiesUtils.get(ConstantUtils.DOSSIER_STATUS), curStatus, curSubStatus);
//update dossierStatus
dossier = DossierLocalServiceUtil.updateStatus(groupId, dossierId, dossier.getReferenceUid(), curStatus,
jsonDataStatusText != null ? jsonDataStatusText.getString(curStatus) : StringPool.BLANK, curSubStatus,
jsonDataStatusText != null ? jsonDataStatusText.getString(curSubStatus) : StringPool.BLANK, backCurStep.getLockState(), dossier.getDossierNote(), context);
dossier.setDossierActionId(previousAction.getPreviousActionId());
dossierLocalService.updateDossier(dossier);
// chỉ cán bộ thao tác trước đó có moderator = 1
List<DossierActionUser> lstDaus =
DossierActionUserLocalServiceUtil.getByDossierAndStepCode(
dossier.getDossierId(), previousAction.getStepCode());
for (DossierActionUser dau : lstDaus) {
if (dau.getUserId() == backCurStep.getUserId()) {
dau.setModerator(1);
} else {
dau.setModerator(0);
}
DossierActionUserLocalServiceUtil.updateDossierActionUser(dau);
}
return previousAction;
}
ProcessStep curStep = processStepLocalService.fetchBySC_GID(postStepCode, groupId, serviceProcessId);
//Kiểm tra cấu hình cần tạo hồ sơ liên thông
Dossier hsltDossier = createCrossDossier(groupId, proAction, curStep, previousAction, employee, dossier, user, payloadObject, context);
if (Validator.isNotNull(proAction.getCreateDossiers())) {
if (Validator.isNull(hsltDossier)) {
return null;
}
}
//Cập nhật hành động và quyền người dùng với hồ sơ
dossierAction = createActionAndAssignUser(groupId, userId, curStep, actionConfig, dossierAction,
previousAction, proAction, dossier, actionCode, actionUser, actionNote, payload, assignUsers,
paymentFee, serviceProcess, option, flagChanged, dateOption, context);
// dossier = dossierLocalService.updateDossier(dossier);
//Tạo văn bản đính kèm
if (OpenCPSConfigUtil.isDossierDocumentEnable()) {
if (!flagDocument) {
createDossierDocument(groupId, userId, actionConfig, dossier, dossierAction, payloadObject, employee, user, context);
} else {
createDossierDocumentPostAction(groupId, userId, dossier, dossierAction,
payloadObject, employee, user, documentTypeList, context);
}
}
//Kiểm tra xem có gửi dịch vụ vận chuyển hay không
if (proAction.getPreCondition().toLowerCase().contains(ProcessActionTerm.PRECONDITION_SEND_VIAPOSTAL)) {
vnpostEvent(dossier, dossierAction.getDossierActionId());
}
if (proAction.getPreCondition().toLowerCase().contains(ProcessActionTerm.PRECONDITION_SEND_COLLECTION_VNPOST)) {
collectVnpostEvent(dossier, dossierAction.getDossierActionId());
}
if (proAction.getPreCondition().toLowerCase().contains(ProcessActionTerm.PRECONDITION_REC_COLLECTION_VNPOST)
&& dossier.getVnpostalStatus() == VnpostCollectionTerm.VNPOSTAL_STAUS_2) {
dossier.setVnpostalStatus(VnpostCollectionTerm.VNPOSTAL_STAUS_3);
}
}
else {
}
//Create notification
if (OpenCPSConfigUtil.isNotificationEnable()) {
JSONObject notificationPayload = buildNotificationPayload(dossier, payloadObject);
createNotificationQueue(user, groupId, dossier, proAction, actionConfig, dossierAction, notificationPayload, context);
}
//Create subcription
createSubcription(userId, groupId, dossier, actionConfig, dossierAction, context);
//Tạo thông tin đồng bộ hồ sơ
createDossierSync(groupId, userId, actionConfig, proAction, dossierAction, dossier, syncType, option, payloadObject, flagChanged, actionCode, actionUser, actionNote, serviceProcess, context);
JSONObject newObj = JSONFactoryUtil.createJSONObject(payload);
if (payloadObject.has(DossierTerm.CROSS_DOSSIER)) {
newObj.put(DossierTerm.CROSS_DOSSIER, payloadObject.getJSONObject(DossierTerm.CROSS_DOSSIER));
}
//Add by TrungNT - Fix tam theo y/k cua a TrungDK va Duantv
if (dossier.isOnline() && proAction != null && "listener".equals(proAction.getAutoEvent().toString()) && OpenCPSConfigUtil.isPublishEventEnable()) {
publishEvent(dossier, context, dossierAction.getDossierActionId());
}
//Thực hiện thao tác lên hồ sơ gốc hoặc hồ sơ liên thông trong trường hợp có cấu hình mappingAction
doMappingAction(groupId, userId, employee, dossier, actionConfig, actionUser, actionNote, newObj.toJSONString(), assignUsers, payment, context);
//Update dossier
dossierLocalService.updateDossier(dossier);
// Indexer<Dossier> indexer = IndexerRegistryUtil
// .nullSafeGetIndexer(Dossier.class);
// indexer.reindex(dossier);
return dossierAction;
}
private JSONObject buildNotificationPayload(Dossier dossier, JSONObject payloadObject) {
JSONObject returnObject;
try {
returnObject = JSONFactoryUtil.createJSONObject(payloadObject.toJSONString());
_log.debug("=======> BUILD NOTIFICATION QUEUE SMS PAYLOAD");
if (dossier.getReceiveDate() != null) {
returnObject.put(DossierTerm.RECEIVE_DATE, APIDateTimeUtils.convertDateToString(dossier.getReceiveDate(), APIDateTimeUtils._NORMAL_DATE_TIME));
_log.debug("=======> BUILD NOTIFICATION QUEUE SMS RECEIVE DATE: " + returnObject.get(DossierTerm.RECEIVE_DATE));
}
else {
returnObject.put(DossierTerm.RECEIVE_DATE, StringPool.BLANK);
}
if (!returnObject.has(DossierTerm.DOSSIER_NO)) {
if (Validator.isNotNull(dossier.getDossierNo())) {
returnObject.put(DossierTerm.DOSSIER_NO, dossier.getDossierNo());
}
}
int durationUnit = dossier.getDurationUnit();
double durationCount = dossier.getDurationCount();
String durationText = StringPool.BLANK;
if (durationUnit == DossierTerm.DURATION_UNIT_DAY) {
durationText = String.valueOf(durationCount);
}
else if (durationUnit == DossierTerm.DURATION_UNIT_HOUR) {
durationText = String.valueOf(durationCount * 1.0 / DossierTerm.WORKING_HOUR_PER_DAY);
}
returnObject.put(DossierTerm.DURATION_TEXT, durationText);
if (!returnObject.has(DossierTerm.GOV_AGENCY_NAME)) {
returnObject.put(DossierTerm.GOV_AGENCY_NAME, dossier.getGovAgencyName());
}
if (!returnObject.has(DossierTerm.POSTAL_ADDRESS)) {
returnObject.put(DossierTerm.POSTAL_ADDRESS, dossier.getPostalAddress());
}
PaymentFile pf = paymentFileLocalService.getByDossierId(dossier.getGroupId(), dossier.getDossierId());
if (pf != null) {
if (!returnObject.has(PaymentFileTerm.PAYMENT_AMOUNT)) {
returnObject.put(PaymentFileTerm.PAYMENT_AMOUNT, String.valueOf(pf.getPaymentAmount()));
}
}
return returnObject;
} catch (JSONException e) {
_log.debug(e);
return payloadObject;
}
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public DossierAction doAction(long groupId, long userId, Dossier dossier, ProcessOption option, ProcessAction proAction,
String actionCode, String actionUser, String actionNote, String payload, String assignUsers,
String payment,
int syncType,
ServiceContext context) throws PortalException, SystemException, Exception {
context.setUserId(userId);
DossierAction dossierAction = null;
ActionConfig actionConfig = null;
actionConfig = actionConfigLocalService.getByCode(groupId, actionCode);
if (actionConfig != null && !actionConfig.getInsideProcess()) {
dossierAction = doActionOutsideProcess(groupId, userId, dossier, actionConfig, option, proAction, actionCode, actionUser, actionNote, payload, assignUsers, payment, syncType, context);
}
else {
dossierAction = doActionInsideProcess(groupId, userId, dossier, actionConfig, option, proAction, actionCode, actionUser, actionNote, payload, assignUsers, payment, syncType, context);
}
return dossierAction;
}
private void createNotificationQueue(User user, long groupId, Dossier dossier, ProcessAction proAction, ActionConfig actionConfig,
DossierAction dossierAction, JSONObject payloadObject, ServiceContext context) throws PortalException {
// DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId());
// User u = UserLocalServiceUtil.fetchUser(userId);
JSONObject payloadObj = JSONFactoryUtil.createJSONObject(payloadObject.toJSONString());
try {
JSONObject dossierObj = JSONFactoryUtil.createJSONObject(
JSONFactoryUtil.looseSerialize(dossier));
dossierObj = buildNotificationPayload(dossier, dossierObj);
payloadObj.put(
KeyPayTerm.DOSSIER, dossierObj);
// payloadObj.put(
// KeyPayTerm.DOSSIER, JSONFactoryUtil.createJSONObject(
// JSONFactoryUtil.looseSerialize(dossier)));
if (dossierAction != null) {
payloadObj.put(DossierActionTerm.ACTION_CODE, dossierAction.getActionCode());
payloadObj.put(DossierActionTerm.ACTION_USER, dossierAction.getActionUser());
payloadObj.put(DossierActionTerm.ACTION_NAME, dossierAction.getActionName());
payloadObj.put(DossierActionTerm.ACTION_NOTE, dossierAction.getActionNote());
}
//
if (payloadObject != null) {
Iterator<String> keys = payloadObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (PAYLOAD_KEY_COMPLEMENT_DATE.equalsIgnoreCase(key)) {
Long complementDate = payloadObject.getLong(PAYLOAD_KEY_COMPLEMENT_DATE);
if (complementDate != null && complementDate > 0) {
String strDate = APIDateTimeUtils.convertDateToString(new Date(complementDate),
APIDateTimeUtils._NORMAL_PARTTERN);
payloadObj.put(key, strDate);
}
} else {
payloadObj.put(key, payloadObject.getString(key));
}
}
}
}
catch (Exception e) {
_log.error(e);
}
String notificationType = StringPool.BLANK;
String preCondition = StringPool.BLANK;
if (actionConfig != null && Validator.isNotNull(actionConfig.getNotificationType())) {
_log.info("NOTIFICATION TYPE: " + actionConfig.getNotificationType());
if (actionConfig.getNotificationType().contains(StringPool.AT)) {
String[] split = StringUtil.split(actionConfig.getNotificationType(), StringPool.AT);
if (split.length == 2) {
notificationType = split[0];
preCondition = split[1];
}
}
else {
notificationType = actionConfig.getNotificationType();
}
_log.info("NOTIFICATION TYPE: " + notificationType + ", CONDITION: " + preCondition);
boolean isSendSMS = NotificationUtil.isSendSMS(preCondition);
boolean isSendEmail = NotificationUtil.isSendEmail(preCondition);
boolean isSendNotiSMS = true;
boolean isSendNotiEmail = true;
if (Validator.isNotNull(preCondition)) {
if (!DossierMgtUtils.checkPreCondition(new String[] { preCondition } , dossier, null)) {
if (isSendSMS) {
isSendNotiSMS = false;
isSendNotiEmail = true;
}
else {
isSendNotiSMS = false;
isSendNotiEmail = false;
}
}
else {
isSendNotiSMS = isSendSMS;
isSendNotiEmail = isSendEmail;
}
}
// Notificationtemplate notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, actionConfig.getNotificationType());
Serializable notiCache = cache.getFromCache(CACHE_NOTIFICATION_TEMPLATE, groupId +StringPool.UNDERLINE+ notificationType);
Notificationtemplate notiTemplate = null;
// notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, actionConfig.getNotificationType());
if (notiCache == null) {
notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, notificationType);
if (notiTemplate != null) {
cache.addToCache(CACHE_NOTIFICATION_TEMPLATE,
groupId +StringPool.UNDERLINE+ notificationType, (Serializable) notiTemplate,
ttl);
}
} else {
notiTemplate = (Notificationtemplate) notiCache;
}
Date now = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(now);
if (notiTemplate != null) {
if (KeyPayTerm.MINUTELY.equals(notiTemplate.getInterval())) {
cal.add(Calendar.MINUTE, notiTemplate.getExpireDuration());
}
else if (KeyPayTerm.HOURLY.equals(notiTemplate.getInterval())) {
cal.add(Calendar.HOUR, notiTemplate.getExpireDuration());
}
else {
cal.add(Calendar.MINUTE, notiTemplate.getExpireDuration());
}
Date expired = cal.getTime();
if (notificationType.startsWith(KeyPayTerm.APLC)) {
if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA
|| dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) {
try {
// Applicant applicant = ApplicantLocalServiceUtil.fetchByAppId(dossier.getApplicantIdNo());
List<Applicant> applicants = ApplicantLocalServiceUtil.findByAppIds(dossier.getApplicantIdNo());
Applicant foundApplicant = (applicants.isEmpty() ? null : applicants.get(0));
for (Applicant applicant : applicants) {
long toUserId = (applicant != null ? applicant.getMappingUserId() : 0l);
if (toUserId != 0) {
foundApplicant = applicant;
break;
}
}
if (foundApplicant != null) {
JSONObject filesAttach = getFileAttachMailForApplicant(dossier, proAction);
payloadObj.put("filesAttach", filesAttach);
String fromFullName = user.getFullName();
if (Validator.isNotNull(OpenCPSConfigUtil.getMailToApplicantFrom())) {
fromFullName = OpenCPSConfigUtil.getMailToApplicantFrom();
}
NotificationQueueLocalServiceUtil.addNotificationQueue(
user.getUserId(), groupId,
notificationType,
Dossier.class.getName(),
String.valueOf(dossier.getDossierId()),
payloadObj.toJSONString(),
fromFullName,
dossier.getApplicantName(),
foundApplicant.getMappingUserId(),
isSendNotiEmail ? dossier.getContactEmail() : StringPool.BLANK,
isSendNotiSMS ? dossier.getContactTelNo() : StringPool.BLANK,
now,
expired,
context);
}
} catch (NoSuchUserException e) {
_log.debug(e);
}
}
}
else if (notificationType.startsWith(KeyPayTerm.USER)) {
}
else if (notificationType.startsWith("EMPL")) {
_log.debug("ADD NOTI EMPL");
List<DossierActionUser> lstDaus = DossierActionUserLocalServiceUtil.getByDossierAndStepCode(dossier.getDossierId(), dossierAction.getStepCode());
_log.debug("ADD NOTI LIST DAU: " + lstDaus.size());
for (DossierActionUser dau : lstDaus) {
_log.debug("ADD NOTI DAU: " + dau.getAssigned());
if (dau.getAssigned() == DossierActionUserTerm.ASSIGNED_TH || dau.getAssigned() == DossierActionUserTerm.ASSIGNED_PH) {
// Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId());
Serializable employeeCache = cache.getFromCache("Employee", groupId +"_"+ dau.getUserId());
Employee employee = null;
// employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId());
if (employeeCache == null) {
employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId());
if (employee != null) {
cache.addToCache("Employee",
groupId +"_"+ dau.getUserId(), (Serializable) employee,
ttl);
}
} else {
employee = (Employee) employeeCache;
}
_log.debug("ADD NOTI EMPLOYEE: " + employee);
if (employee != null) {
String telNo = employee != null ? employee.getTelNo() : StringPool.BLANK;
String fullName = employee != null ? employee.getFullName() : StringPool.BLANK;
long start = System.currentTimeMillis();
_log.debug("BEFORE ADD NOTI EMPLOYEE: " + actionConfig.getNotificationType());
NotificationQueueLocalServiceUtil.addNotificationQueue(
user.getUserId(), groupId,
notificationType,
Dossier.class.getName(),
String.valueOf(dossier.getDossierId()),
payloadObj.toJSONString(),
user.getFullName(),
fullName,
dau.getUserId(),
employee.getEmail(),
telNo,
now,
expired,
context);
_log.debug("ADD NOTI QUEUE: " + (System.currentTimeMillis() - start));
}
}
}
}
}
}
// Notificationtemplate emplTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, NotificationTemplateTerm.EMPL_01);
Serializable emplCache = cache.getFromCache(CACHE_NOTIFICATION_TEMPLATE, groupId +StringPool.UNDERLINE+ NotificationTemplateTerm.EMPL_01);
//Notificationtemplate emplTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, NotificationTemplateTerm.EMPL_01);
Notificationtemplate emplTemplate = null;
if (emplCache == null) {
emplTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, NotificationTemplateTerm.EMPL_01);
if (emplTemplate != null) {
cache.addToCache(CACHE_NOTIFICATION_TEMPLATE,
groupId +StringPool.UNDERLINE+ actionConfig.getNotificationType(), (Serializable) emplTemplate,
ttl);
}
} else {
emplTemplate = (Notificationtemplate) emplCache;
}
Date now = new Date();
Calendar calEmpl = Calendar.getInstance();
calEmpl.setTime(now);
if (emplTemplate != null) {
if (KeyPayTerm.MINUTELY.equals(emplTemplate.getInterval())) {
calEmpl.add(Calendar.MINUTE, emplTemplate.getExpireDuration());
}
else if (KeyPayTerm.HOURLY.equals(emplTemplate.getInterval())) {
calEmpl.add(Calendar.HOUR, emplTemplate.getExpireDuration());
}
else {
calEmpl.add(Calendar.MINUTE, emplTemplate.getExpireDuration());
}
Date expired = calEmpl.getTime();
if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA
|| dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) {
try {
String stepCode = dossierAction.getStepCode();
StringBuilder buildX = new StringBuilder(stepCode);
if (stepCode.length() > 0) {
buildX.setCharAt(stepCode.length() - 1, 'x');
}
String stepCodeX = buildX.toString();
StepConfig stepConfig = StepConfigLocalServiceUtil.getByCode(groupId, dossierAction.getStepCode());
StepConfig stepConfigX = StepConfigLocalServiceUtil.getByCode(groupId, stepCodeX);
if ((stepConfig != null && stepConfig.getStepType() == StepConfigTerm.STEP_TYPE_DISPLAY_MENU_BY_PROCESSED)
|| (stepConfigX != null && stepConfigX.getStepType() == StepConfigTerm.STEP_TYPE_DISPLAY_MENU_BY_PROCESSED)) {
List<DossierActionUser> lstDaus = DossierActionUserLocalServiceUtil.getByDossierAndStepCode(dossier.getDossierId(), dossierAction.getStepCode());
for (DossierActionUser dau : lstDaus) {
if (dau.getAssigned() == DossierActionUserTerm.ASSIGNED_TH || dau.getAssigned() == DossierActionUserTerm.ASSIGNED_PH) {
// Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId());
Serializable employeeCache = cache.getFromCache(CacheTerm.MASTER_DATA_EMPLOYEE, groupId +StringPool.UNDERLINE+ dau.getUserId());
Employee employee = null;
// employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId());
if (employeeCache == null) {
employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId());
if (employee != null) {
cache.addToCache(CacheTerm.MASTER_DATA_EMPLOYEE,
groupId +StringPool.UNDERLINE+ dau.getUserId(), (Serializable) employee,
ttl);
}
} else {
employee = (Employee) employeeCache;
}
if (employee != null) {
String telNo = employee != null ? employee.getTelNo() : StringPool.BLANK;
String fullName = employee != null ? employee.getFullName() : StringPool.BLANK;
long start = System.currentTimeMillis();
NotificationQueueLocalServiceUtil.addNotificationQueue(
user.getUserId(), groupId,
NotificationTemplateTerm.EMPL_01,
Dossier.class.getName(),
String.valueOf(dossier.getDossierId()),
payloadObj.toJSONString(),
user.getFullName(),
fullName,
dau.getUserId(),
employee.getEmail(),
telNo,
now,
expired,
context);
_log.debug("ADD NOTI QUEUE: " + (System.currentTimeMillis() - start));
}
}
}
}
} catch (NoSuchUserException e) {
_log.error(e);
//_log.error(e);
// e.printStackTrace();
}
}
}
}
private void updateDossierPayload(Dossier dossier, JSONObject obj) {
if (obj.has(DossierTerm.DOSSIER_NOTE)) {
if (!obj.getString(DossierTerm.DOSSIER_NOTE).equals(dossier.getDossierNote())) {
dossier.setDossierNote(obj.getString(DossierTerm.DOSSIER_NOTE));
}
}
if (obj.has(DossierTerm.EXTEND_DATE) && Validator.isNotNull(obj.get(DossierTerm.EXTEND_DATE))
&& GetterUtil.getLong(obj.get(DossierTerm.EXTEND_DATE)) > 0) {
if (dossier.getExtendDate() == null || obj.getLong(DossierTerm.EXTEND_DATE) != dossier.getExtendDate().getTime()) {
dossier.setExtendDate(new Date(obj.getLong(DossierTerm.EXTEND_DATE)));
}
}
if (obj.has(DossierTerm.DOSSIER_NO)) {
//_log.info("Sync dossier no");
if (Validator.isNotNull(obj.getString(DossierTerm.DOSSIER_NO)) && !obj.getString(DossierTerm.DOSSIER_NO).equals(dossier.getDossierNo())) {
//_log.info("Sync set dossier no");
dossier.setDossierNo(obj.getString(DossierTerm.DOSSIER_NO));
}
}
if (obj.has(DossierTerm.DUE_DATE) && Validator.isNotNull(obj.get(DossierTerm.DUE_DATE))
&& GetterUtil.getLong(obj.get(DossierTerm.DUE_DATE)) > 0) {
if (dossier.getDueDate() == null || obj.getLong(DossierTerm.DUE_DATE) != dossier.getDueDate().getTime()) {
dossier.setDueDate(new Date(obj.getLong(DossierTerm.DUE_DATE)));
}
}
if (obj.has(DossierTerm.FINISH_DATE) && Validator.isNotNull(obj.get(DossierTerm.FINISH_DATE))
&& GetterUtil.getLong(obj.get(DossierTerm.FINISH_DATE)) > 0) {
if (dossier.getFinishDate() == null || obj.getLong(DossierTerm.FINISH_DATE) != dossier.getFinishDate().getTime()) {
dossier.setFinishDate(new Date(obj.getLong(DossierTerm.FINISH_DATE)));
}
}
if (obj.has(DossierTerm.RECEIVE_DATE) && Validator.isNotNull(obj.get(DossierTerm.RECEIVE_DATE))
&& GetterUtil.getLong(obj.get(DossierTerm.RECEIVE_DATE)) > 0) {
if (dossier.getReceiveDate() == null || obj.getLong(DossierTerm.RECEIVE_DATE) != dossier.getReceiveDate().getTime()) {
dossier.setReceiveDate(new Date(obj.getLong(DossierTerm.RECEIVE_DATE)));
}
}
if (obj.has(DossierTerm.SUBMIT_DATE) && Validator.isNotNull(obj.get(DossierTerm.SUBMIT_DATE))
&& GetterUtil.getLong(obj.get(DossierTerm.SUBMIT_DATE)) > 0) {
if (dossier.getSubmitDate() == null || (dossier.getSubmitDate() != null && obj.getLong(DossierTerm.SUBMIT_DATE) != dossier.getSubmitDate().getTime())) {
dossier.setSubmitDate(new Date(obj.getLong(DossierTerm.SUBMIT_DATE)));
}
}
if (obj.has(DossierTerm.EXTEND_DATE) && Validator.isNotNull(obj.get(DossierTerm.EXTEND_DATE))
&& GetterUtil.getLong(obj.get(DossierTerm.EXTEND_DATE)) > 0) {
if (dossier.getExtendDate() == null || obj.getLong(DossierTerm.EXTEND_DATE) != dossier.getExtendDate().getTime()) {
dossier.setExtendDate(new Date(obj.getLong(DossierTerm.EXTEND_DATE)));
}
}
if (obj.has(DossierTerm.DOSSIER_NOTE)) {
if (dossier.getDossierNote() == null || !obj.getString(DossierTerm.DOSSIER_NOTE).equals(dossier.getDossierNote())) {
dossier.setDossierNote(obj.getString(DossierTerm.DOSSIER_NOTE));
}
}
if (obj.has(DossierTerm.SUBMISSION_NOTE)) {
if (!obj.getString(DossierTerm.SUBMISSION_NOTE).equals(dossier.getDossierNote())) {
dossier.setSubmissionNote(obj.getString(DossierTerm.SUBMISSION_NOTE));
}
}
if (obj.has(DossierTerm.RELEASE_DATE) && Validator.isNotNull(obj.get(DossierTerm.RELEASE_DATE))
&& GetterUtil.getLong(obj.get(DossierTerm.RELEASE_DATE)) > 0) {
if (dossier.getReleaseDate() == null || obj.getLong(DossierTerm.RELEASE_DATE) != dossier.getReleaseDate().getTime()) {
dossier.setReleaseDate(new Date(obj.getLong(DossierTerm.RELEASE_DATE)));
}
}
if (obj.has(DossierTerm.LOCK_STATE)) {
if (!obj.getString(DossierTerm.LOCK_STATE).equals(dossier.getLockState())) {
dossier.setLockState(obj.getString(DossierTerm.LOCK_STATE));
}
}
if (obj.has(DossierTerm.BRIEF_NOTE)) {
if (!obj.getString(DossierTerm.BRIEF_NOTE).equals(dossier.getBriefNote())) {
dossier.setBriefNote(obj.getString(DossierTerm.BRIEF_NOTE));
}
}
}
private void processPaymentFile(long groupId, long userId, String payment, ProcessOption option,
ProcessAction proAction, DossierAction previousAction, Dossier dossier, ServiceContext context)
throws PortalException {
// long serviceProcessId = (option != null ? option.getServiceProcessId() : previousAction.getServiceProcessId());
// ServiceProcess serviceProcess = ServiceProcessLocalServiceUtil.fetchServiceProcess(serviceProcessId);
String paymentMethod = "";
try {
JSONObject paymentObj = JSONFactoryUtil.createJSONObject(payment);
if (paymentObj.has("paymentMethod")) {
paymentMethod = paymentObj.getString("paymentMethod");
}
}
catch (Exception e) {
_log.debug(e);
}
//Yêu cầu nộp tạm ứng
if (proAction.getRequestPayment() == ProcessActionTerm.REQUEST_PAYMENT_YEU_CAU_NOP_TAM_UNG
|| proAction.getRequestPayment() == ProcessActionTerm.REQUEST_PAYMENT_YEU_CAU_QUYET_TOAN_PHI && Validator.isNotNull(payment)) {
createPaymentFile(groupId, userId, payment, option, proAction, previousAction, dossier, context);
} else if (proAction.getRequestPayment() == ProcessActionTerm.REQUEST_PAYMENT_XAC_NHAN_HOAN_THANH_THU_PHI) {
// neu chua co payment file thi phai tao payment file
PaymentFile oldPaymentFile = paymentFileLocalService.getByDossierId(groupId, dossier.getDossierId());
if (Validator.isNull(oldPaymentFile)) {
oldPaymentFile = createPaymentFile(groupId, userId, payment, option, proAction, previousAction, dossier, context);
}
try {
_log.debug("groupId=" + groupId + " dossierId=" + dossier.getDossierId());
ExecuteOneActionTerm.invokeSInvoice(groupId, dossier, context);
} catch (Exception e) {
// TODO: do sth
_log.error(e);
}
String CINVOICEUrl = "postal/invoice";
JSONObject resultObj = null;
Map<String, Object> params = new HashMap<>();
int intpaymentMethod = 0;
if (Validator.isNotNull(proAction.getPreCondition())) {
intpaymentMethod = checkPaymentMethodinPrecondition(proAction.getPreCondition());
}
if (oldPaymentFile != null && proAction.getPreCondition().toLowerCase().contains("sendinvoice=1")){
params = createParamsInvoice(oldPaymentFile, dossier, intpaymentMethod);
InvokeREST callRest = new InvokeREST();
String baseUrl = RESTFulConfiguration.SERVER_PATH_BASE;
HashMap<String, String> properties = new HashMap<String, String>();
resultObj = callRest.callPostAPI(groupId, HttpMethod.POST, MediaType.APPLICATION_JSON, baseUrl,
CINVOICEUrl, StringPool.BLANK, StringPool.BLANK, properties, params, context);
}
if (Validator.isNotNull(oldPaymentFile) ) {
// String paymentMethod = "";
// if (intpaymentMethod != 0) {
// paymentMethod = checkPaymentMethod(intpaymentMethod);
// }
if(resultObj != null) {
oldPaymentFile.setEinvoice(resultObj.toString());
oldPaymentFile.setInvoicePayload(params.toString());
// if (Validator.isNotNull(paymentMethod)) {
// oldPaymentFile.setPaymentMethod(paymentMethod);
// }
if (Validator.isNotNull(paymentMethod)) {
oldPaymentFile.setPaymentMethod(paymentMethod);
}
}
if (Validator.isNotNull(payment)) {
try {
JSONObject paymentObj = JSONFactoryUtil.createJSONObject(payment);
if (paymentObj.has(KeyPayTerm.PAYMENTNOTE)) {
if (oldPaymentFile != null)
oldPaymentFile.setPaymentNote(paymentObj.getString(KeyPayTerm.PAYMENTNOTE));
String epaymentProfile = oldPaymentFile != null ? oldPaymentFile.getEpaymentProfile() : StringPool.BLANK;
if (Validator.isNotNull(epaymentProfile)) {
JSONObject jsonEpayment = JSONFactoryUtil.createJSONObject(epaymentProfile);
jsonEpayment.put(KeyPayTerm.PAYMENTNOTE, paymentObj.getString(KeyPayTerm.PAYMENTNOTE));
if (oldPaymentFile != null)
oldPaymentFile.setEpaymentProfile(jsonEpayment.toJSONString());
}
}
} catch (JSONException e) {
_log.debug(e);
}
}
if (oldPaymentFile != null) {
oldPaymentFile.setPaymentStatus(proAction.getRequestPayment());
paymentFileLocalService.updatePaymentFile(oldPaymentFile);
}
}
} else if (proAction.getRequestPayment() == ProcessActionTerm.REQUEST_PAYMENT_BAO_DA_NOP_PHI) {
PaymentFile oldPaymentFile = paymentFileLocalService.getByDossierId(groupId, dossier.getDossierId());
// int intpaymentMethod = checkPaymentMethodinPrecondition(proAction.getPreCondition());
// String paymentMethod = checkPaymentMethod(intpaymentMethod);
if (oldPaymentFile != null) {
oldPaymentFile.setPaymentStatus(proAction.getRequestPayment());
// oldPaymentFile.setPaymentMethod(paymentMethod);
if (Validator.isNotNull(paymentMethod)) {
oldPaymentFile.setPaymentMethod(paymentMethod);
}
paymentFileLocalService.updatePaymentFile(oldPaymentFile);
}
}
}
private PaymentFile createPaymentFile (long groupId, long userId, String payment, ProcessOption option,
ProcessAction proAction, DossierAction previousAction, Dossier dossier, ServiceContext context) throws PortalException {
String paymentFee = StringPool.BLANK;
Long feeAmount = 0l, serviceAmount = 0l, shipAmount = 0l;
String paymentNote = StringPool.BLANK;
long advanceAmount = 0l;
//long paymentAmount = 0l;
String epaymentProfile = StringPool.BLANK;
String bankInfo = StringPool.BLANK;
int paymentStatus = 0;
String paymentMethod = StringPool.BLANK;
NumberFormat fmt = NumberFormat.getNumberInstance(LocaleUtil.getDefault());
DecimalFormatSymbols customSymbol = new DecimalFormatSymbols();
customSymbol.setDecimalSeparator(',');
customSymbol.setGroupingSeparator('.');
((DecimalFormat)fmt).setDecimalFormatSymbols(customSymbol);
fmt.setGroupingUsed(true);
try {
JSONObject paymentObj = JSONFactoryUtil.createJSONObject(payment);
if (paymentObj.has(KeyPayTerm.PAYMENTNOTE)) {
paymentNote = paymentObj.getString(KeyPayTerm.PAYMENTNOTE);
}
if (paymentObj.has(KeyPayTerm.FEEAMOUNT)) {
feeAmount = (Long)fmt.parse(paymentObj.getString(KeyPayTerm.FEEAMOUNT));
}
if (paymentObj.has(KeyPayTerm.SERVICEAMOUNT)) {
serviceAmount = (Long)fmt.parse(paymentObj.getString(KeyPayTerm.SERVICEAMOUNT));
}
if (paymentObj.has(KeyPayTerm.SHIPAMOUNT)) {
shipAmount = (Long)fmt.parse(paymentObj.getString(KeyPayTerm.SHIPAMOUNT));
}
if (paymentObj.has(KeyPayTerm.REQUESTPAYMENT)) {
paymentStatus = paymentObj.getInt(KeyPayTerm.REQUESTPAYMENT);
}
if (paymentObj.has(KeyPayTerm.ADVANCEAMOUNT)) {
advanceAmount = (Long)fmt.parse(paymentObj.getString(KeyPayTerm.ADVANCEAMOUNT));
}
JSONObject paymentObj2 = JSONFactoryUtil.createJSONObject(proAction.getPaymentFee());
if (paymentObj2.has("paymentFee")) {
paymentFee = paymentObj2.getString("paymentFee");
}
if (paymentObj.has("paymentMethod")) {
paymentMethod = paymentObj.getString("paymentMethod");
}
}
catch (JSONException e) {
_log.debug(e);
} catch (ParseException e) {
_log.debug(e);
}
PaymentFile oldPaymentFile = paymentFileLocalService.getByDossierId(groupId, dossier.getDossierId());
if (oldPaymentFile != null) {
if (Validator.isNotNull(paymentMethod)) {
oldPaymentFile.setPaymentMethod(paymentMethod);
}
if (Validator.isNotNull(paymentNote))
oldPaymentFile.setPaymentNote(paymentNote);
try {
PaymentFile paymentFile = paymentFileLocalService.updateApplicantFeeAmount(
oldPaymentFile.getPaymentFileId(), proAction.getRequestPayment(), feeAmount, serviceAmount,
shipAmount, paymentNote, dossier.getOriginality());
String generatorPayURL = PaymentUrlGenerator.generatorPayURL(groupId,
paymentFile.getPaymentFileId(), paymentFee, dossier.getDossierId());
JSONObject epaymentProfileJsonNew = JSONFactoryUtil.createJSONObject(paymentFile.getEpaymentProfile());
epaymentProfileJsonNew.put(KeyPayTerm.KEYPAYURL, generatorPayURL);
PaymentConfig paymentConfig = paymentConfigLocalService.getPaymentConfigByGovAgencyCode(groupId,
dossier.getGovAgencyCode());
JSONObject epaymentConfigJSON = paymentConfig != null ? JSONFactoryUtil.createJSONObject(paymentConfig.getEpaymentConfig()) : JSONFactoryUtil.createJSONObject();
_log.debug("==========VTPayTerm.VTP_CONFIG========"+epaymentConfigJSON);
if (epaymentConfigJSON.has(VTPayTerm.VTP_CONFIG)) {
try {
JSONObject schema = epaymentConfigJSON.getJSONObject(VTPayTerm.VTP_CONFIG);
JSONObject data = JSONFactoryUtil.createJSONObject();
data.put(schema.getJSONObject(VTPayTerm.PRIORITY).getString(VTPayTerm.KEY),
schema.getJSONObject(VTPayTerm.PRIORITY).getString(VTPayTerm.VALUE));
data.put(schema.getJSONObject(VTPayTerm.VERSION).getString(VTPayTerm.KEY),
schema.getJSONObject(VTPayTerm.VERSION).getString(VTPayTerm.VALUE));
data.put(schema.getJSONObject(VTPayTerm.TYPE).getString(VTPayTerm.KEY),
schema.getJSONObject(VTPayTerm.TYPE).getString(VTPayTerm.VALUE));
data.put(schema.getJSONObject(VTPayTerm.BILLCODE).getString(VTPayTerm.KEY), VTPayTerm.createBillCode(dossier.getGovAgencyCode(), paymentFile.getInvoiceNo()));
data.put(schema.getJSONObject(VTPayTerm.ORDER_ID).getString(VTPayTerm.KEY), VTPayTerm.createOrderId(dossier.getDossierId(), dossier.getDossierNo()));
data.put(schema.getJSONObject(VTPayTerm.AMOUNT).getString(VTPayTerm.KEY), paymentFile.getPaymentAmount());
data.put(schema.getJSONObject(VTPayTerm.MERCHANT_CODE).getString(VTPayTerm.KEY),
schema.getJSONObject(VTPayTerm.MERCHANT_CODE).getString(VTPayTerm.VALUE));
epaymentProfileJsonNew.put(VTPayTerm.VTPAY_GENQR, data);
} catch (Exception e) {
_log.error(e);
}
}
paymentFileLocalService.updateEProfile(dossier.getDossierId(), paymentFile.getReferenceUid(), epaymentProfileJsonNew.toJSONString(),
context);
} catch (IOException e) {
_log.error(e);
}
catch (JSONException e) {
_log.debug(e);
}
} else {
long paymentAmount = feeAmount + serviceAmount + shipAmount - advanceAmount;
PaymentFile paymentFile = paymentFileLocalService.createPaymentFiles(userId, groupId,
dossier.getDossierId(), dossier.getReferenceUid(), paymentFee, advanceAmount, feeAmount,
serviceAmount, shipAmount, paymentAmount, paymentNote, epaymentProfile, bankInfo,
paymentStatus, paymentMethod, context);
long counterPaymentFile = CounterLocalServiceUtil.increment(PaymentFile.class.getName() + "paymentFileNo");
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
int prefix = cal.get(Calendar.YEAR);
String invoiceNo = Integer.toString(prefix) + String.format("%010d", counterPaymentFile);
paymentFile.setInvoiceNo(invoiceNo);
PaymentConfig paymentConfig = paymentConfigLocalService.getPaymentConfigByGovAgencyCode(groupId,
dossier.getGovAgencyCode());
if (Validator.isNotNull(paymentConfig)) {
paymentFile.setInvoiceTemplateNo(paymentConfig.getInvoiceTemplateNo());
paymentFile.setGovAgencyTaxNo(paymentConfig.getGovAgencyTaxNo());
paymentFile.setGovAgencyCode(paymentConfig.getGovAgencyCode());
paymentFile.setGovAgencyName(paymentConfig.getGovAgencyName());
}
paymentFileLocalService.updatePaymentFile(paymentFile);
JSONObject epaymentConfigJSON = paymentConfig != null ? JSONFactoryUtil.createJSONObject(paymentConfig.getEpaymentConfig()) : JSONFactoryUtil.createJSONObject();
JSONObject epaymentProfileJSON = JSONFactoryUtil.createJSONObject();
if (epaymentConfigJSON.has("paymentKeypayDomain")) {
try {
String generatorPayURL = PaymentUrlGenerator.generatorPayURL(groupId,
paymentFile.getPaymentFileId(), paymentFee, dossier.getDossierId());
epaymentProfileJSON.put(KeyPayTerm.KEYPAYURL, generatorPayURL);
String pattern1 = KeyPayTerm.GOOD_CODE_EQ;
String pattern2 = StringPool.AMPERSAND;
String regexString = Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2);
Pattern p = Pattern.compile(regexString);
Matcher m = p.matcher(generatorPayURL);
if (m.find()) {
String goodCode = m.group(1);
epaymentProfileJSON.put(KeyPayTerm.KEYPAYGOODCODE, goodCode);
} else {
epaymentProfileJSON.put(KeyPayTerm.KEYPAYGOODCODE, StringPool.BLANK);
}
epaymentProfileJSON.put(KeyPayTerm.KEYPAYMERCHANTCODE, epaymentConfigJSON.get("paymentMerchantCode"));
epaymentProfileJSON.put(KeyPayTerm.BANK, String.valueOf(true));
epaymentProfileJSON.put(KeyPayTerm.PAYGATE, String.valueOf(true));
epaymentProfileJSON.put(KeyPayTerm.SERVICEAMOUNT, serviceAmount);
epaymentProfileJSON.put(KeyPayTerm.PAYMENTNOTE, paymentNote);
epaymentProfileJSON.put(KeyPayTerm.PAYMENTFEE, paymentFee);
paymentFileLocalService.updateEProfile(dossier.getDossierId(), paymentFile.getReferenceUid(), epaymentProfileJSON.toJSONString(),
context);
} catch (IOException e) {
_log.error(e);
}
} else {
paymentFileLocalService.updateEProfile(dossier.getDossierId(), paymentFile.getReferenceUid(), epaymentProfileJSON.toJSONString(),
context);
}
_log.debug("==========VTPayTerm.VTP_CONFIG========"+epaymentConfigJSON);
if (epaymentConfigJSON.has(VTPayTerm.VTP_CONFIG)) {
try {
JSONObject schema = epaymentConfigJSON.getJSONObject(VTPayTerm.VTP_CONFIG);
JSONObject data = JSONFactoryUtil.createJSONObject();
data.put(schema.getJSONObject(VTPayTerm.PRIORITY).getString(VTPayTerm.KEY),
schema.getJSONObject(VTPayTerm.PRIORITY).getString(VTPayTerm.VALUE));
data.put(schema.getJSONObject(VTPayTerm.VERSION).getString(VTPayTerm.KEY),
schema.getJSONObject(VTPayTerm.VERSION).getString(VTPayTerm.VALUE));
data.put(schema.getJSONObject(VTPayTerm.TYPE).getString(VTPayTerm.KEY),
schema.getJSONObject(VTPayTerm.TYPE).getString(VTPayTerm.VALUE));
data.put(schema.getJSONObject(VTPayTerm.BILLCODE).getString(VTPayTerm.KEY), VTPayTerm.createBillCode(dossier.getGovAgencyCode(), paymentFile.getInvoiceNo()));
data.put(schema.getJSONObject(VTPayTerm.ORDER_ID).getString(VTPayTerm.KEY), VTPayTerm.createOrderId(dossier.getDossierId(), dossier.getDossierNo()));
data.put(schema.getJSONObject(VTPayTerm.AMOUNT).getString(VTPayTerm.KEY), paymentFile.getPaymentAmount());
data.put(schema.getJSONObject(VTPayTerm.MERCHANT_CODE).getString(VTPayTerm.KEY),
schema.getJSONObject(VTPayTerm.MERCHANT_CODE).getString(VTPayTerm.VALUE));
epaymentProfileJSON.put(VTPayTerm.VTPAY_GENQR, data);
paymentFileLocalService.updateEProfile(dossier.getDossierId(), paymentFile.getReferenceUid(), epaymentProfileJSON.toJSONString(),
context);
} catch (Exception e) {
_log.error(e);
}
}
}
return oldPaymentFile;
}
private void createNotificationSMS(long userId, long groupId, Dossier dossier, JSONArray assignedUsers, DossierAction dossierAction, ServiceContext context) {
// DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId());
User u = UserLocalServiceUtil.fetchUser(userId);
JSONObject payloadObj = JSONFactoryUtil.createJSONObject();
try {
payloadObj.put(
KeyPayTerm.DOSSIER, JSONFactoryUtil.createJSONObject(
JSONFactoryUtil.looseSerialize(dossier)));
if (dossierAction != null) {
payloadObj.put(DossierActionTerm.ACTION_CODE, dossierAction.getActionCode());
payloadObj.put(DossierActionTerm.ACTION_USER, dossierAction.getActionUser());
payloadObj.put(DossierActionTerm.ACTION_NAME, dossierAction.getActionName());
payloadObj.put(DossierActionTerm.ACTION_NOTE, dossierAction.getActionNote());
}
}
catch (Exception e) {
_log.error(e);
}
Notificationtemplate emplTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, NotificationTemplateTerm.EMPL_03);
Date now = new Date();
Calendar calEmpl = Calendar.getInstance();
calEmpl.setTime(now);
if (emplTemplate != null) {
if (KeyPayTerm.MINUTELY.equals(emplTemplate.getInterval())) {
calEmpl.add(Calendar.MINUTE, emplTemplate.getExpireDuration());
}
else if (KeyPayTerm.HOURLY.equals(emplTemplate.getInterval())) {
calEmpl.add(Calendar.HOUR, emplTemplate.getExpireDuration());
}
else {
calEmpl.add(Calendar.MINUTE, emplTemplate.getExpireDuration());
}
Date expired = calEmpl.getTime();
if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA
|| dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) {
try {
String stepCode = dossierAction.getStepCode();
StringBuilder buildX = new StringBuilder(stepCode);
if (stepCode.length() > 0) {
buildX.setCharAt(stepCode.length() - 1, 'x');
}
String stepCodeX = buildX.toString();
StepConfig stepConfig = StepConfigLocalServiceUtil.getByCode(groupId, dossierAction.getStepCode());
StepConfig stepConfigX = StepConfigLocalServiceUtil.getByCode(groupId, stepCodeX);
if ((stepConfig != null && stepConfig.getStepType() == StepConfigTerm.STEP_TYPE_DISPLAY_MENU_BY_PROCESSED)
|| (stepConfigX != null && stepConfigX.getStepType() == StepConfigTerm.STEP_TYPE_DISPLAY_MENU_BY_PROCESSED)) {
for (int n = 0; n < assignedUsers.length(); n++) {
JSONObject subUser = assignedUsers.getJSONObject(n);
if (subUser != null && subUser.has(DossierActionUserTerm.ASSIGNED)
&& subUser.getInt(DossierActionUserTerm.ASSIGNED) == DossierActionUserTerm.ASSIGNED_TH) {
long userIdAssigned = subUser.getLong(Field.USER_ID);
Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userIdAssigned);
if (employee != null) {
String telNo = employee != null ? employee.getTelNo() : StringPool.BLANK;
String fullName = employee != null ? employee.getFullName() : StringPool.BLANK;
NotificationQueueLocalServiceUtil.addNotificationQueue(
userId, groupId,
NotificationTemplateTerm.EMPL_03,
Dossier.class.getName(),
String.valueOf(dossier.getDossierId()),
payloadObj.toJSONString(),
u.getFullName(),
fullName,
userIdAssigned,
employee.getEmail(),
telNo,
now,
expired,
context);
}
}
}
}
} catch (NoSuchUserException e) {
_log.error(e);
//_log.error(e);
// e.printStackTrace();
}
}
}
}
private void createSubcription(long userId, long groupId, Dossier dossier, ActionConfig actionConfig, DossierAction dossierAction, ServiceContext context) {
if (actionConfig != null && Validator.isNotNull(actionConfig.getNotificationType())) {
// DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId());
// User u = UserLocalServiceUtil.fetchUser(userId);
Notificationtemplate notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, actionConfig.getNotificationType());
if (notiTemplate != null) {
if (actionConfig.getDocumentType().startsWith(KeyPayTerm.APLC)) {
if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA
|| dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) {
}
}
else if (actionConfig.getDocumentType().startsWith("EMPL")) {
if ((dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA
|| dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG)
&& dossierAction != null) {
StepConfig stepConfig = stepConfigLocalService.getByCode(groupId, dossierAction.getStepCode());
List<DossierActionUser> lstDaus = dossierActionUserLocalService.getByDID_DAI_SC_AS(dossier.getDossierId(), dossierAction.getDossierActionId(), dossierAction.getStepCode(), new int[] { 1, 2 });
if (NotificationTemplateTerm.EMPL_01.equals(actionConfig.getDocumentType()) && stepConfig != null
&& String.valueOf(1).equals(Validator.isNotNull(stepConfig.getStepType())
? String.valueOf(stepConfig.getStepType())
: StringPool.BLANK)) {
for (DossierActionUser dau : lstDaus) {
try {
SubscriptionLocalServiceUtil.addSubscription(dau.getUserId(), groupId, NotificationTemplateTerm.EMPL_01, 0);
} catch (PortalException e) {
_log.debug(e);
}
}
}
}
}
else if (actionConfig.getDocumentType().startsWith("USER")) {
}
}
}
}
private List<String> _putPaymentMessage(String pattern) {
List<String> lsDesc = new ArrayList<String>();
lsDesc.add(0, StringPool.BLANK);
lsDesc.add(1, StringPool.BLANK);
lsDesc.add(2, StringPool.BLANK);
lsDesc.add(3, StringPool.BLANK);
lsDesc.add(4, StringPool.BLANK);
List<String> lsMsg = DossierPaymentUtils.getMessagePayment(pattern);
for (int i = 0; i < lsMsg.size(); i++) {
lsDesc.set(1, lsMsg.get(i));
}
return lsDesc;
}
private long _genetatorTransactionId() {
long transactionId = 0;
try {
transactionId = counterLocalService.increment(PaymentFile.class.getName() + ".genetatorTransactionId");
} catch (SystemException e) {
_log.error(e);
}
return transactionId;
}
private String generatorPayURL(long groupId, long paymentFileId, String pattern,
Dossier dossier) throws IOException {
String result = StringPool.BLANK;
try {
PaymentFile paymentFile = paymentFileLocalService.getPaymentFile(paymentFileId);
PaymentConfig paymentConfig = paymentConfigLocalService.getPaymentConfigByGovAgencyCode(groupId,
dossier.getGovAgencyCode());
if (Validator.isNotNull(paymentConfig)) {
List<String> lsMessages = _putPaymentMessage(pattern);
long merchant_trans_id = _genetatorTransactionId();
JSONObject epaymentConfigJSON = JSONFactoryUtil.createJSONObject(paymentConfig.getEpaymentConfig());
String merchant_code = epaymentConfigJSON.getString("paymentMerchantCode");
String good_code = generatorGoodCode(10);
String net_cost = String.valueOf(paymentFile.getPaymentAmount());
String ship_fee = String.valueOf(0);
String tax = String.valueOf(0);
String bank_code = StringPool.BLANK;
String service_code = epaymentConfigJSON.getString("paymentServiceCode");
String version = epaymentConfigJSON.getString("paymentVersion");
String command = epaymentConfigJSON.getString("paymentCommand");
String currency_code = epaymentConfigJSON.getString("paymentCurrencyCode");
String desc_1 = StringPool.BLANK;
String desc_2 = StringPool.BLANK;
String desc_3 = StringPool.BLANK;
String desc_4 = StringPool.BLANK;
String desc_5 = StringPool.BLANK;
if (lsMessages.size() > 0) {
desc_1 = lsMessages.get(0);
desc_2 = lsMessages.get(1);
desc_3 = lsMessages.get(2);
desc_4 = lsMessages.get(3);
desc_5 = lsMessages.get(4);
if (desc_1.length() >= 20) {
desc_1 = desc_1.substring(0, 19);
}
if (desc_2.length() >= 30) {
desc_2 = desc_2.substring(0, 29);
}
if (desc_3.length() >= 40) {
desc_3 = desc_3.substring(0, 39);
}
if (desc_4.length() >= 100) {
desc_4 = desc_4.substring(0, 89);
}
if (desc_5.length() > 15) {
desc_5 = desc_5.substring(0, 15);
if (!Validator.isDigit(desc_5)) {
desc_5 = StringPool.BLANK;
}
}
}
String xml_description = StringPool.BLANK;
String current_locale = epaymentConfigJSON.getString("paymentCurrentLocale");
String country_code = epaymentConfigJSON.getString("paymentCountryCode");
String internal_bank = epaymentConfigJSON.getString("paymentInternalBank");
String merchant_secure_key = epaymentConfigJSON.getString("paymentMerchantSecureKey");
String algorithm = KeyPayTerm.VALUE_MD5;
if (epaymentConfigJSON.has("paymentHashAlgorithm")) {
algorithm = epaymentConfigJSON.getString("paymentHashAlgorithm");
}
// dossier = _getDossier(dossierId);
// TODO : update returnURL keyPay
String return_url;
_log.info("SONDT GENURL paymentReturnUrl ====================== "+ JSONFactoryUtil.looseSerialize(epaymentConfigJSON));
// return_url = epaymentConfigJSON.getString("paymentReturnUrl")+ "/" + dossier.getReferenceUid() + "/" + paymentFile.getReferenceUid();
return_url = epaymentConfigJSON.getString("paymentReturnUrl")+ "&dossierId=" + dossier.getDossierId() + "&goodCode=" + good_code + "&transId=" + merchant_trans_id + "&referenceUid=" + dossier.getReferenceUid();
_log.info("SONDT GENURL paymentReturnUrl ====================== "+ return_url);
// http://119.17.200.66:2681/web/bo-van-hoa/dich-vu-cong/#/thanh-toan-thanh-cong?paymentPortal=KEYPAY&dossierId=77603&goodCode=123&transId=555
KeyPay keypay = new KeyPay(String.valueOf(merchant_trans_id), merchant_code, good_code, net_cost,
ship_fee, tax, bank_code, service_code, version, command, currency_code, desc_1, desc_2, desc_3,
desc_4, desc_5, xml_description, current_locale, country_code, return_url, internal_bank,
merchant_secure_key, algorithm);
// keypay.setKeypay_url(paymentConfig.getKeypayDomain());
StringBuffer param = new StringBuffer();
param.append(KeyPayTerm.MERCHANT_CODE_EQ).append(URLEncoder.encode(keypay.getMerchant_code(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
// param.append(KeyPayTerm.MERCHANT_SECURE_KEY_EQ).append(URLEncoder.encode(keypay.getMerchant_secure_key(), StandardCharsets.UTF_8.name()))
// .append(StringPool.AMPERSAND);
param.append(KeyPayTerm.BANK_CODE_EQ).append(URLEncoder.encode(keypay.getBank_code(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.INTERNAL_BANK_EQ).append(URLEncoder.encode(keypay.getInternal_bank(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.MERCHANT_TRANS_ID_EQ).append(URLEncoder.encode(keypay.getMerchant_trans_id(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.GOOD_CODE_EQ).append(URLEncoder.encode(keypay.getGood_code(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.NET_COST_EQ).append(URLEncoder.encode(keypay.getNet_cost(), StandardCharsets.UTF_8.name()) )
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.SHIP_FEE_EQ).append(URLEncoder.encode(keypay.getShip_fee(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.TAX_EQ).append(URLEncoder.encode(keypay.getTax(), StandardCharsets.UTF_8.name())).append(StringPool.AMPERSAND);
param.append(KeyPayTerm.RETURN_URL_EQ).append(URLEncoder.encode(keypay.getReturn_url(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.VERSION_EQ).append(URLEncoder.encode(keypay.getVersion(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.COMMAND_EQ).append(URLEncoder.encode(keypay.getCommand(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.CURRENT_LOCALE_EQ).append(URLEncoder.encode(keypay.getCurrent_locale(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.CURRENCY_CODE_EQ).append(URLEncoder.encode(keypay.getCurrency_code(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.SERVICE_CODE_EQ).append(URLEncoder.encode(keypay.getService_code(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.COUNTRY_CODE_EQ).append(URLEncoder.encode(keypay.getCountry_code(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.DESC_1_EQ).append(URLEncoder.encode(keypay.getDesc_1(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.DESC_2_EQ).append(URLEncoder.encode(keypay.getDesc_2(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.DESC_3_EQ).append(URLEncoder.encode(keypay.getDesc_3(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.DESC_4_EQ).append(URLEncoder.encode(keypay.getDesc_4(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.DESC_5_EQ).append(URLEncoder.encode(keypay.getDesc_5(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.XML_DESCRIPTION_EQ).append(URLEncoder.encode(keypay.getXml_description(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.SECURE_HASH_EQ).append(keypay.getSecure_hash());
result = epaymentConfigJSON.getString(KeyPayTerm.PAYMENTKEYPAYDOMAIN) + StringPool.QUESTION + param.toString();
}
} catch (NoSuchPaymentFileException e) {
_log.debug(e);
} catch (Exception e) {
_log.debug(e);
}
return result;
}
private Map<String, Object> createParamsInvoice(PaymentFile oldPaymentFile, Dossier dossier, int intpaymentMethod) {
Map<String, Object> params = new HashMap<>();
StringBuilder address = new StringBuilder();
address.append(dossier.getAddress());address.append(", ");
address.append(dossier.getWardName());address.append(", ");
address.append(dossier.getDistrictName());address.append(", ");
address.append(dossier.getCityName());
SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
String dateformatted = sdf.format(new Date());
_log.info("SONDT CINVOICE DATEFORMATED ============= " + dateformatted);
params.put(Field.USER_NAME, StringPool.BLANK);
params.put(CInvoiceTerm.secret, String.valueOf(1));
params.put(CInvoiceTerm.soid, String.valueOf(0));
params.put(CInvoiceTerm.maHoadon, StringPool.BLANK);
params.put(CInvoiceTerm.ngayHd, dateformatted); //"01/08/2018"
params.put(CInvoiceTerm.seri, String.valueOf(12314));
params.put(CInvoiceTerm.maNthue, "01");
params.put(CInvoiceTerm.kieuSo, "G");
params.put(CInvoiceTerm.maKhackHang, Long.toString(dossier.getUserId()));
params.put(CInvoiceTerm.ten, dossier.getApplicantName());
params.put(CInvoiceTerm.phone, dossier.getContactTelNo());
if(dossier.getApplicantIdType().contentEquals("business")) {
params.put(CInvoiceTerm.tax, dossier.getApplicantIdNo());
} else {
params.put(CInvoiceTerm.tax, StringPool.BLANK);
}
params.put(CInvoiceTerm.dchi, address);
params.put(CInvoiceTerm.maTk, StringPool.BLANK);
params.put(CInvoiceTerm.tenNh, StringPool.BLANK);
params.put(CInvoiceTerm.mailH, GetterUtil.getString(dossier.getContactEmail()));
params.put(CInvoiceTerm.phoneH, GetterUtil.getString(dossier.getContactTelNo()));
params.put(CInvoiceTerm.tenM, GetterUtil.getString(dossier.getDelegateName()));
params.put(CInvoiceTerm.maKhL, "K");
params.put(CInvoiceTerm.maNt, "VND");
params.put(CInvoiceTerm.tg, String.valueOf(1));
if(intpaymentMethod == 3) {
params.put(CInvoiceTerm.hthuc, CInvoiceTerm.hthuc_M);
}else {
params.put(CInvoiceTerm.hthuc, CInvoiceTerm.hthuc_C);
}
params.put(CInvoiceTerm.han, StringPool.BLANK);
params.put(CInvoiceTerm.tlGgia, String.valueOf(0));
params.put(CInvoiceTerm.ggia, String.valueOf(0));
params.put(CInvoiceTerm.phi, String.valueOf(0));
params.put(CInvoiceTerm.noidung, dossier.getDossierNo());
params.put(CInvoiceTerm.tien, Long.toString(oldPaymentFile.getPaymentAmount()));
params.put(CInvoiceTerm.ttoan, Long.toString(oldPaymentFile.getPaymentAmount()));
params.put(CInvoiceTerm.maVtDetail, dossier.getDossierNo());
params.put(CInvoiceTerm.tenDetail, GetterUtil.getString(dossier.getServiceName()));
params.put(CInvoiceTerm.dvtDetail, "bo");
params.put(CInvoiceTerm.luongDetail, String.valueOf(1));
params.put(CInvoiceTerm.giaDetail, Long.toString(oldPaymentFile.getPaymentAmount()));
params.put(CInvoiceTerm.tienDetail, Long.toString(oldPaymentFile.getPaymentAmount()));
params.put(CInvoiceTerm.tsDetail, String.valueOf(0));
params.put(CInvoiceTerm.thueDetail, String.valueOf(0));
params.put(CInvoiceTerm.ttoanDetail, Long.toString(oldPaymentFile.getPaymentAmount()));
return params;
}
private int checkPaymentMethodinPrecondition(String preCondition) {
int paymentMethod = 0;
String[] preConditions = StringUtil.split(preCondition);
for(String pre : preConditions) {
pre = pre.trim();
if (pre.toLowerCase().contains(KeyPayTerm.PAYMENTMETHOD_EQ)) {
String[] splitPaymentMethod = pre.split(StringPool.EQUAL);
if (splitPaymentMethod.length == 2) {
paymentMethod = Integer.parseInt(splitPaymentMethod[1]);
}
break;
}
}
return paymentMethod;
}
private String checkPaymentMethod(int mt) {
String pmMethod = StringPool.BLANK;
if (mt == 1) {
pmMethod = KeyPayTerm.PM_METHOD_1; //KeyPay
} else if (mt == 2) {
pmMethod = KeyPayTerm.PM_METHOD_2;
} else if (mt == 3) {
pmMethod = KeyPayTerm.PM_METHOD_3;
}
return pmMethod;
}
private JSONObject getStatusText(long groupId, String collectionCode, String curStatus, String curSubStatus) {
JSONObject jsonData = null;
DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(collectionCode, groupId);
if (Validator.isNotNull(dc) && Validator.isNotNull(curStatus)) {
jsonData = JSONFactoryUtil.createJSONObject();
DictItem it = DictItemLocalServiceUtil.fetchByF_dictItemCode(curStatus, dc.getPrimaryKey(), groupId);
if (Validator.isNotNull(it)) {
jsonData.put(curStatus, it.getItemName());
if (Validator.isNotNull(curSubStatus)) {
DictItem dItem = DictItemLocalServiceUtil.fetchByF_dictItemCode(curSubStatus, dc.getPrimaryKey(),
groupId);
if (Validator.isNotNull(dItem)) {
jsonData.put(curSubStatus, dItem.getItemName());
}
}
}
}
return jsonData;
}
private int getActionDueDate(long groupId, long dossierId, String refId, long processActionId) {
return 0;
}
protected String getDictItemName(long groupId, String collectionCode, String itemCode) {
DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(collectionCode, groupId);
if (Validator.isNotNull(dc)) {
DictItem it = DictItemLocalServiceUtil.fetchByF_dictItemCode(itemCode, dc.getPrimaryKey(), groupId);
if(Validator.isNotNull(it)){
return it.getItemName();
}else{
return StringPool.BLANK;
}
} else {
return StringPool.BLANK;
}
}
private void updateStatus(Dossier dossier, String status, String statusText, String subStatus,
String subStatusText, String lockState, String stepInstruction, ServiceContext context)
throws PortalException {
Date now = new Date();
dossier.setModifiedDate(now);
dossier.setDossierStatus(status);
dossier.setDossierStatusText(statusText);
dossier.setDossierSubStatus(subStatus);
dossier.setDossierSubStatusText(subStatusText);
if (dossier != null && !DossierTerm.PAUSE_OVERDUE_LOCK_STATE.equals(dossier.getLockState())) {
dossier.setLockState(lockState);
}
dossier.setDossierNote(stepInstruction);
// if (status.equalsIgnoreCase(DossierStatusConstants.RELEASING)) {
// dossier.setReleaseDate(now);
// }
//
// if (status.equalsIgnoreCase(DossierStatusConstants.DONE)) {
// dossier.setFinishDate(now);
// }
}
private Map<String, Boolean> updateProcessingDate(DossierAction dossierAction, DossierAction prevAction, ProcessStep processStep, Dossier dossier, String curStatus, String curSubStatus, String prevStatus,
int dateOption,
ProcessOption option,
ServiceProcess serviceProcess,
ServiceContext context) {
Date now = new Date();
Map<String, Boolean> bResult = new HashMap<>();
LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();
params.put(DossierTerm.GOV_AGENCY_CODE, dossier.getGovAgencyCode());
params.put(DossierTerm.SERVICE_CODE, dossier.getServiceCode());
params.put(DossierTerm.DOSSIER_TEMPLATE_NO, dossier.getDossierTemplateNo());
params.put(DossierTerm.DOSSIER_STATUS, StringPool.BLANK);
// ServiceProcess serviceProcess = null;
//
// long serviceProcessId = (option != null ? option.getServiceProcessId() : prevAction.getServiceProcessId());
// serviceProcess = ServiceProcessLocalServiceUtil.fetchServiceProcess(serviceProcessId);
// if ((Validator.isNull(prevStatus) && DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus)
// && (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA))
if ((DossierTerm.DOSSIER_STATUS_RECEIVING.equals(curStatus) || DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus))
&& dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) {
try {
if (Validator.isNotNull(option) && Validator.isNull(dossier.getDossierNo())
&& dossier.getOriginDossierId() > 0) {
String dossierRef = DossierNumberGenerator.generateDossierNumber(dossier.getGroupId(), dossier.getCompanyId(),
dossier.getDossierId(), option.getProcessOptionId(), serviceProcess.getDossierNoPattern(), params);
dossier.setDossierNo(dossierRef.trim());
// DossierLocalServiceUtil.updateDossier(dossier);
bResult.put(DossierTerm.DOSSIER_NO, true);
}
} catch (PortalException e) {
_log.debug(e);
//_log.error(e);
// e.printStackTrace();
}
}
if ((DossierTerm.DOSSIER_STATUS_NEW.equals(prevStatus)
&& DossierTerm.DOSSIER_STATUS_RECEIVING.equals(curStatus)) ||
(dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA && DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus))) {
// try {
// DossierLocalServiceUtil.updateSubmittingDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context);
if (Validator.isNull(dossier.getSubmitDate())) {
dossier.setSubmitDate(now);
bResult.put(DossierTerm.SUBMIT_DATE, true);
}
// } catch (PortalException e) {
// _log.error(e);
// e.printStackTrace();
// }
}
if (dossier.getOriginality() != DossierTerm.ORIGINALITY_DVCTT &&
((DossierTerm.DOSSIER_STATUS_PROCESSING.equals(curStatus) && dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG)
|| (DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus) && dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA)
|| (DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus) && dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG)
|| (dateOption == DossierTerm.DATE_OPTION_TWO))
&& dossier.getReceiveDate() == null) {
// try {
// DossierLocalServiceUtil.updateReceivingDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context);
dossier.setReceiveDate(now);
bResult.put(DossierTerm.RECEIVE_DATE, true);
Double durationCount = serviceProcess.getDurationCount();
int durationUnit = serviceProcess.getDurationUnit();
Date dueDate = null;
if (Validator.isNotNull(durationCount) && durationCount > 0
&& !areEqualDouble(durationCount, 0.00d, 3)) {
// dueDate = HolidayUtils.getDueDate(now, durationCount, durationUnit, dossier.getGroupId());
DueDateUtils dueDateUtils = new DueDateUtils(now, durationCount, durationUnit, dossier.getGroupId());
dueDate = dueDateUtils.getDueDate();
}
if (Validator.isNotNull(dueDate)) {
dossier.setDueDate(dueDate);
// DossierLocalServiceUtil.updateDueDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), dueDate, context);
bResult.put(DossierTerm.DUE_DATE, true);
}
dossier.setDurationCount(durationCount);
dossier.setDurationUnit(durationUnit);
if (dossier.getCounter() == 0 && Validator.isNotNull(dossier.getRegisterBookCode())) {
long counterCode = DossierNumberGenerator.countByRegiterBookCode(dossier.getGroupId(),
dossier.getRegisterBookCode());
dossier.setCounter(counterCode);
}
if (Validator.isNull(dossier.getDossierNo())) {
try {
String dossierRef = DossierNumberGenerator.generateDossierNumber(dossier.getGroupId(), dossier.getCompanyId(),
dossier.getDossierId(), option.getProcessOptionId(), serviceProcess.getDossierNoPattern(), params);
dossier.setDossierNo(dossierRef.trim());
} catch (Exception e) {
_log.debug(e);
}
}
if (Validator.isNull(dossier.getDossierCounter()) && Validator.isNotNull(serviceProcess.getCounterCode())) {
ConfigCounter counterConfig = ConfigCounterLocalServiceUtil.fetchByCountrCode(dossier.getGroupId(),
serviceProcess.getCounterCode());
if (counterConfig != null) {
if (Validator.isNotNull(counterConfig.getStartCounter()) && counterConfig.getStartCounter() > 0) {
String patternCode = counterConfig.getPatternCode();
try {
_log.info("dossierId: " + dossier.getDossierId() + "| option.getProcessOptionId(): "
+ option.getProcessOptionId() + "| serviceProcess.getCounterCode(): "
+ serviceProcess.getCounterCode() + "| getStartCounter(): "
+ counterConfig.getStartCounter());
String dossierCounter = ConfigCounterNumberGenerator.generateCounterNumber(dossier.getGroupId(),
dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(),
patternCode, counterConfig, params);
dossier.setDossierCounter(dossierCounter.trim());
_log.info("dossierCounter: " + dossierCounter);
} catch (Exception e) {
_log.debug(e);
}
} else {
String patternCode = counterConfig.getPatternCode();
try {
_log.info("dossierId: " + dossier.getDossierId() + "| option.getProcessOptionId(): "
+ option.getProcessOptionId() + "| serviceProcess.getCounterCode(): "
+ serviceProcess.getCounterCode());
String dossierCounter = ConfigCounterNumberGenerator.generateCounterNumber(dossier.getGroupId(),
dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(),
patternCode, counterConfig, params);
dossier.setDossierCounter(dossierCounter.trim());
_log.info("dossierCounter: " + dossierCounter);
} catch (Exception e) {
_log.debug(e);
}
}
}
}
}
//Update counter and dossierNo
if (dateOption == DossierTerm.DATE_OPTION_TWO || dateOption == DossierTerm.DATE_OPTION_TEN) {
if (dossier.getCounter() == 0 && Validator.isNotNull(dossier.getRegisterBookCode())) {
long counterCode = DossierNumberGenerator.countByRegiterBookCode(dossier.getGroupId(),
dossier.getRegisterBookCode());
dossier.setCounter(counterCode);
}
if (Validator.isNull(dossier.getDossierNo())) {
try {
String dossierRef = DossierNumberGenerator.generateDossierNumber(dossier.getGroupId(), dossier.getCompanyId(),
dossier.getDossierId(), option.getProcessOptionId(), serviceProcess.getDossierNoPattern(),
params);
dossier.setDossierNo(dossierRef.trim());
} catch (Exception e) {
_log.debug(e);
}
}
if (Validator.isNull(dossier.getDossierCounter()) && Validator.isNotNull(serviceProcess.getCounterCode())) {
ConfigCounter counterConfig = ConfigCounterLocalServiceUtil.fetchByCountrCode(dossier.getGroupId(),
serviceProcess.getCounterCode());
if (counterConfig != null) {
if (Validator.isNotNull(counterConfig.getStartCounter()) && counterConfig.getStartCounter() > 0) {
String patternCode = counterConfig.getPatternCode();
try {
_log.info("dossierId: " + dossier.getDossierId() + "| option.getProcessOptionId(): "
+ option.getProcessOptionId() + "| serviceProcess.getCounterCode(): "
+ serviceProcess.getCounterCode() + "| getStartCounter(): "
+ counterConfig.getStartCounter());
String dossierCounter = ConfigCounterNumberGenerator.generateCounterNumber(dossier.getGroupId(),
dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(),
patternCode, counterConfig, params);
dossier.setDossierCounter(dossierCounter.trim());
_log.info("dossierCounter: " + dossierCounter);
} catch (Exception e) {
_log.debug(e);
}
} else {
String patternCode = counterConfig.getPatternCode();
try {
_log.info("dossierId: " + dossier.getDossierId() + "| option.getProcessOptionId(): "
+ option.getProcessOptionId() + "| serviceProcess.getCounterCode(): "
+ serviceProcess.getCounterCode());
String dossierCounter = ConfigCounterNumberGenerator.generateCounterNumber(dossier.getGroupId(),
dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(),
patternCode, counterConfig, params);
dossier.setDossierCounter(dossierCounter.trim());
_log.info("dossierCounter: " + dossierCounter);
} catch (Exception e) {
_log.debug(e);
}
}
}
}
}
if (DossierTerm.DOSSIER_STATUS_RECEIVING.equals(prevStatus) && DossierTerm.DOSSIER_STATUS_PROCESSING.equals(curStatus)) {
// try {
// DossierLocalServiceUtil.updateProcessDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context);
dossier.setProcessDate(now);
bResult.put(DossierTerm.PROCESS_DATE, true);
// } catch (PortalException e) {
// _log.error(e);
// e.printStackTrace();
// }
}
// if (DossierTerm.DOSSIER_STATUS_RELEASING.equals(curStatus)
// || DossierTerm.DOSSIER_STATUS_DENIED.equals(curStatus)
// || DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus)
// || DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus)
// || DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)) {
if (DossierTerm.DOSSIER_STATUS_RELEASING.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus)
|| (dateOption == 4)
) {
if (Validator.isNull(dossier.getReleaseDate())) {
// try {
// DossierLocalServiceUtil.updateReleaseDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context);
dossier.setReleaseDate(now);
if (OpenCPSConfigUtil.isAutoBetimes()) {
int valueCompareRelease = BetimeUtils.getValueCompareRelease(dossier.getGroupId(), now, dossier.getDueDate());
if (3 == valueCompareRelease) {
dossier.setExtendDate(now);
}
}
bResult.put(DossierTerm.RELEASE_DATE, true);
// } catch (PortalException e) {
// _log.error(e);
// e.printStackTrace();
// }
}
}
// _log.info("========STEP DUE CUR STATUS: " + curStatus);
if (DossierTerm.DOSSIER_STATUS_DENIED.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)) {
// _log.info("========STEP DUE CUR STATUS UPDATING STATE DONE");
// dossierAction.setState(DossierActionTerm.STATE_ALREADY_PROCESSED);
// dossierAction.setModifiedDate(new Date());
dossierAction = dossierActionLocalService.updateState(dossierAction.getDossierActionId(), DossierActionTerm.STATE_ALREADY_PROCESSED);
}
//Check verification
if (DossierTerm.DOSSIER_STATUS_DONE.contentEquals(curStatus)) {
Applicant checkApplicant = ApplicantLocalServiceUtil.fetchByMappingID(dossier.getUserId());
if (checkApplicant != null && dossier.getOriginality() == DossierTerm.ORIGINALITY_DVCTT) {
if (checkApplicant.getVerification() == ApplicantTerm.LOCKED || checkApplicant.getVerification() == ApplicantTerm.LOCKED_DOSSIER) {
checkApplicant.setVerification(ApplicantTerm.UNLOCKED);
ApplicantLocalServiceUtil.updateApplicant(checkApplicant);
}
}
}
// if (DossierTerm.DOSSIER_STATUS_DENIED.equals(curStatus)
// || DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus)
// || DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus)
// || DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)) {
if (DossierTerm.DOSSIER_STATUS_DENIED.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus)
|| (dateOption == 5)) {
if (Validator.isNull(dossier.getFinishDate())) {
// try {
// DossierLocalServiceUtil.updateFinishDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context);
dossier.setFinishDate(now);
bResult.put(DossierTerm.FINISH_DATE, true);
// dossierAction.setState(DossierActionTerm.STATE_ALREADY_PROCESSED);
// dossierAction.setModifiedDate(new Date());
dossierAction = dossierActionLocalService.updateState(dossierAction.getDossierActionId(), DossierActionTerm.STATE_ALREADY_PROCESSED);
// } catch (PortalException e) {
// _log.error(e);
// e.printStackTrace();
// }
}
if (Validator.isNull(dossier.getReleaseDate())) {
// try {
// DossierLocalServiceUtil.updateReleaseDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context);
dossier.setReleaseDate(now);
if (OpenCPSConfigUtil.isAutoBetimes()) {
int valueCompareRelease = BetimeUtils.getValueCompareRelease(dossier.getGroupId(), now, dossier.getDueDate());
if (3 == valueCompareRelease) {
dossier.setExtendDate(now);
}
}
bResult.put(DossierTerm.RELEASE_DATE, true);
// } catch (PortalException e) {
// _log.error(e);
// e.printStackTrace();
// }
}
}
if (DossierTerm.DOSSIER_STATUS_PROCESSING.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_INTEROPERATING.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_WAITING.equals(curStatus)) {
if (Validator.isNotNull(dossier.getFinishDate())) {
dossier.setFinishDate(null);
bResult.put(DossierTerm.FINISH_DATE, true);
}
if (Validator.isNotNull(dossier.getReleaseDate())) {
dossier.setReleaseDate(null);
bResult.put(DossierTerm.RELEASE_DATE, true);
}
}
if (DossierTerm.DOSSIER_STATUS_RECEIVING.equals(prevStatus)) {
bResult.put(DossierTerm.DOSSIER_NO, true);
bResult.put(DossierTerm.RECEIVE_DATE, true);
bResult.put(DossierTerm.PROCESS_DATE, true);
bResult.put(DossierTerm.RELEASE_DATE, true);
bResult.put(DossierTerm.FINISH_DATE, true);
}
if (DossierTerm.DOSSIER_STATUS_NEW.equals(prevStatus) && dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG
&& Validator.isNotNull(dossier.getReceiveDate())) {
bResult.put(DossierTerm.RECEIVE_DATE, true);
}
if (DossierTerm.DOSSIER_STATUS_RECEIVING.contentEquals(dossier.getDossierStatus()) && dossier.getOriginality() == DossierTerm.ORIGINALITY_DVCTT) {
Applicant checkApplicant = ApplicantLocalServiceUtil.fetchByMappingID(dossier.getUserId());
if (checkApplicant != null) {
int countDossier = DossierLocalServiceUtil.countByG_UID_DS(dossier.getGroupId(), dossier.getUserId(), DossierTerm.DOSSIER_STATUS_RECEIVING);
_log.debug("APPLICANT NUMBER OF CREATE DOSSIER: " + countDossier);
if (countDossier >= DossierTerm.MAX_DOSSIER_WITHOUT_VERIFICATION) {
if (checkApplicant.getVerification() != ApplicantTerm.UNLOCKED) {
checkApplicant.setVerification(ApplicantTerm.LOCKED_DOSSIER);
ApplicantLocalServiceUtil.updateApplicant(checkApplicant);
}
}
}
}
//int dateOption = actionConfig.getDateOption();
_log.debug("dateOption: "+dateOption);
if (dateOption == DossierTerm.DATE_OPTION_CAL_WAITING) {
DossierAction dActEnd = dossierActionLocalService
.fetchDossierAction(dossierAction.getDossierActionId());
// DossierAction dActEnd = dossierAction;
if (dActEnd != null && dossier.getDurationCount() > 0) {
_log.debug("dActEnd.getPreviousActionId(): "+dActEnd.getPreviousActionId());
DossierAction dActPrevious = dossierActionLocalService
.fetchDossierAction(dActEnd.getPreviousActionId());
// DossierAction dActStart = prevAction;
if (dActPrevious != null) {
ActionConfig actPrevious = ActionConfigLocalServiceUtil.getByCode(dActPrevious.getGroupId(),
dActPrevious.getActionCode());
_log.debug("actPrevious: "+actPrevious.getDateOption());
long createEnd = dActEnd.getCreateDate().getTime();
long createStart = 0;
if (actPrevious != null && actPrevious.getDateOption() != 1) {
createStart = dActPrevious.getCreateDate().getTime();
} else {
List<DossierAction> dActionList = DossierActionLocalServiceUtil
.findByG_DID(dActEnd.getGroupId(), dActEnd.getDossierId());
if (dActionList != null && dActionList.size() > 1) {
int lengthAction = dActionList.size();
for (int i = lengthAction - 2; i >= 0; i--) {
DossierAction dAction = dActionList.get(i);
_log.debug("dAction: "+i+": "+dAction);
ActionConfig actDetail = ActionConfigLocalServiceUtil.getByCode(dAction.getGroupId(),
dAction.getActionCode());
_log.debug("actDetail: "+i+": "+actDetail.getDateOption());
if (actDetail.getDateOption() == 1) {
createStart = dAction.getCreateDate().getTime();
} else {
break;
}
}
}
}
_log.debug("createStart: "+createStart);
_log.debug("createEnd: "+createEnd);
if (createEnd > createStart) {
DueDateUtils dueDateUtils = new DueDateUtils(new Date(createStart), new Date(createEnd), 1, dActEnd.getGroupId());
//long extendDateTimeStamp = ExtendDueDateUtils.getTimeWaitingByHoliday(createStart, createEnd, dossier.getGroupId());
long extendDateTimeStamp = dueDateUtils.getOverDue();
_log.debug("extendDateTimeStamp: "+extendDateTimeStamp);
if (extendDateTimeStamp > 0) {
double hoursCount = extendDateTimeStamp * 1.0 / (1000 * 60 * 60);
_log.debug("hoursCount: "+hoursCount);
//_log.info("dossier.getExtendDate(): "+dossier.getExtendDate());
// List<Holiday> holidayList = HolidayLocalServiceUtil
// .getHolidayByGroupIdAndType(dossier.getGroupId(), 0);
// List<Holiday> extendWorkDayList = HolidayLocalServiceUtil
// .getHolidayByGroupIdAndType(dossier.getGroupId(), 1);
//Date dueDateExtend = HolidayUtils.getEndDate(dossier.getGroupId(),
// dossier.getDueDate(), hoursCount, holidayList,
// extendWorkDayList);
//
DueDateUtils dateUtils = new DueDateUtils(dossier.getDueDate(),
hoursCount, 1, dossier.getGroupId());
Date dueDateExtend = dateUtils.getDueDate();
_log.debug("dueDateExtend: "+dueDateExtend);
if (dueDateExtend != null) {
dossier.setDueDate(dueDateExtend);
//dossier.setCorrecttingDate(null);
bResult.put(DossierTerm.DUE_DATE, true);
}
}
}
}
} else if (dossier.getDurationCount() <= 0) {
dossier.setDueDate(null);
}
} else if (dateOption == DossierTerm.DATE_OPTION_CHANGE_DUE_DATE) {
if (dossier.getDueDate() != null) {
//dossier.setCorrecttingDate(dossier.getDueDate());
//dossier.setDueDate(null);
dossier.setLockState(DossierTerm.PAUSE_STATE);
}
}
else if (dateOption == DossierTerm.DATE_OPTION_RESET_DUE_DATE) {
if (dossier != null && !DossierTerm.PAUSE_OVERDUE_LOCK_STATE.equals(dossier.getLockState())) {
dossier.setLockState(StringPool.BLANK);
}
if (dossier.getDueDate() != null) {
if (serviceProcess != null) {
// Date newDueDate = HolidayUtils.getDueDate(new Date(),
// serviceProcess.getDurationCount(),
// serviceProcess.getDurationUnit(), dossier.getGroupId());
DueDateUtils dueDateUtils = new DueDateUtils(new Date(),
serviceProcess.getDurationCount(),
serviceProcess.getDurationUnit(), dossier.getGroupId());
Date newDueDate = dueDateUtils.getDueDate();
if (newDueDate != null) {
//dossier.setReceiveDate(new Date());
dossier.setDueDate(newDueDate);
bResult.put(DossierTerm.DUE_DATE, true);
}
}
}
}
else if (dateOption == DossierTerm.DATE_OPTION_PAUSE_OVERDUE) {
if (dossier.getDueDate() != null) {
dossier.setLockState(DossierTerm.PAUSE_OVERDUE_LOCK_STATE);
}
} else if ((dateOption == DossierTerm.DATE_OPTION_DUEDATE_PHASE_1
|| dateOption == DossierTerm.DATE_OPTION_DUEDATE_PHASE_2
|| dateOption == DossierTerm.DATE_OPTION_DUEDATE_PHASE_3)
&& serviceProcess != null) {
DueDatePhaseUtil dueDatePharse = new DueDatePhaseUtil(dossier.getGroupId(), new Date(), dateOption, serviceProcess.getDueDatePattern());
dossier.setDueDate(dueDatePharse.getDueDate());
bResult.put(DossierTerm.DUE_DATE, true);
dossier = setDossierNoNDueDate(dossier, serviceProcess, option, true, false, null, params);
} else //Update counter and dossierNo
if (dateOption == DossierTerm.DATE_OPTION_TWO || dateOption == DossierTerm.DATE_OPTION_TEN) {
/**
* THANHNV create common init DueDate DossierNo DossierCounter
if (dossier.getCounter() == 0 && Validator.isNotNull(dossier.getRegisterBookCode())) {
long counterCode = DossierNumberGenerator.countByRegiterBookCode(dossier.getGroupId(),
dossier.getRegisterBookCode());
dossier.setCounter(counterCode);
}
if (Validator.isNull(dossier.getDossierNo())) {
try {
String dossierRef = DossierNumberGenerator.generateDossierNumber(dossier.getGroupId(), dossier.getCompanyId(),
dossier.getDossierId(), option.getProcessOptionId(), serviceProcess.getDossierNoPattern(),
params);
dossier.setDossierNo(dossierRef.trim());
} catch (Exception e) {
_log.debug(e);
}
}
if (Validator.isNull(dossier.getDossierCounter()) && Validator.isNotNull(serviceProcess.getCounterCode())) {
ConfigCounter counterConfig = ConfigCounterLocalServiceUtil.fetchByCountrCode(dossier.getGroupId(),
serviceProcess.getCounterCode());
if (counterConfig != null) {
if (Validator.isNotNull(counterConfig.getStartCounter()) && counterConfig.getStartCounter() > 0) {
String patternCode = counterConfig.getPatternCode();
try {
_log.info("dossierId: " + dossier.getDossierId() + "| option.getProcessOptionId(): "
+ option.getProcessOptionId() + "| serviceProcess.getCounterCode(): "
+ serviceProcess.getCounterCode() + "| getStartCounter(): "
+ counterConfig.getStartCounter());
String dossierCounter = ConfigCounterNumberGenerator.generateCounterNumber(dossier.getGroupId(),
dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(),
patternCode, counterConfig, params);
dossier.setDossierCounter(dossierCounter.trim());
_log.info("dossierCounter: " + dossierCounter);
} catch (Exception e) {
_log.debug(e);
}
} else {
String patternCode = counterConfig.getPatternCode();
try {
_log.info("dossierId: " + dossier.getDossierId() + "| option.getProcessOptionId(): "
+ option.getProcessOptionId() + "| serviceProcess.getCounterCode(): "
+ serviceProcess.getCounterCode());
String dossierCounter = ConfigCounterNumberGenerator.generateCounterNumber(dossier.getGroupId(),
dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(),
patternCode, counterConfig, params);
dossier.setDossierCounter(dossierCounter.trim());
_log.info("dossierCounter: " + dossierCounter);
} catch (Exception e) {
_log.debug(e);
}
}
}
}
THANHNV: end
*/
dossier = setDossierNoNDueDate(dossier, serviceProcess, option, true, false, null, params);
}
//Check if dossier is done
if (DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)) {
List<DossierFile> lstFiles = dossierFileLocalService.getAllDossierFile(dossier.getDossierId());
int countTemplateNo = 0;
for (DossierFile df : lstFiles) {
//GS. Ta Tuan Anh
if (!df.getRemoved()) {
df.setOriginal(true);
}
dossierFileLocalService.updateDossierFile(df);
//GS. DuanTV ApplicantData
if (Validator.isNotNull(df.getFileTemplateNo())) {
countTemplateNo++;
}
}
String[] fileTemplateNos = new String[countTemplateNo];
DossierFile[] files = new DossierFile[countTemplateNo];
int count = 0;
for (DossierFile df : lstFiles) {
if (Validator.isNotNull(df.getFileTemplateNo())) {
files[count] = df;
fileTemplateNos[count++] = df.getFileTemplateNo();
}
}
List<FileItem> lstFileItems = FileItemLocalServiceUtil.findByG_FTNS(dossier.getGroupId(), fileTemplateNos);
for (int i = 0; i < lstFileItems.size(); i++) {
FileItem item = lstFileItems.get(i);
try {
ApplicantDataLocalServiceUtil.updateApplicantData(context, dossier.getGroupId(),
item.getFileTemplateNo(),
files[i].getDisplayName(),
files[i].getFileEntryId(),
StringPool.BLANK,
ApplicantDataTerm.STATUS_ACTIVE,
dossier.getApplicantIdNo(),
1,
dossier.getDossierNo(),
StringPool.BLANK);
} catch (SystemException e) {
_log.debug(e);
} catch (PortalException e) {
_log.debug(e);
}
}
}
//Calculate step due date
// DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId());
// _log.info("dossierAction: "+dossierAction);
dossierAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId());
Date rootDate = now;
Date dueDate = null;
// if (prevAction != null) {
// if (prevAction.getDueDate() != null) {
// if (rootDate.getTime() < prevAction.getDueDate().getTime()) {
// rootDate = prevAction.getDueDate();
// }
// }
// }
Double durationCount = processStep.getDurationCount();
// _log.info("durationCountStep: "+durationCount);
int durationUnit = serviceProcess.getDurationUnit();
// _log.info("Calculate do action duration count: " + durationCount);
if (Validator.isNotNull(durationCount) && durationCount > 0
&& !areEqualDouble(durationCount, 0.00d, 3)) {
// _log.info("========STEP DUE DATE CACULATE DUE DATE");
DueDateUtils dueDateUtils = new DueDateUtils(rootDate, durationCount, durationUnit, dossier.getGroupId());
// dueDate = HolidayUtils.getDueDate(rootDate, durationCount, durationUnit, dossier.getGroupId());
dueDate = dueDateUtils.getDueDate();
// _log.info("dueDateAction: "+dueDate);
}
// _log.info("========STEP DUE DATE:" + dueDate);
// DossierLocalServiceUtil.updateDossier(dossier);
// _log.info("dossierAction: " + dossierAction);
if (dossierAction != null) {
// _log.info("========STEP DUE DATE ACTION:" + dueDate);
if (dueDate != null) {
long dateNowTimeStamp = now.getTime();
Long dueDateTimeStamp = dueDate.getTime();
int overdue = 0;
// _log.info("dueDateTEST: "+dueDate);
// _log.info("Due date timestamp: " + dueDateTimeStamp);
if (dueDateTimeStamp != null && dueDateTimeStamp > 0) {
long subTimeStamp = dueDateTimeStamp - dateNowTimeStamp;
if (subTimeStamp > 0) {
overdue = calculatorOverDue(durationUnit, subTimeStamp);
// overdue = calculatorOverDue(durationUnit, subTimeStamp, dateNowTimeStamp, dueDateTimeStamp,
// dossierAction.getGroupId(), true);
} else {
overdue = -calculatorOverDue(durationUnit, subTimeStamp);
//// calculatorOverDue(int durationUnit, long subTimeStamp, long releaseDateTimeStamp,
//// long dueDateTimeStamp, long groupId, true);
// overdue = -calculatorOverDue(durationUnit, subTimeStamp, dateNowTimeStamp, dueDateTimeStamp,
// dossierAction.getGroupId(), true);
}
} else {
}
// _log.info("dueDateTEST111: "+dueDate);
dossierAction.setActionOverdue(overdue);
dossierAction.setDueDate(dueDate);
// _log.info("========STEP DUE DATE SET DUE DATE: " + dossierAction.getStepCode());
// DossierAction dActTest = DossierActionLocalServiceUtil.updateDossierAction(dossierAction);
dossierActionLocalService.updateDossierAction(dossierAction);
// _log.info("dActTest: "+dActTest);
}
else {
dossierActionLocalService.updateDossierAction(dossierAction);
}
}
return bResult;
}
public static boolean areEqualDouble(double a, double b, int precision) {
return Math.abs(a - b) <= Math.pow(10, -precision);
}
private static int calculatorOverDue(int durationUnit, long subTimeStamp) {
if (subTimeStamp < 0) {
subTimeStamp = Math.abs(subTimeStamp);
}
double dueCount;
double overDue;
int retval = Double.compare(durationUnit, 1.0);
if (retval < 0) {
dueCount = (double) subTimeStamp / VALUE_CONVERT_DATE_TIMESTAMP;
double subDueCount = (double) Math.round(dueCount * 100) / 100;
overDue = (double) Math.ceil(subDueCount * 4) / 4;
return (int)overDue;
} else {
dueCount = (double) subTimeStamp / VALUE_CONVERT_HOUR_TIMESTAMP;
overDue = (double) Math.round(dueCount);
}
return (int)overDue;
}
private JSONObject processMergeDossierFormData(Dossier dossier, JSONObject jsonData) {
jsonData.put(DossierTerm.GOV_AGENCY_CODE, dossier.getGovAgencyCode());
jsonData.put(DossierTerm.GOV_AGENCY_NAME, dossier.getGovAgencyName());
jsonData.put(DossierTerm.APPLICANT_ID_NO, dossier.getApplicantIdNo());
jsonData.put(DossierTerm.APPLICANT_ID_TYPE, dossier.getApplicantIdType());
jsonData.put(DossierTerm.APPLICANT_ID_DATE,
APIDateTimeUtils.convertDateToString(dossier.getApplicantIdDate(), APIDateTimeUtils._NORMAL_PARTTERN));
jsonData.put(DossierTerm.CITY_CODE, dossier.getCityCode());
jsonData.put(DossierTerm.CITY_NAME, dossier.getCityName());
jsonData.put(DossierTerm.DISTRICT_CODE, dossier.getDistrictCode());
jsonData.put(DossierTerm.DISTRICT_NAME, dossier.getDistrictName());
jsonData.put(DossierTerm.WARD_CODE, dossier.getWardCode());
jsonData.put(DossierTerm.WARD_NAME, dossier.getWardName());
jsonData.put(DossierTerm.DOSSIER_NO, dossier.getDossierNo());
jsonData.put(DossierTerm.APPLICANT_NAME, dossier.getApplicantName());
jsonData.put(DossierTerm.ADDRESS, dossier.getAddress());
jsonData.put(DossierTerm.CONTACT_TEL_NO, dossier.getContactTelNo());
jsonData.put(DossierTerm.CONTACT_EMAIL, dossier.getContactEmail());
jsonData.put(DossierTerm.CONTACT_NAME, dossier.getContactName());
jsonData.put(DossierTerm.DELEGATE_ADDRESS, dossier.getDelegateAddress());
jsonData.put(DossierTerm.SERVICE_CODE, dossier.getServiceCode());
jsonData.put(DossierTerm.SERVICE_NAME, dossier.getServiceName());
jsonData.put(DossierTerm.SAMPLE_COUNT, dossier.getSampleCount());
jsonData.put(DossierTerm.DURATION_UNIT, dossier.getDurationUnit());
jsonData.put(DossierTerm.DURATION_COUNT, dossier.getDurationCount());
jsonData.put(DossierTerm.SECRET_KEY, dossier.getPassword());
jsonData.put(DossierTerm.RECEIVE_DATE,
APIDateTimeUtils.convertDateToString(dossier.getReceiveDate(), APIDateTimeUtils._NORMAL_PARTTERN));
jsonData.put(DossierTerm.DELEGATE_NAME, dossier.getDelegateName());
jsonData.put(DossierTerm.DELEGATE_EMAIL, dossier.getDelegateEmail());
jsonData.put(DossierTerm.DELEGATE_TELNO, dossier.getDelegateTelNo());
jsonData.put(DossierTerm.DOSSIER_NAME, dossier.getDossierName());
jsonData.put(DossierTerm.VIA_POSTAL, dossier.getViaPostal());
jsonData.put(DossierTerm.POSTAL_ADDRESS, dossier.getPostalAddress());
jsonData.put(DossierTerm.APPLICANT_NOTE, dossier.getApplicantNote());
jsonData.put(DossierTerm.DOSSIER_COUNTER, dossier.getDossierCounter());
// MetaData
String metaData = dossier.getMetaData();
if (Validator.isNotNull(metaData)) {
try {
JSONObject jsonMetaData = JSONFactoryUtil.createJSONObject(metaData);
//
Iterator<String> keys = jsonMetaData.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = jsonMetaData.getString(key);
if (Validator.isNotNull(value)) {
try {
JSONArray valueObject = JSONFactoryUtil.createJSONArray(value);
jsonData.put(key, valueObject);
} catch (JSONException e) {
_log.debug(e);
try {
JSONObject valueObject = JSONFactoryUtil.createJSONObject(value);
jsonData.put(key, valueObject);
} catch (JSONException e1) {
_log.debug(e1);
jsonData.put(key, value);
}
}
}
}
} catch (JSONException e) {
_log.debug(e);
}
}
try {
ServiceInfo service = ServiceInfoLocalServiceUtil.getByCode(dossier.getGroupId(), dossier.getServiceCode());
jsonData.put(ServiceInfoTerm.FEE_TEXT, service != null ? service.getFeeText() : StringPool.BLANK);
jsonData.put(ServiceInfoTerm.DURATION_TEXT, service != null ? service.getDurationText() : StringPool.BLANK);
} catch (PortalException e1) {
_log.debug(e1);
jsonData.put(ServiceInfoTerm.FEE_TEXT, StringPool.BLANK);
jsonData.put(ServiceInfoTerm.DURATION_TEXT, StringPool.BLANK);
}
//
Date dueDate = dossier.getDueDate();
if (dueDate != null) {
ServiceProcess process = ServiceProcessLocalServiceUtil.getByG_PNO(dossier.getGroupId(),
dossier.getProcessNo());
if (process != null) {
String dueDatePattern = process.getDueDatePattern();
//_log.info("dueDatePattern: " + dueDatePattern);
// _log.info("START DUEDATE TEST");
if (Validator.isNotNull(dueDatePattern)) {
//_log.info("START DUEDATE TEST");
// _log.info("dueDatePattern: "+dueDatePattern);
try {
JSONObject jsonDueDate = JSONFactoryUtil.createJSONObject(dueDatePattern);
//_log.info("jsonDueDate: " + jsonDueDate);
if (jsonDueDate != null) {
JSONObject hours = jsonDueDate.getJSONObject(KeyPayTerm.HOUR);
JSONObject processHours = jsonDueDate.getJSONObject(KeyPayTerm.PROCESSHOUR);
//_log.info("hours: " + hours);
if (hours != null && hours.has(KeyPayTerm.AM) && hours.has(KeyPayTerm.PM)) {
//_log.info("AM-PM: ");
Calendar receiveCalendar = Calendar.getInstance();
receiveCalendar.setTime(dossier.getReceiveDate());
Calendar dueCalendar = Calendar.getInstance();
//_log.info("hours: " + receiveCalendar.get(Calendar.HOUR_OF_DAY));
if (receiveCalendar.get(Calendar.HOUR_OF_DAY) < 12) {
dueCalendar.setTime(dossier.getDueDate());
String hoursAfterNoon = hours.getString(KeyPayTerm.AM);
//_log.info("hoursAfterNoon: " + hoursAfterNoon);
if (Validator.isNotNull(hoursAfterNoon)) {
String[] splitAfter = StringUtil.split(hoursAfterNoon, StringPool.COLON);
if (splitAfter != null) {
dueCalendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(splitAfter[0]));
dueCalendar.set(Calendar.MINUTE, Integer.valueOf(splitAfter[1]));
}
}
} else {
dueCalendar.setTime(dossier.getDueDate());
String hoursAfterNoon = hours.getString(KeyPayTerm.PM);
if (Validator.isNotNull(hoursAfterNoon)) {
String[] splitAfter = StringUtil.split(hoursAfterNoon, StringPool.COLON);
if (splitAfter != null) {
if (Integer.valueOf(splitAfter[0]) < 12) {
dueCalendar.add(Calendar.DAY_OF_MONTH, 1);
dueCalendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(splitAfter[0]));
dueCalendar.set(Calendar.MINUTE, Integer.valueOf(splitAfter[1]));
} else {
//dueCalendar.add(Calendar.DAY_OF_MONTH, 1);
dueCalendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(splitAfter[0]));
dueCalendar.set(Calendar.MINUTE, Integer.valueOf(splitAfter[1]));
}
}
}
}
jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils
.convertDateToString(dueCalendar.getTime(), APIDateTimeUtils._NORMAL_PARTTERN));
} else if (processHours != null && processHours.has(KeyPayTerm.STARTHOUR) && processHours.has(KeyPayTerm.DUEHOUR)) {
//_log.info("STRART check new: ");
Calendar receiveCalendar = Calendar.getInstance();
receiveCalendar.setTime(dossier.getReceiveDate());
//
String receiveHour = processHours.getString(KeyPayTerm.STARTHOUR);
//_log.info("receiveHour: " + receiveHour);
if (Validator.isNotNull(receiveHour)) {
String[] splitHour = StringUtil.split(receiveHour, StringPool.COLON);
if (splitHour != null) {
int hourStart = GetterUtil.getInteger(splitHour[0]);
if (receiveCalendar.get(Calendar.HOUR_OF_DAY) < hourStart) {
String[] splitdueHour = StringUtil.split(processHours.getString(KeyPayTerm.DUEHOUR),
StringPool.COLON);
Calendar dueCalendar = Calendar.getInstance();
if (splitdueHour != null) {
dueCalendar.set(Calendar.HOUR_OF_DAY,
GetterUtil.getInteger(splitdueHour[0]));
dueCalendar.set(Calendar.MINUTE,
GetterUtil.getInteger(splitdueHour[1]));
} else {
jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString(
dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN));
}
jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString(
dueCalendar.getTime(), APIDateTimeUtils._NORMAL_PARTTERN));
} else {
jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString(
dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN));
}
}
}
} else {
jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils
.convertDateToString(dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN));
}
} else {
jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils
.convertDateToString(dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN));
}
} catch (JSONException e) {
_log.error(e);
jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString(dossier.getDueDate(),
APIDateTimeUtils._NORMAL_PARTTERN));
}
} else {
jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString(dossier.getDueDate(),
APIDateTimeUtils._NORMAL_PARTTERN));
}
} else {
jsonData.put(DossierTerm.DUE_DATE,
APIDateTimeUtils.convertDateToString(dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN));
}
} else {
jsonData.put(DossierTerm.DUE_DATE, StringPool.BLANK);
}
//
jsonData.put(DossierTerm.POSTAL_ADDRESS, dossier.getPostalAddress());
jsonData.put(DossierTerm.COUNTER, dossier.getCounter());
jsonData.put(DossierTerm.REGISTER_BOOK_CODE, dossier.getRegisterBookCode());
jsonData.put(DossierTerm.SECRET, dossier.getPassword());
jsonData.put(DossierTerm.BRIEF_NOTE, dossier.getBriefNote());
jsonData.put(DossierTerm.DOSSIER_ID, dossier.getDossierId());
//
long groupId = dossier.getGroupId();
JSONArray dossierMarkArr = JSONFactoryUtil.createJSONArray();
long dossierId = dossier.getDossierId();
String templateNo = dossier.getDossierTemplateNo();
List<DossierMark> dossierMarkList = DossierMarkLocalServiceUtil.getDossierMarksByFileMark(groupId, dossierId, 0);
if (dossierMarkList != null && dossierMarkList.size() > 0) {
JSONObject jsonMark = null;
String partNo;
for (DossierMark dossierMark : dossierMarkList) {
jsonMark = JSONFactoryUtil.createJSONObject();
partNo = dossierMark.getDossierPartNo();
if (Validator.isNotNull(partNo)) {
DossierPart part = DossierPartLocalServiceUtil.getByTempAndPartNo(groupId, templateNo, partNo);
if (part != null) {
jsonMark.put(DossierPartTerm.DOSSIERPART_ID, part.getDossierPartId());
jsonMark.put(DossierPartTerm.PART_NAME, part.getPartName());
jsonMark.put(DossierPartTerm.PART_TIP, part.getPartTip());
jsonMark.put(DossierPartTerm.PART_TYPE, part.getPartType());
}
}
jsonMark.put(DossierPartTerm.PART_NO, partNo);
jsonMark.put(DossierPartTerm.FILE_MARK, dossierMark.getFileMark());
jsonMark.put(DossierPartTerm.FILE_CHECK, dossierMark.getFileCheck());
jsonMark.put(DossierPartTerm.FILE_COMMENT, dossierMark.getFileComment());
jsonMark.put(DossierPartTerm.RECORD_COUNT, dossierMark.getRecordCount());
// String strDossierMark = JSONFactoryUtil.looseSerialize(dossierMark);
dossierMarkArr.put(jsonMark);
}
}
//Hot fix TP99
DossierMark dossierMark = DossierMarkLocalServiceUtil.getDossierMarkbyDossierId(groupId, dossierId, KeyPayTerm.TP99);
if (dossierMark != null) {
JSONObject jsonMark = null;
String partNo = dossierMark.getDossierPartNo();
if (Validator.isNotNull(partNo)) {
List<DossierFile> fileList = DossierFileLocalServiceUtil.getDossierFileByDID_DPNO(dossierId, partNo, false);
DossierPart part = DossierPartLocalServiceUtil.getByTempAndPartNo(groupId, templateNo, partNo);
if (fileList != null && part != null) {
for (DossierFile dossierFile : fileList) {
jsonMark = JSONFactoryUtil.createJSONObject();
jsonMark.put(DossierPartTerm.PART_NAME, dossierFile.getDisplayName());
jsonMark.put(DossierPartTerm.DOSSIERPART_ID, part.getDossierPartId());
jsonMark.put(DossierPartTerm.PART_TIP, part.getPartTip());
jsonMark.put(DossierPartTerm.PART_TYPE, part.getPartType());
jsonMark.put(DossierPartTerm.PART_NO, partNo);
jsonMark.put(DossierPartTerm.FILE_MARK, dossierMark.getFileMark());
jsonMark.put(DossierPartTerm.FILE_CHECK, dossierMark.getFileCheck());
jsonMark.put(DossierPartTerm.FILE_COMMENT, dossierMark.getFileComment());
jsonMark.put(DossierPartTerm.RECORD_COUNT, dossierMark.getRecordCount());
// String strDossierMark = JSONFactoryUtil.looseSerialize(dossierMark);
dossierMarkArr.put(jsonMark);
}
}
}
}
jsonData.put(DossierTerm.DOSSIER_MARKS, dossierMarkArr);
PaymentFile payment = PaymentFileLocalServiceUtil.getByDossierId(groupId, dossierId);
if (payment != null) {
jsonData.put(PaymentFileTerm.ADVANCE_AMOUNT, payment.getAdvanceAmount());
jsonData.put(PaymentFileTerm.PAYMENT_AMOUNT, payment.getPaymentAmount());
jsonData.put(PaymentFileTerm.PAYMENT_FEE, payment.getPaymentFee());
jsonData.put(PaymentFileTerm.SERVICE_AMOUNT, payment.getServiceAmount());
jsonData.put(PaymentFileTerm.SHIP_AMOUNT, payment.getShipAmount());
}
if (dossier.getOriginality() == DossierTerm.ORIGINALITY_HOSONHOM) {
JSONArray groupDossierArr = JSONFactoryUtil.createJSONArray();
List<Dossier> lstDossiers = DossierLocalServiceUtil.findByG_GDID(groupId, dossier.getDossierId());
for (Dossier d : lstDossiers) {
JSONObject dObject = JSONFactoryUtil.createJSONObject();
dObject.put(DossierTerm.DOSSIER_NO, d.getDossierNo());
dObject.put(DossierTerm.APPLICANT_NAME, d.getApplicantName());
dObject.put(DossierTerm.ADDRESS, d.getAddress());
dObject.put(DossierTerm.CONTACT_TEL_NO, d.getContactTelNo());
dObject.put(DossierTerm.CONTACT_EMAIL, d.getContactEmail());
dObject.put(DossierTerm.CONTACT_NAME, d.getContactName());
dObject.put(DossierTerm.DELEGATE_ADDRESS, d.getDelegateAddress());
dObject.put(DossierTerm.SERVICE_CODE, d.getServiceCode());
dObject.put(DossierTerm.SERVICE_NAME, d.getServiceName());
dObject.put(DossierTerm.SAMPLE_COUNT, d.getSampleCount());
dObject.put(DossierTerm.DURATION_UNIT, d.getDurationUnit());
dObject.put(DossierTerm.DURATION_COUNT, d.getDurationCount());
dObject.put(DossierTerm.SECRET_KEY, d.getPassword());
dObject.put(DossierTerm.RECEIVE_DATE,
APIDateTimeUtils.convertDateToString(d.getReceiveDate(), APIDateTimeUtils._NORMAL_PARTTERN));
dObject.put(DossierTerm.DELEGATE_NAME, d.getDelegateName());
dObject.put(DossierTerm.DELEGATE_EMAIL, d.getDelegateEmail());
dObject.put(DossierTerm.DELEGATE_TELNO, d.getDelegateTelNo());
dObject.put(DossierTerm.DOSSIER_NAME, d.getDossierName());
dObject.put(DossierTerm.VIA_POSTAL, d.getViaPostal());
dObject.put(DossierTerm.POSTAL_ADDRESS, d.getPostalAddress());
groupDossierArr.put(dObject);
}
jsonData.put(DossierTerm.GROUP_DOSSIERS, groupDossierArr);
}
DictCollection govCollection = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(GOVERNMENT_AGENCY, dossier.getGroupId());
if (govCollection != null) {
DictItem govAgenItem = DictItemLocalServiceUtil.fetchByF_dictItemCode(dossier.getGovAgencyCode(), govCollection.getDictCollectionId(), dossier.getGroupId());
String metaDataItem = govAgenItem.getMetaData();
try {
JSONObject metaObj = JSONFactoryUtil.createJSONObject(metaDataItem);
if (govAgenItem != null) {
if (metaObj.has(BN_TELEPHONE)) {
jsonData.put(BN_TELEPHONE, metaObj.getString(BN_TELEPHONE));
}
if (metaObj.has(BN_EMAIL)) {
jsonData.put(BN_EMAIL, metaObj.getString(BN_EMAIL));
}
if (metaObj.has(BN_ADDRESS)) {
jsonData.put(BN_ADDRESS, metaObj.getString(BN_ADDRESS));
}
}
}
catch (Exception e) {
_log.debug(e);
}
}
if (jsonData.has(DossierTerm.EXTEND_DATE) && Validator.isNotNull(jsonData.get(DossierTerm.EXTEND_DATE))
&& GetterUtil.getLong(jsonData.get(DossierTerm.EXTEND_DATE)) > 0) {
Date extendDate = new Date(GetterUtil.getLong(jsonData.get(DossierTerm.EXTEND_DATE)));
jsonData.put(DossierTerm.EXTEND_DATE, APIDateTimeUtils.convertDateToString(extendDate, APIDateTimeUtils._NORMAL_DATE_TIME));
}
//Notarization
ServiceInfo si;
try {
si = ServiceInfoLocalServiceUtil.getByCode(dossier.getGroupId(), dossier.getServiceCode());
if (si != null) {
jsonData.put(ServiceInfoTerm.IS_NOTARIZATION, si.isIsNotarization());
}
else {
jsonData.put(ServiceInfoTerm.IS_NOTARIZATION, false);
}
} catch (PortalException e) {
_log.debug(e);
}
List<Notarization> lstNotarizations = NotarizationLocalServiceUtil.findByG_DID(groupId, dossierId);
JSONArray notarizationArr = JSONFactoryUtil.createJSONArray();
for (Notarization nt : lstNotarizations) {
JSONObject notObj = JSONFactoryUtil.createJSONObject();
notObj.put(NotarizationTerm.NOTARIZATION_ID, nt.getNotarizationId());
notObj.put(NotarizationTerm.DOSSIER_ID, nt.getDossierId());
notObj.put(NotarizationTerm.GROUP_ID, nt.getGroupId());
notObj.put(NotarizationTerm.FILE_NAME, nt.getFileName());
notObj.put(NotarizationTerm.NOTARIZATION_DATE, nt.getNotarizationDate() != null ? APIDateTimeUtils.convertDateToString(nt.getNotarizationDate(), APIDateTimeUtils._NORMAL_PARTTERN) : StringPool.BLANK);
notObj.put(NotarizationTerm.NOTARIZATION_NO, nt.getNotarizationNo());
notObj.put(NotarizationTerm.NOTARIZATION_YEAR, nt.getNotarizationYear());
notObj.put(NotarizationTerm.SIGNER_NAME, nt.getSignerName());
notObj.put(NotarizationTerm.SIGNER_POSITION, nt.getSignerPosition());
notObj.put(NotarizationTerm.STATUS_CODE, nt.getStatusCode());
notObj.put(NotarizationTerm.TOTAL_COPY, nt.getTotalCopy());
notObj.put(NotarizationTerm.TOTAL_FEE, nt.getTotalFee());
notObj.put(NotarizationTerm.TOTAL_PAGE, nt.getTotalPage());
notObj.put(NotarizationTerm.TOTAL_RECORD, nt.getTotalRecord());
notarizationArr.put(notObj);
}
jsonData.put(DossierTerm.NOTARIZATIONS, notarizationArr);
return jsonData;
}
//LamTV_ Mapping process dossier and formData
private JSONObject processMergeDossierProcessRole(Dossier dossier, int length, JSONObject jsonData,
DossierAction dAction) {
//
long groupId = dossier.getGroupId();
if (dAction != null) {
long serviceProcessId = dAction.getServiceProcessId();
jsonData.put(DossierTerm.GOV_AGENCY_NAME, dossier.getGovAgencyName());
jsonData.put(DossierTerm.TOTAL, length);
jsonData.put(DossierTerm.ACTION_USER, dAction.getActionUser());
String sequenceNo = dAction.getSequenceNo();
if (Validator.isNotNull(sequenceNo)) {
ProcessSequence sequence = ProcessSequenceLocalServiceUtil.findBySID_SNO(groupId, serviceProcessId,
sequenceNo);
if (sequence != null) {
jsonData.put(DossierTerm.SEQUENCE_ROLE, sequence.getSequenceRole());
} else {
jsonData.put(DossierTerm.SEQUENCE_ROLE, StringPool.BLANK);
}
} else {
jsonData.put(DossierTerm.SEQUENCE_ROLE, StringPool.BLANK);
}
// Process get Next sequence Role
//List<ProcessSequence> sequenceList = ProcessSequenceLocalServiceUtil.getByServiceProcess(groupId,
// serviceProcessId);
//TODO: Using cache
// List<ProcessSequence> sequenceList = null;
// Serializable data = CacheLocalServiceUtil.getFromCache("ProcessSequence", groupId +"_"+serviceProcessId);
// if (data != null) {
// sequenceList = (List<ProcessSequence>) data;
// } else {
// sequenceList = ProcessSequenceLocalServiceUtil.getByServiceProcess(groupId,
// serviceProcessId);
// if (sequenceList != null) {
// //_log.info("START_ Serlist null");
// CacheLocalServiceUtil.addToCache("ProcessSequence",
// groupId +"_"+serviceProcessId, (Serializable) sequenceList,
// (int) Time.MINUTE * 30);
// }
// }
List<ProcessSequence> sequenceList = ProcessSequenceLocalServiceUtil.getByServiceProcess(groupId,
serviceProcessId);
String[] sequenceArr = null;
if (sequenceList != null && !sequenceList.isEmpty()) {
int lengthSeq = sequenceList.size();
sequenceArr = new String[lengthSeq];
for (int i = 0; i < lengthSeq; i++) {
ProcessSequence processSequence = sequenceList.get(i);
if (processSequence != null) {
sequenceArr[i] = processSequence.getSequenceNo();
}
}
}
if (sequenceArr != null && sequenceArr.length > 0) {
Arrays.sort(sequenceArr);
for (int i = 0; i < sequenceArr.length - 1; i++) {
String seq = sequenceArr[i];
if (sequenceNo.equals(seq)) {
String nextSequenceNo = sequenceArr[i + 1];
if (Validator.isNotNull(nextSequenceNo)) {
ProcessSequence sequence = ProcessSequenceLocalServiceUtil.findBySID_SNO(groupId,
serviceProcessId, nextSequenceNo);
if (sequence != null) {
jsonData.put(DossierTerm.NEXT_SEQUENCE_ROLE, sequence.getSequenceRole());
} else {
jsonData.put(DossierTerm.NEXT_SEQUENCE_ROLE, StringPool.BLANK);
}
} else {
jsonData.put(DossierTerm.NEXT_SEQUENCE_ROLE, StringPool.BLANK);
}
}
}
} else {
jsonData.put(DossierTerm.NEXT_SEQUENCE_ROLE, StringPool.BLANK);
}
//Process array sequence
JSONArray jsonSequenceArr = getProcessSequencesJSON(sequenceArr, sequenceList);
if (jsonSequenceArr != null) {
jsonData.put(KeyPayTerm.processSequenceArr, jsonSequenceArr);
}
}
return jsonData;
}
private static JSONArray getProcessSequencesJSON(String[] sequenceArr, List<ProcessSequence> sequenceList) {
JSONArray jsonSequenceArr = JSONFactoryUtil.createJSONArray();
if (sequenceArr != null && sequenceArr.length > 0) {
for (int i = 0; i < sequenceArr.length - 1; i++) {
String sequenceNo = sequenceArr[i];
JSONObject sequenceObj = JSONFactoryUtil.createJSONObject();
for (ProcessSequence proSeq : sequenceList) {
if (sequenceNo.equals(proSeq.getSequenceNo())) {
sequenceObj.put(DossierTerm.SEQUENCE_NO, proSeq.getSequenceNo());
sequenceObj.put(DossierTerm.SEQUENCE_NAME, proSeq.getSequenceName());
sequenceObj.put(DossierTerm.SEQUENCE_ROLE, proSeq.getSequenceRole());
sequenceObj.put(DossierTerm.DURATION_COUNT, proSeq.getDurationCount());
sequenceObj.put(Field.CREATE_DATE, proSeq.getCreateDate());
}
}
String nextSequenceNo = sequenceArr[i + 1];
for (ProcessSequence proSeq : sequenceList) {
if (nextSequenceNo.equals(proSeq.getSequenceNo())) {
sequenceObj.put(DossierTerm.NEXT_SEQUENCE_NO, proSeq.getSequenceNo());
sequenceObj.put(DossierTerm.NEXT_SEQUENCE_NAME, proSeq.getSequenceName());
sequenceObj.put(DossierTerm.NEXT_SEQUENCE_ROLE, proSeq.getSequenceRole());
sequenceObj.put(DossierTerm.NEXT_CREATE_DATE, proSeq.getCreateDate());
}
}
jsonSequenceArr.put(sequenceObj);
}
}
return jsonSequenceArr;
}
private void vnpostEvent(Dossier dossier, long dossierActionId) {
Message message = new Message();
JSONObject msgData = JSONFactoryUtil.createJSONObject();
message.put(ConstantUtils.MSG_ENG, msgData);
message.put(DossierTerm.CONSTANT_DOSSIER, DossierMgtUtils.convertDossierToJSON(dossier, dossierActionId));
MessageBusUtil.sendMessage(DossierTerm.VNPOST_DOSSIER_DESTINATION, message);
}
private void collectVnpostEvent(Dossier dossier, long dossierActionId) {
Message message = new Message();
JSONObject msgData = JSONFactoryUtil.createJSONObject();
message.put(ConstantUtils.MSG_ENG, msgData);
message.put(DossierTerm.CONSTANT_DOSSIER, DossierMgtUtils.convertDossierToJSON(dossier, dossierActionId));
_log.info("=============create collectVnpostEvent============");
MessageBusUtil.sendMessage(DossierTerm.COLLECTION_VNPOST_DOSSIER_DESTINATION, message);
}
private void publishEvent(Dossier dossier, ServiceContext context, long dossierActionId) {
if (dossier.getOriginDossierId() != 0 || Validator.isNotNull(dossier.getOriginDossierNo())) {
return;
}
Message message = new Message();
JSONObject msgData = JSONFactoryUtil.createJSONObject();
message.put(ConstantUtils.MSG_ENG, msgData);
message.put(DossierTerm.CONSTANT_DOSSIER, DossierMgtUtils.convertDossierToJSON(dossier, dossierActionId));
// MessageBusUtil.sendMessage(DossierTerm.PUBLISH_DOSSIER_DESTINATION, message);
Message lgspMessage = new Message();
JSONObject lgspMsgData = msgData;
lgspMessage.put(ConstantUtils.MSG_ENG, lgspMsgData);
lgspMessage.put(DossierTerm.CONSTANT_DOSSIER, DossierMgtUtils.convertDossierToJSON(dossier, dossierActionId));
// MessageBusUtil.sendMessage(DossierTerm.LGSP_DOSSIER_DESTINATION, lgspMessage);
//Add publish queue
List<ServerConfig> lstScs = ServerConfigLocalServiceUtil.getByProtocol(dossier.getGroupId(), ServerConfigTerm.PUBLISH_PROTOCOL);
for (ServerConfig sc : lstScs) {
try {
List<PublishQueue> lstQueues = PublishQueueLocalServiceUtil.getByG_DID_SN_ST(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo(), new int[] { PublishQueueTerm.STATE_WAITING_SYNC, PublishQueueTerm.STATE_ALREADY_SENT });
if (lstQueues == null || lstQueues.isEmpty()) {
publishQueueLocalService.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
}
// PublishQueue pq = PublishQueueLocalServiceUtil.getByG_DID_SN(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo());
// if (pq == null) {
// PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
// }
// else {
// if (pq.getStatus() == PublishQueueTerm.STATE_ACK_ERROR) {
// PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), pq.getPublishQueueId(), dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
// }
// }
} catch (PortalException e) {
_log.debug(e);
}
}
lstScs = ServerConfigLocalServiceUtil.getByProtocol(dossier.getGroupId(), ServerConfigTerm.LGSP_PROTOCOL);
for (ServerConfig sc : lstScs) {
try {
List<PublishQueue> lstQueues = publishQueueLocalService.getByG_DID_SN_ST(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo(), new int[] { PublishQueueTerm.STATE_WAITING_SYNC, PublishQueueTerm.STATE_ALREADY_SENT });
if (lstQueues == null || lstQueues.isEmpty()) {
publishQueueLocalService.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
}
// PublishQueue pq = PublishQueueLocalServiceUtil.getByG_DID_SN(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo());
// if (pq == null) {
// PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
// }
// else {
// if (pq.getStatus() == PublishQueueTerm.STATE_ACK_ERROR) {
// PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), pq.getPublishQueueId(), dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
// }
// }
} catch (PortalException e) {
_log.debug(e);
}
}
//add by TrungNT
DVCQGIntegrationActionImpl actionImpl = new DVCQGIntegrationActionImpl();
String mappingDossierStatus = actionImpl.getMappingStatus(dossier.getGroupId(), dossier);
if(Validator.isNotNull(mappingDossierStatus)) {
lstScs = ServerConfigLocalServiceUtil.getByProtocol(dossier.getGroupId(), ServerConfigTerm.DVCQG_INTEGRATION);
for (ServerConfig sc : lstScs) {
try {
List<PublishQueue> lstQueues = publishQueueLocalService.getByG_DID_SN_ST(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo(), new int[] { PublishQueueTerm.STATE_WAITING_SYNC, PublishQueueTerm.STATE_ALREADY_SENT });
if (lstQueues == null || lstQueues.isEmpty()) {
publishQueueLocalService.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
}
// PublishQueue pq = PublishQueueLocalServiceUtil.getByG_DID_SN(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo());
// if (pq == null) {
// PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
// }
// else {
// if (pq.getStatus() == PublishQueueTerm.STATE_ACK_ERROR) {
// PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), pq.getPublishQueueId(), dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
// }
// }
} catch (PortalException e) {
_log.debug(e);
}
}
}
}
private ProcessOption getProcessOption(String serviceInfoCode, String govAgencyCode, String dossierTemplateNo,
long groupId) throws PortalException {
ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, serviceInfoCode, govAgencyCode);
return processOptionLocalService.getByDTPLNoAndServiceCF(groupId, dossierTemplateNo,
config.getServiceConfigId());
}
protected ProcessAction getProcessAction(long groupId, long dossierId, String refId, String actionCode,
long serviceProcessId) throws PortalException {
ProcessAction action = null;
try {
List<ProcessAction> actions = processActionLocalService.getByActionCode(groupId, actionCode,
serviceProcessId);
Dossier dossier = getDossier(groupId, dossierId, refId);
String dossierStatus = dossier.getDossierStatus();
String dossierSubStatus = Validator.isNull(dossier.getDossierSubStatus()) ? StringPool.BLANK
: dossier.getDossierSubStatus();
String curStepCode = StringPool.BLANK;
if (dossier.getDossierActionId() > 0) {
DossierAction curAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId());
if (curAction != null) {
curStepCode = curAction.getStepCode();
}
}
for (ProcessAction act : actions) {
String preStepCode = act.getPreStepCode();
if (Validator.isNotNull(curStepCode) && !preStepCode.contentEquals(curStepCode)) continue;
ProcessStep step = processStepLocalService.fetchBySC_GID(preStepCode, groupId, serviceProcessId);
String subStepStatus = StringPool.BLANK;
if (Validator.isNotNull(step)) {
subStepStatus = Validator.isNull(step.getDossierSubStatus()) ? StringPool.BLANK
: step.getDossierSubStatus();
}
if (Validator.isNull(step)) {
action = act;
break;
} else {
if (step.getDossierStatus().contentEquals(dossierStatus)
&& subStepStatus.contentEquals(dossierSubStatus)) {
action = act;
break;
}
}
}
} catch (Exception e) {
_log.debug(e);
//_log.error(e);
throw new NotFoundException("ProcessActionNotFoundException with actionCode= " + actionCode
+ "|serviceProcessId= " + serviceProcessId + "|referenceUid= " + refId + "|groupId= " + groupId);
}
return action;
}
protected Dossier getDossier(long groupId, long dossierId, String refId) throws PortalException {
Dossier dossier = null;
if (dossierId != 0) {
dossier = dossierLocalService.fetchDossier(dossierId);
} else {
dossier = dossierLocalService.getByRef(groupId, refId);
}
return dossier;
}
private String generatorGoodCode(int length) {
String tempGoodCode = _generatorUniqueString(length);
String goodCode;
while (_checkContainsGoodCode(tempGoodCode)) {
tempGoodCode = _generatorUniqueString(length);
}
/*
* while(_testCheck(tempGoodCode)) { tempGoodCode =
* _generatorUniqueString(length); }
*/
goodCode = tempGoodCode;
return goodCode;
}
private boolean _checkContainsGoodCode(String keypayGoodCode) {
boolean isContains = false;
try {
PaymentFile paymentFile = null;//PaymentFileLocalServiceUtil.getByGoodCode(keypayGoodCode);
if (Validator.isNotNull(paymentFile)) {
isContains = true;
}
} catch (Exception e) {
_log.error(e);
isContains = true;
}
return isContains;
}
private DossierAction doActionOutsideProcess(long groupId, long userId, Dossier dossier, ActionConfig actionConfig, ProcessOption option, ProcessAction proAction,
String actionCode, String actionUser, String actionNote, String payload, String assignUsers,
String payment,
int syncType,
ServiceContext context) throws PortalException, SystemException, Exception {
context.setUserId(userId);
DossierAction dossierAction = null;
String dossierStatus = dossier.getDossierStatus().toLowerCase();
if (Validator.isNotNull(dossierStatus) && !"new".equals(dossierStatus)) {
dossier = dossierLocalService.updateDossier(dossier);
}
// ServiceProcess serviceProcess = null;
// if (option != null) {
// long serviceProcessId = option.getServiceProcessId();
// serviceProcess = serviceProcessLocalService.fetchServiceProcess(serviceProcessId);
// }
dossierAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId());
// ActionConfig ac = actionConfigLocalService.getByCode(groupId, actionCode);
ActionConfig ac = actionConfig;
JSONObject payloadObject = JSONFactoryUtil.createJSONObject(payload);
if (Validator.isNotNull(payload)) {
if (DossierActionTerm.OUTSIDE_ACTION_9100.equals(actionCode)) {
dossier = dossierLocalService.updateDossierSpecial(dossier.getDossierId(), payloadObject);
}
else {
dossier = dossierLocalService.updateDossier(dossier.getDossierId(), payloadObject);
}
}
if (DossierActionTerm.OUTSIDE_ACTION_ROLLBACK.equals(actionCode)) {
Dossier hslt = dossierLocalService.getByOrigin(dossier.getGroupId(), dossier.getDossierId());
// chi nguoi thuc hien buoc truoc moi duoc phep quay lai buoc
User user=UserLocalServiceUtil.getUser(userId);
List<Role> userRoles = user.getRoles();
boolean isAdmin = false;
for (Role r : userRoles) {
if (r.getName().startsWith("Administrator")) {
isAdmin = true;
break;
}
}
if (dossierAction != null && !dossierAction.getPending() &&
(dossierAction.isRollbackable() || hslt.getOriginality() < 0)
&& (isAdmin || dossierAction.getUserId() == userId)) {
dossierActionLocalService.updateState(dossierAction.getDossierActionId(), DossierActionTerm.STATE_ROLLBACK);
DossierAction previousAction = dossierActionLocalService.fetchDossierAction(dossierAction.getPreviousActionId());
if (previousAction != null) {
dossierActionLocalService.updateState(previousAction.getDossierActionId(), DossierActionTerm.STATE_WAITING_PROCESSING);
dossierActionLocalService.updateNextActionId(previousAction.getDossierActionId(), 0);
dossierLocalService.rollback(dossier, previousAction);
}
else {
dossierActionLocalService.removeAction(dossierAction.getDossierActionId());
dossier.setDossierActionId(0);
dossier.setOriginality(-dossier.getOriginality());
dossierLocalService.updateDossier(dossier);
}
}
}
//Create DossierSync
String dossierRefUid = dossier.getReferenceUid();
String syncRefUid = UUID.randomUUID().toString();
if (syncType > 0) {
int state = DossierActionUtils.getSyncState(syncType, dossier);
//Update payload
if (Validator.isNotNull(dossier.getServerNo())
&& dossier.getServerNo().split(StringPool.BLANK).length > 1) {
String serverNo = dossier.getServerNo().split(StringPool.COMMA)[0].split(StringPool.AT)[0];
dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid,
dossierAction.getPrimaryKey(), actionCode, ac.getActionName(), actionUser, actionNote,
syncType, ac.getInfoType(), payloadObject.toJSONString(), serverNo, state);
}
else {
dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid,
dossierAction.getPrimaryKey(), actionCode, ac.getActionName(), actionUser, actionNote,
syncType, ac.getInfoType(), payloadObject.toJSONString(), dossier.getServerNo(), state);
}
}
if (ac != null && dossierAction != null) {
//Only create dossier document if 2 && 3
if (dossier.getOriginality() != DossierTerm.ORIGINALITY_DVCTT) {
if (Validator.isNotNull(ac.getDocumentType()) && !ac.getActionCode().startsWith(StringPool.AT)) {
//Generate document
DocumentType dt = documentTypeLocalService.getByTypeCode(groupId, ac.getDocumentType());
if (dt != null) {
String documentCode = DocumentTypeNumberGenerator.generateDocumentTypeNumber(groupId, ac.getCompanyId(), dt.getDocumentTypeId());
DossierDocument dossierDocument = dossierDocumentLocalService.addDossierDoc(groupId, dossier.getDossierId(), UUID.randomUUID().toString(), dossierAction.getDossierActionId(), dt.getTypeCode(), dt.getDocumentName(), documentCode, 0L, dt.getDocSync(), context);
//Generate PDF
String formData = payload;
JSONObject formDataObj = processMergeDossierFormData(dossier, JSONFactoryUtil.createJSONObject(formData));
// _log.info("Dossier document form data action outside: " + formDataObj.toJSONString());
Message message = new Message();
// _log.info("Document script: " + dt.getDocumentScript());
JSONObject msgData = JSONFactoryUtil.createJSONObject();
msgData.put(ConstantUtils.CLASS_NAME, DossierDocument.class.getName());
msgData.put(Field.CLASS_PK, dossierDocument.getDossierDocumentId());
msgData.put(ConstantUtils.JRXML_TEMPLATE, dt.getDocumentScript());
msgData.put(ConstantUtils.FORM_DATA, formDataObj.toJSONString());
msgData.put(Field.USER_ID, userId);
message.put(ConstantUtils.MSG_ENG, msgData);
MessageBusUtil.sendMessage(ConstantUtils.JASPER_DESTINATION, message);
}
}
}
}
if (ac != null && ac.getEventType() == ActionConfigTerm.EVENT_TYPE_SENT && OpenCPSConfigUtil.isPublishEventEnable()) {
publishEvent(dossier, context, dossierAction.getDossierActionId());
}
//Add by TrungNT - Fix tam theo y/k cua a TrungDK va Duantv
if (dossier.isOnline() && proAction != null && "listener".equals(proAction.getAutoEvent().toString()) && OpenCPSConfigUtil.isPublishEventEnable()) {
publishEvent(dossier, context, dossierAction.getDossierActionId());
}
if (OpenCPSConfigUtil.isNotificationEnable()) {
createNotificationQueueOutsideProcess(userId, groupId, dossier, proAction, actionConfig, context);
}
if (DossierActionTerm.OUTSIDE_ACTION_ROLLBACK.equals(actionCode)) {
if (dossier.getOriginDossierId() != 0) {
Dossier hslt = dossierLocalService.fetchDossier(dossier.getOriginDossierId());
ProcessOption optionHslt = getProcessOption(hslt.getServiceCode(), hslt.getGovAgencyCode(),
hslt.getDossierTemplateNo(), groupId);
String actionUserHslt = actionUser;
if (dossier.getOriginDossierId() != 0) {
Dossier originDossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId());
if (originDossier != null) {
DossierAction lastAction = dossierActionLocalService.fetchDossierAction(originDossier.getDossierActionId());
ActionConfig mappingAction = actionConfigLocalService.getByCode(groupId, lastAction.getActionCode());
if (Validator.isNotNull(mappingAction.getMappingAction())) {
DossierAction previousOriginAction = dossierActionLocalService.fetchDossierAction(lastAction.getPreviousActionId());
dossierActionLocalService.updateState(previousOriginAction.getDossierActionId(), DossierActionTerm.STATE_WAITING_PROCESSING);
dossierActionLocalService.updateNextActionId(previousOriginAction.getDossierActionId(), 0);
dossierLocalService.rollback(originDossier, previousOriginAction);
}
}
}
if (DossierTerm.DOSSIER_STATUS_NEW.equals(hslt.getDossierStatus())) {
Date now = new Date();
hslt.setSubmitDate(now);
hslt = dossierLocalService.updateDossier(hslt);
try {
JSONObject payloadObj = JSONFactoryUtil.createJSONObject(payload);
payloadObj.put(DossierTerm.SUBMIT_DATE, now.getTime());
payload = payloadObj.toJSONString();
}
catch (JSONException e) {
_log.debug(e);
}
}
DossierAction lastAction = dossierActionLocalService.fetchDossierAction(hslt.getDossierActionId());
ActionConfig mappingAction = actionConfigLocalService.getByCode(groupId, lastAction.getActionCode());
if (Validator.isNotNull(mappingAction.getMappingAction())) {
doAction(groupId, userId, hslt, optionHslt, null, DossierActionTerm.OUTSIDE_ACTION_ROLLBACK, actionUserHslt, actionNote, payload, assignUsers, payment, 0, context);
}
}
}
return dossierAction;
}
private boolean isSmsNotify(Dossier dossier) {
String metaData = dossier.getMetaData();
if (Validator.isNotNull(metaData)) {
try {
JSONObject jsonMetaData = JSONFactoryUtil.createJSONObject(metaData);
//
Iterator<String> keys = jsonMetaData.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = jsonMetaData.getString(key);
if (Validator.isNotNull(value) && value.contentEquals(DossierTerm.SMS_NOTIFY)) {
try {
Boolean isSmsNotify = Boolean.parseBoolean(value);
return isSmsNotify;
} catch (Exception e) {
_log.debug(e);
}
}
}
} catch (JSONException e) {
_log.debug(e);
}
}
return true;
}
private boolean isEmailNotify(Dossier dossier) {
String metaData = dossier.getMetaData();
if (Validator.isNotNull(metaData)) {
try {
JSONObject jsonMetaData = JSONFactoryUtil.createJSONObject(metaData);
//
Iterator<String> keys = jsonMetaData.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = jsonMetaData.getString(key);
if (Validator.isNotNull(value) && value.contentEquals(DossierTerm.EMAIL_NOTIFY)) {
try {
Boolean isEmailNotify = Boolean.parseBoolean(value);
return isEmailNotify;
} catch (Exception e) {
_log.debug(e);
}
}
}
} catch (JSONException e) {
_log.debug(e);
}
}
return true;
}
private void createNotificationQueueOutsideProcess(long userId, long groupId, Dossier dossier, ProcessAction proAction, ActionConfig actionConfig, ServiceContext context) {
DossierAction dossierAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId());
User u = UserLocalServiceUtil.fetchUser(userId);
JSONObject payloadObj = JSONFactoryUtil.createJSONObject();
payloadObj = buildNotificationPayload(dossier, payloadObj);
try {
JSONObject dossierObj = JSONFactoryUtil.createJSONObject(
JSONFactoryUtil.looseSerialize(dossier));
dossierObj = buildNotificationPayload(dossier, dossierObj);
payloadObj.put(
KeyPayTerm.DOSSIER, dossierObj);
if (dossierAction != null) {
payloadObj.put(DossierActionTerm.ACTION_CODE, dossierAction.getActionCode());
payloadObj.put(DossierActionTerm.ACTION_USER, dossierAction.getActionUser());
payloadObj.put(DossierActionTerm.ACTION_NAME, dossierAction.getActionName());
payloadObj.put(DossierActionTerm.ACTION_NOTE, dossierAction.getActionNote());
}
}
catch (Exception e) {
_log.error(e);
}
String notificationType = StringPool.BLANK;
String preCondition = StringPool.BLANK;
if (actionConfig != null && Validator.isNotNull(actionConfig.getNotificationType())) {
if (actionConfig.getNotificationType().contains(StringPool.AT)) {
String[] split = StringUtil.split(actionConfig.getNotificationType(), StringPool.AT);
if (split.length == 2) {
notificationType = split[0];
preCondition = split[1];
}
}
else {
notificationType = actionConfig.getNotificationType();
}
boolean isSendSMS = NotificationUtil.isSendSMS(preCondition);
boolean isSendEmail = NotificationUtil.isSendEmail(preCondition);
boolean isSendNotiSMS = true;
boolean isSendNotiEmail = true;
if (Validator.isNotNull(preCondition)) {
if (!DossierMgtUtils.checkPreCondition(new String[] { preCondition } , dossier, null)) {
if (isSendSMS) {
isSendNotiSMS = false;
isSendNotiEmail = true;
}
else {
isSendNotiSMS = false;
isSendNotiEmail = false;
}
}
else {
isSendNotiSMS = isSendSMS;
isSendNotiEmail = isSendEmail;
}
}
Notificationtemplate notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, notificationType);
Date now = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(now);
if (notiTemplate != null) {
if (KeyPayTerm.MINUTELY.equals(notiTemplate.getInterval())) {
cal.add(Calendar.MINUTE, notiTemplate.getExpireDuration());
}
else if (KeyPayTerm.HOURLY.equals(notiTemplate.getInterval())) {
cal.add(Calendar.HOUR, notiTemplate.getExpireDuration());
}
else {
cal.add(Calendar.MINUTE, notiTemplate.getExpireDuration());
}
Date expired = cal.getTime();
if (notificationType.startsWith(KeyPayTerm.APLC)) {
if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA
|| dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) {
try {
Applicant applicant = ApplicantLocalServiceUtil.fetchByAppId(dossier.getApplicantIdNo());
long toUserId = (applicant != null ? applicant.getMappingUserId() : 0l);
String contactEmail = (isEmailNotify(dossier)) ? dossier.getContactEmail() : StringPool.BLANK;
String telNo = (isSmsNotify(dossier)) ? dossier.getContactTelNo() : StringPool.BLANK;
String fromFullName = u.getFullName();
if (Validator.isNotNull(OpenCPSConfigUtil.getMailToApplicantFrom())) {
fromFullName = OpenCPSConfigUtil.getMailToApplicantFrom();
}
JSONObject filesAttach = getFileAttachMailForApplicant(dossier, proAction);
payloadObj.put("filesAttach", filesAttach);
NotificationQueueLocalServiceUtil.addNotificationQueue(
userId, groupId,
notificationType,
Dossier.class.getName(),
String.valueOf(dossier.getDossierId()),
payloadObj.toJSONString(),
fromFullName,
dossier.getApplicantName(),
toUserId,
isSendNotiEmail ? contactEmail : StringPool.BLANK,
isSendNotiSMS ? telNo : StringPool.BLANK,
now,
expired,
context);
} catch (NoSuchUserException e) {
_log.error(e);
}
}
}
else if (notificationType.startsWith(KeyPayTerm.USER)) {
}
}
}
}
/**
* @param pattern
* @param lenght
* @return
*/
private String _generatorUniqueString(int lenght) {
char[] chars = KeyPayTerm.ZERO_TO_NINE.toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < lenght; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
return sb.toString();
}
private void assignDossierActionUser(Dossier dossier, int allowAssignUser, DossierAction dossierAction, long userId, long groupId, long assignUserId, JSONArray assignedUsers)
throws PortalException {
int moderator = 1;
List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId());
HashMap<Long, DossierUser> mapDus = new HashMap<>();
for (DossierUser du : lstDus) {
mapDus.put(du.getUserId(), du);
}
List<org.opencps.dossiermgt.model.DossierActionUser> lstDaus = dossierActionUserLocalService.getByDossierId(dossier.getDossierId());
HashMap<Long, Map<Long, org.opencps.dossiermgt.model.DossierActionUser>> mapDaus = new HashMap<>();
for (org.opencps.dossiermgt.model.DossierActionUser dau : lstDaus) {
if (mapDaus.get(dau.getDossierActionId()) != null) {
Map<Long, org.opencps.dossiermgt.model.DossierActionUser> temp = mapDaus.get(dau.getDossierActionId());
temp.put(dau.getUserId(), dau);
}
else {
Map<Long, org.opencps.dossiermgt.model.DossierActionUser> temp = new HashMap<>();
temp.put(dau.getUserId(), dau);
mapDaus.put(dau.getDossierActionId(), temp);
}
}
for (int n = 0; n < assignedUsers.length(); n++) {
JSONObject subUser = assignedUsers.getJSONObject(n);
if (subUser != null && subUser.has(DossierActionUserTerm.ASSIGNED)
&& subUser.getInt(DossierActionUserTerm.ASSIGNED) == DossierActionUserTerm.ASSIGNED_TH) {
DossierActionUserPK pk = new DossierActionUserPK();
long userIdAssigned = subUser.getLong(Field.USER_ID);
int assigned = subUser.has(DossierActionUserTerm.ASSIGNED) ? subUser.getInt(DossierActionUserTerm.ASSIGNED) : 0;
pk.setDossierActionId(dossierAction.getDossierActionId());
pk.setUserId(subUser.getLong(Field.USER_ID));
DossierUser dossierUser = null;
dossierUser = mapDus.get(subUser.getLong(Field.USER_ID));
if (dossierUser != null) {
//Update dossier user if assigned
if (allowAssignUser != ProcessActionTerm.NOT_ASSIGNED) {
dossierUser.setModerator(1);
dossierUserLocalService.updateDossierUser(dossierUser.getDossierId(), dossierUser.getUserId(),
dossierUser.getModerator(), dossierUser.getVisited());
// model.setModerator(dossierUser.getModerator());
moderator = dossierUser.getModerator();
}
}
else {
if (allowAssignUser != ProcessActionTerm.NOT_ASSIGNED) {
dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userIdAssigned, 1, true);
}
}
// org.opencps.dossiermgt.model.DossierActionUser dau = DossierActionUserLocalServiceUtil.fetchDossierActionUser(pk);
org.opencps.dossiermgt.model.DossierActionUser dau = null;
// dau = mapDaus.get(userIdAssigned);
if (mapDaus.get(dossierAction.getDossierActionId()) != null) {
dau = mapDaus.get(dossierAction.getDossierActionId()).get(userIdAssigned);
}
if (dau == null) {
// DossierAction dAction = DossierActionLocalServiceUtil.fetchDossierAction(dossierAction.getDossierActionId());
DossierAction dAction = dossierAction;
if (dAction != null) {
addDossierActionUserByAssigned(groupId, allowAssignUser, userIdAssigned, dossierAction.getDossierActionId(), moderator, false,
dAction.getStepCode(), dossier.getDossierId(), assigned, 0);
}
// else {
// addDossierActionUserByAssigned(allowAssignUser, userIdAssigned, dossierAction.getDossierActionId(), moderator, false,
// StringPool.BLANK, dossier.getDossierId(), assigned);
// }
}
else {
dau.setModerator(1);
dau.setAssigned(assigned);
dossierActionUserLocalService.updateDossierActionUser(dau);
}
}
else if (subUser != null && subUser.has(DossierActionUserTerm.ASSIGNED)
&& subUser.getInt(DossierActionUserTerm.ASSIGNED) == DossierActionUserTerm.NOT_ASSIGNED) {
// model = new org.opencps.dossiermgt.model.impl.DossierActionUserImpl();
DossierActionUserPK pk = new DossierActionUserPK();
pk.setDossierActionId(dossierAction.getDossierActionId());
pk.setUserId(subUser.getLong(Field.USER_ID));
org.opencps.dossiermgt.model.DossierActionUser dau = dossierActionUserLocalService.fetchDossierActionUser(pk);
if (Validator.isNull(dau)) {
}
else {
dau.setModerator(0);
dossierActionUserLocalService.updateDossierActionUser(dau);
}
}
}
}
private void addDossierActionUserByAssigned(long groupId, int allowAssignUser, long userId, long dossierActionId,
int moderator, boolean visited, String stepCode, long dossierId, int assigned, int delegacy) {
org.opencps.dossiermgt.model.DossierActionUser model = new org.opencps.dossiermgt.model.impl.DossierActionUserImpl();
// int assigned = DossierActionUserTerm.NOT_ASSIGNED;
model.setVisited(visited);
model.setDossierId(dossierId);
model.setStepCode(stepCode);
model.setAssigned(assigned);
model.setDelegacy(delegacy);
//Check employee is exits and wokingStatus
Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId);
_log.debug("Employee : " + employee);
_log.debug("ADD DOSSIER ACTION USER ASSIGNED : " + stepCode);
if (employee != null && employee.getWorkingStatus() == 1) {
DossierActionUserPK pk = new DossierActionUserPK(dossierActionId, userId);
org.opencps.dossiermgt.model.DossierActionUser dau = dossierActionUserLocalService.fetchDossierActionUser(pk);
model.setUserId(userId);
model.setDossierActionId(dossierActionId);
model.setModerator(moderator);
// if (allowAssignUser == ProcessActionTerm.NOT_ASSIGNED) {
// model.setUserId(userId);
// model.setDossierActionId(dossierActionId);
// model.setModerator(moderator);
// if (moderator == 1) {
// model.setAssigned(1);
// } else {
// model.setAssigned(assigned);
// }
// if (dau == null) {
// dossierActionUserLocalService.addDossierActionUser(model);
// }
// else {
// if (dau.getModerator() != DossierActionUserTerm.ASSIGNED_TH
// && model.getModerator() == DossierActionUserTerm.ASSIGNED_TH) {
// dossierActionUserLocalService.updateDossierActionUser(model);
// }
// }
// }
// else if (allowAssignUser == ProcessActionTerm.ASSIGNED_TH) {
// _log.debug("Assign dau: " + userId);
// model.setUserId(userId);
// model.setDossierActionId(dossierActionId);
// model.setModerator(moderator);
// assigned = DossierActionUserTerm.ASSIGNED_TH;
// model.setAssigned(assigned);
// if (dau == null) {
// _log.debug("Assign add dau: " + userId);
// dossierActionUserLocalService.addDossierActionUser(model);
// }
// else {
// if (dau.getModerator() != DossierActionUserTerm.ASSIGNED_TH
// && model.getModerator() == DossierActionUserTerm.ASSIGNED_TH) {
// _log.debug("Assign update dau: " + userId);
// dossierActionUserLocalService.updateDossierActionUser(model);
// }
// }
// }
// else if (allowAssignUser == ProcessActionTerm.ASSIGNED_TH_PH) {
// model.setUserId(userId);
// model.setDossierActionId(dossierActionId);
// model.setModerator(moderator);
// assigned = DossierActionUserTerm.ASSIGNED_TH;
// model.setAssigned(assigned);
// dossierActionUserLocalService.addDossierActionUser(model);
//
// model.setUserId(userId);
// model.setDossierActionId(dossierActionId);
// model.setModerator(moderator);
// model.setVisited(true);
// assigned = DossierActionUserTerm.ASSIGNED_PH;
// model.setAssigned(assigned);
// if (dau == null) {
// dossierActionUserLocalService.addDossierActionUser(model);
// }
// else {
// if (dau.getModerator() != DossierActionUserTerm.ASSIGNED_TH
// && model.getModerator() == DossierActionUserTerm.ASSIGNED_TH) {
// dossierActionUserLocalService.updateDossierActionUser(model);
// }
// }
// }
// else if (allowAssignUser == ProcessActionTerm.ASSIGNED_TH_PH_TD) {
// model.setUserId(userId);
// model.setDossierActionId(dossierActionId);
// model.setModerator(moderator);
// assigned = DossierActionUserTerm.ASSIGNED_TH;
// model.setAssigned(assigned);
// dossierActionUserLocalService.addDossierActionUser(model);
//
// model.setUserId(userId);
// model.setDossierActionId(dossierActionId);
// model.setModerator(moderator);
// assigned = DossierActionUserTerm.ASSIGNED_PH;
// model.setAssigned(assigned);
// dossierActionUserLocalService.addDossierActionUser(model);
//
// model.setUserId(userId);
// model.setDossierActionId(dossierActionId);
// model.setModerator(moderator);
// assigned = DossierActionUserTerm.ASSIGNED_TD;
// model.setAssigned(assigned);
// if (dau == null) {
// dossierActionUserLocalService.addDossierActionUser(model);
// }
// else {
// if (dau.getModerator() != DossierActionUserTerm.ASSIGNED_TH
// && model.getModerator() == DossierActionUserTerm.ASSIGNED_TH) {
// dossierActionUserLocalService.updateDossierActionUser(model);
// }
// }
// }
_log.debug("DOSSIER ACTION ASSIGNED USER: " + dau);
if (dau == null) {
dossierActionUserLocalService.addDossierActionUser(model);
}
else {
dossierActionUserLocalService.updateDossierActionUser(model);
}
}
}
public void initDossierActionUser(ProcessAction processAction, Dossier dossier, int allowAssignUser, DossierAction dossierAction, long userId, long groupId, long assignUserId)
throws PortalException {
// Delete record in dossierActionUser
List<org.opencps.dossiermgt.model.DossierActionUser> dossierActionUser = dossierActionUserLocalService
.getListUser(dossierAction.getDossierActionId());
if (dossierActionUser != null && dossierActionUser.size() > 0) {
dossierActionUserLocalService.deleteByDossierAction(dossierAction.getDossierActionId());
}
long serviceProcessId = dossierAction.getServiceProcessId();
String stepCode = processAction.getPostStepCode();
// Get ProcessStep
ProcessStep processStep = processStepLocalService.fetchBySC_GID(stepCode, groupId, serviceProcessId);
long processStepId = processStep.getProcessStepId();
int assigned;
// Get List ProcessStepRole
List<ProcessStepRole> listProcessStepRole = processStepRoleLocalService.findByP_S_ID(processStepId);
ProcessStepRole processStepRole = null;
List<DossierAction> lstStepActions = dossierActionLocalService.getByDID_FSC_NOT_DAI(dossier.getDossierId(), stepCode, dossierAction.getDossierActionId());
if (listProcessStepRole.size() != 0) {
for (int i = 0; i < listProcessStepRole.size(); i++) {
processStepRole = listProcessStepRole.get(i);
long roleId = processStepRole.getRoleId();
boolean moderator = processStepRole.getModerator();
int mod = 0;
if (moderator) {
mod = 1;
}
// Get list user
List<User> users = UserLocalServiceUtil.getRoleUsers(roleId);
for (User user : users) {
Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(dossier.getGroupId(), user.getUserId());
//_log.debug("Employee : " + employee);
if (employee != null && employee.getWorkingStatus() == 1
&& (Validator.isNull(employee.getScope()) || (Validator.isNotNull(employee.getScope()) && dossier.getGovAgencyCode().contentEquals(employee.getScope())))) {
List<DossierAction> lstDoneActions = dossierActionLocalService
.getByDID_U_FSC(dossier.getDossierId(), user.getUserId(), stepCode);
if (!lstStepActions.isEmpty()) {
if (!lstDoneActions.isEmpty())
mod = 1;
else
mod = 0;
}
if (moderator) {
assigned = DossierActionUserTerm.ASSIGNED_TH;
}
else {
assigned = DossierActionUserTerm.NOT_ASSIGNED;
}
updateDossierUser(dossier, processStepRole, user);
List<DossierActionUser> lstDau = dossierActionUserLocalService.getByDossierUserAndStepCode(dossier.getDossierId(), user.getUserId(), stepCode);
DossierActionUser lastDau = (lstDau.size() > 0 ? lstDau.get(0) : null);
for (DossierActionUser dau : lstDau) {
if (dau.getDossierActionId() > lastDau.getDossierActionId()) {
lastDau = dau;
}
}
if (lastDau != null) {
addDossierActionUserByAssigned(groupId, processAction.getAllowAssignUser(), user.getUserId(),
dossierAction.getDossierActionId(), lastDau.getModerator(), false, stepCode, dossier.getDossierId(), lastDau.getAssigned(), lastDau.getDelegacy());
}
else {
addDossierActionUserByAssigned(groupId, processAction.getAllowAssignUser(), user.getUserId(),
dossierAction.getDossierActionId(), mod, false, stepCode, dossier.getDossierId(), assigned, 0);
}
}
}
}
}
else {
//Get role from service process
initDossierActionUserByServiceProcessRole(dossier, allowAssignUser, dossierAction, userId, groupId, assignUserId);
}
}
private void updateDossierUser(Dossier dossier, ProcessStepRole processStepRole, User user) {
DossierUserPK pk = new DossierUserPK();
pk.setDossierId(dossier.getDossierId());
pk.setUserId(user.getUserId());
DossierUser du = dossierUserLocalService.fetchDossierUser(pk);
if (du == null) {
dossierUserLocalService.addDossierUser(dossier.getGroupId(), dossier.getDossierId(), user.getUserId(), processStepRole.getModerator() ? 1 : 0, true);
}
else {
try {
if ((processStepRole.getModerator() && du.getModerator() != DossierActionUserTerm.ASSIGNED_PH)
|| (!processStepRole.getModerator() && du.getModerator() != DossierActionUserTerm.ASSIGNED_PH)) {
dossierUserLocalService.updateDossierUser(dossier.getDossierId(), user.getUserId(), du.getModerator() == 0 ? (processStepRole.getModerator() ? 1 : 0) : 1, true);
}
} catch (NoSuchDossierUserException e) {
_log.error(e);
}
}
}
private boolean checkGovDossierEmployee(Dossier dossier, Employee e) {
if (e != null && (Validator.isNull(e.getScope()) || (dossier.getGovAgencyCode().contentEquals(e.getScope())))) {
return true;
}
return false;
}
private void initDossierActionUserByServiceProcessRole(Dossier dossier, int allowAssignUser, DossierAction dossierAction, long userId, long groupId, long assignUserId) {
try {
Map<Long, Employee> mapEmps = new HashMap<Long, Employee>();
List<Employee> lstEmps = EmployeeLocalServiceUtil.findByG(dossier.getGroupId());
for (Employee e : lstEmps) {
mapEmps.put(e.getMappingUserId(), e);
}
ServiceProcess serviceProcess = serviceProcessLocalService.getServiceByCode(groupId, dossier.getServiceCode(), dossier.getGovAgencyCode(), dossier.getDossierTemplateNo());
List<ServiceProcessRole> listSprs = serviceProcessRoleLocalService.findByS_P_ID(serviceProcess.getServiceProcessId());
DossierAction da = dossierAction;
for (ServiceProcessRole spr : listSprs) {
int mod = 0;
boolean moderator = spr.getModerator();
if (moderator) {
mod = 1;
}
List<User> users = UserLocalServiceUtil.getRoleUsers(spr.getRoleId());
for (User user : users) {
if (mapEmps.containsKey(user.getUserId())) {
Employee e = mapEmps.get(user.getUserId());
if (checkGovDossierEmployee(dossier, e)) {
int assigned = user.getUserId() == assignUserId ? DossierActionUserTerm.ASSIGNED_TH : (moderator ? DossierActionUserTerm.ASSIGNED_TH : DossierActionUserTerm.NOT_ASSIGNED);
org.opencps.dossiermgt.model.DossierActionUser dau = dossierActionUserLocalService.getByDossierAndUser(dossierAction.getDossierActionId(), user.getUserId());
if (dau != null) {
dau.setModerator(mod);
dau.setAssigned(assigned);
dossierActionUserLocalService.updateDossierActionUser(dau);
} else {
addDossierActionUserByAssigned(groupId, allowAssignUser, user.getUserId(), dossierAction.getDossierActionId(), mod, false, da.getStepCode(), dossier.getDossierId(), assigned, 0);
}
}
}
}
}
} catch (PortalException e) {
_log.error(e);
}
}
private void copyRoleAsStep(ProcessStep curStep, Dossier dossier) {
if (Validator.isNull(curStep.getRoleAsStep()))
return;
String[] stepCodeArr = StringUtil.split(curStep.getRoleAsStep());
Map<Long, Employee> mapEmps = new HashMap<Long, Employee>();
List<Employee> lstEmps = EmployeeLocalServiceUtil.findByG(dossier.getGroupId());
for (Employee e : lstEmps) {
mapEmps.put(e.getMappingUserId(), e);
}
if (stepCodeArr.length > 0) {
for (String stepCode : stepCodeArr) {
if (stepCode.startsWith(StringPool.EXCLAMATION)) {
int index = stepCode.indexOf(StringPool.EXCLAMATION);
String stepCodePunc = stepCode.substring(index + 1);
List<org.opencps.dossiermgt.model.DossierActionUser> lstDaus = dossierActionUserLocalService.getByDossierAndStepCode(dossier.getDossierId(), stepCodePunc);
List<DossierAction> lstDossierActions = dossierActionLocalService.findDossierActionByDID_STEP(dossier.getDossierId(), stepCodePunc);
try {
for (org.opencps.dossiermgt.model.DossierActionUser dau : lstDaus) {
boolean flagDA = false;
for (DossierAction da : lstDossierActions) {
if (da.getUserId() == dau.getUserId()) {
flagDA = true;
break;
}
}
if (flagDA) {
DossierUserPK duPk = new DossierUserPK();
duPk.setDossierId(dossier.getDossierId());
duPk.setUserId(dau.getUserId());
int moderator = dau.getModerator();
DossierUser duModel = dossierUserLocalService.fetchDossierUser(duPk);
if (duModel == null) {
dossierUserLocalService.addDossierUser(dossier.getGroupId(), dossier.getDossierId(),
dau.getUserId(), moderator, true);
}
else {
try {
if (duModel.getModerator() == 0 && moderator == 1) {
dossierUserLocalService.updateDossierUser(dossier.getDossierId(), dau.getUserId(),
moderator, true);
}
} catch (NoSuchDossierUserException e) {
// e.printStackTrace();
_log.error(e);
}
}
DossierActionUserPK dauPk = new DossierActionUserPK();
dauPk.setDossierActionId(dossier.getDossierActionId());
dauPk.setUserId(dau.getUserId());
int assigned = moderator == 1 ? 1 : 0;
dossierActionUserLocalService.addOrUpdateDossierActionUser(dau.getUserId(), dossier.getGroupId(), dossier.getDossierActionId(), dossier.getDossierId(), curStep.getStepCode(), moderator, assigned, true);
}
}
}
catch (Exception e) {
_log.error(e);
}
}
else {
ServiceProcess serviceProcess = null;
try {
serviceProcess = serviceProcessLocalService.getServiceByCode(dossier.getGroupId(), dossier.getServiceCode(), dossier.getGovAgencyCode(), dossier.getDossierTemplateNo());
if (serviceProcess != null) {
ProcessStep processStep = processStepLocalService.fetchBySC_GID(stepCode, dossier.getGroupId(), serviceProcess.getServiceProcessId());
if (processStep == null) continue;
List<ProcessStepRole> lstRoles = processStepRoleLocalService.findByP_S_ID(processStep.getProcessStepId());
for (ProcessStepRole psr : lstRoles) {
List<User> users = UserLocalServiceUtil.getRoleUsers(psr.getRoleId());
for (User u : users) {
if (mapEmps.containsKey(u.getUserId())) {
Employee emp = mapEmps.get(u.getUserId());
if (checkGovDossierEmployee(dossier, emp)) {
DossierUserPK duPk = new DossierUserPK();
duPk.setDossierId(dossier.getDossierId());
duPk.setUserId(u.getUserId());
int moderator = (psr.getModerator() ? 1 : 0);
DossierUser duModel = dossierUserLocalService.fetchDossierUser(duPk);
if (duModel == null) {
dossierUserLocalService.addDossierUser(dossier.getGroupId(), dossier.getDossierId(),
u.getUserId(), moderator, true);
}
else {
try {
if (duModel.getModerator() == 0 && moderator == 1) {
dossierUserLocalService.updateDossierUser(dossier.getDossierId(), u.getUserId(),
moderator, true);
}
} catch (NoSuchDossierUserException e) {
_log.error(e);
}
}
DossierActionUserPK dauPk = new DossierActionUserPK();
dauPk.setDossierActionId(dossier.getDossierActionId());
dauPk.setUserId(u.getUserId());
int assigned = moderator == 1 ? 1 : 0;
dossierActionUserLocalService.addOrUpdateDossierActionUser(u.getUserId(), dossier.getGroupId(), dossier.getDossierActionId(), dossier.getDossierId(), curStep.getStepCode(), moderator, assigned, true);
}
}
}
}
}
} catch (PortalException e) {
_log.error(e);
}
}
}
}
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public Dossier addDossier(long groupId, Company company, User user, ServiceContext serviceContext,
DossierInputModel input) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
DossierPermission dossierPermission = new DossierPermission();
long start = System.currentTimeMillis();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
ProcessOption option = getProcessOption(input.getServiceCode(), input.getGovAgencyCode(),
input.getDossierTemplateNo(), groupId);
long serviceProcessId = 0;
if (option != null) {
serviceProcessId = option.getServiceProcessId();
}
boolean flag = false;
long userId = serviceContext.getUserId();
Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId);
if (employee != null) {
long employeeId = employee.getEmployeeId();
if (employeeId > 0) {
List<EmployeeJobPos> empJobList = EmployeeJobPosLocalServiceUtil.findByF_EmployeeId(employeeId);
if (empJobList != null && empJobList.size() > 0) {
for (EmployeeJobPos employeeJobPos : empJobList) {
long jobPosId = employeeJobPos.getJobPostId();
if (jobPosId > 0) {
JobPos job = JobPosLocalServiceUtil.fetchJobPos(jobPosId);
if (job != null) {
ServiceProcessRolePK pk = new ServiceProcessRolePK(serviceProcessId,
job.getMappingRoleId());
ServiceProcessRole role = serviceProcessRoleLocalService
.fetchServiceProcessRole(pk);
if (role != null && role.getModerator()) {
flag = true;
break;
}
}
}
}
}
}
} else {
flag = true;
}
if (!flag) {
throw new UnauthenticationException("No permission create dossier");
}
_log.debug("CREATE DOSSIER 1: " + (System.currentTimeMillis() - start) + " ms");
_log.debug("CREATE DOSSIER 1.X: " + input.getServiceCode() + ", " + input.getGovAgencyCode() + ", " + input.getDossierTemplateNo());
dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(),
input.getGovAgencyCode(), input.getDossierTemplateNo());
//int counter = DossierNumberGenerator.counterDossier(user.getUserId(), groupId);
String referenceUid = input.getReferenceUid();
int counter = 0;
// Create dossierNote
ServiceProcess process = null;
boolean online = GetterUtil.getBoolean(input.getOnline());
int originality = GetterUtil.getInteger(input.getOriginality());
Integer viaPostal = input.getViaPostal();
ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, input.getServiceCode(),
input.getGovAgencyCode());
if (config != null && Validator.isNotNull(viaPostal)) {
viaPostal = config.getPostService() ? (viaPostal == 0 ? 1 : viaPostal) : 0;
}
else if (config != null) {
viaPostal = config.getPostService() ? 1 : 0;
}
if (option != null) {
process = serviceProcessLocalService.getServiceProcess(serviceProcessId);
}
if (process == null) {
throw new NotFoundException("Cant find process");
}
if (Validator.isNull(referenceUid) || referenceUid.trim().length() == 0)
referenceUid = DossierNumberGenerator.generateReferenceUID(groupId);
//Dossier checkDossier = dossierLocalService.getByRef(groupId, referenceUid);
//if (checkDossier != null) {
// return checkDossier;
//}
ServiceInfo service = serviceInfoLocalService.getByCode(groupId, input.getServiceCode());
String serviceName = StringPool.BLANK;
if (service != null) {
serviceName = service.getServiceName();
}
String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, input.getGovAgencyCode());
DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(ADMINISTRATIVE_REGION, groupId);
String cityName = getDictItemName(groupId, dc, input.getCityCode());
String districtName = getDictItemName(groupId, dc, input.getDistrictCode());
String wardName = getDictItemName(groupId, dc, input.getWardCode());
// _log.info("Service code: " + input.getServiceCode());
_log.debug("===ADD DOSSIER CITY NAME:" + cityName);
String password = StringPool.BLANK;
if (Validator.isNotNull(input.getPassword())) {
password = input.getPassword();
} else if (Validator.isNotNull(process.getGeneratePassword()) && process.getGeneratePassword()) {
_log.debug("DOSSIER SECRET LENGTH: " + OpenCPSConfigUtil.getDefaultDossierSecretLength());
if (OpenCPSConfigUtil.getDefaultDossierSecretLength() > DossierTerm.PIN_LENGTH) {
password = PwdGenerator.getPassword(OpenCPSConfigUtil.getDefaultDossierSecretLength(), PwdGenerator.KEY1);
}
else {
password = PwdGenerator.getPinNumber();
}
}
String postalCityName = StringPool.BLANK;
if (Validator.isNotNull(input.getPostalCityCode())) {
postalCityName = getDictItemName(groupId, VNPOST_CITY_CODE, input.getPostalCityCode());
}
Long sampleCount = (option != null ? option.getSampleCount() : 1l);
String registerBookCode = (option != null ? (Validator.isNotNull(option.getRegisterBookCode()) ? option.getRegisterBookCode() : StringPool.BLANK) : StringPool.BLANK);
//String registerBookName = (Validator.isNotNull(registerBookCode) ? getDictItemName(groupId, REGISTER_BOOK, registerBookCode) : StringPool.BLANK);
String registerBookName = StringPool.BLANK;
if (Validator.isNotNull(registerBookCode)) {
DynamicReport report = DynamicReportLocalServiceUtil.fetchByG_CODE(groupId, registerBookCode);
if (report != null) {
registerBookName = report.getReportName();
}
}
// Process group dossier
if (originality == 9) {
_log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date appIdDate = null;
try {
appIdDate = sdf.parse(input.getApplicantIdDate());
} catch (Exception e) {
_log.debug(e);
}
Dossier dossier = dossierLocalService.initDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName,
input.getGovAgencyCode(), govAgencyName, input.getApplicantName(), input.getApplicantIdType(),
input.getApplicantIdNo(), appIdDate, input.getAddress(), input.getCityCode(),
cityName, input.getDistrictCode(), districtName, input.getWardCode(), wardName,
input.getContactName(), input.getContactTelNo(), input.getContactEmail(),
input.getDossierTemplateNo(), password, viaPostal, input.getPostalAddress(), input.getPostalCityCode(), postalCityName,
input.getPostalTelNo(), online, process.getDirectNotification(), input.getApplicantNote(),
Integer.valueOf(input.getOriginality()),
service, process, option,
serviceContext);
if (Validator.isNotNull(input.getDossierName())) {
dossier.setDossierName(input.getDossierName());
} else {
dossier.setDossierName(serviceName);
}
dossier.setSampleCount(sampleCount);
dossier.setSystemId(input.getSystemId());
//Delegate dossier
dossier.setDelegateType(input.getDelegateType() != null ? input.getDelegateType() : 0);
if (Validator.isNotNull(input.getDocumentNo())) {
dossier.setDocumentNo(input.getDocumentNo());
}
if (input.getDocumentDate() != null && 0 != input.getDocumentDate()) {
dossier.setDocumentDate(new Date(input.getDocumentDate()));
}
if (Validator.isNotNull(input.getMetaData()))
dossier.setMetaData(input.getMetaData());
updateDelegateApplicant(dossier, input);
// Process update dossierNo
// LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();
// params.put(DossierTerm.GOV_AGENCY_CODE, dossier.getGovAgencyCode());
// params.put(DossierTerm.SERVICE_CODE, dossier.getServiceCode());
// params.put(DossierTerm.DOSSIER_TEMPLATE_NO, dossier.getDossierTemplateNo());
// params.put(DossierTerm.DOSSIER_STATUS, StringPool.BLANK);
if (option != null) {
//Process submition note
dossier.setSubmissionNote(option.getSubmissionNote());
// String dossierRef = DossierNumberGenerator.generateDossierNumber(groupId, dossier.getCompanyId(),
// dossier.getDossierId(), option.getProcessOptionId(), process.getDossierGroupPattern(), params);
// dossier.setDossierNo(dossierRef.trim());
}
dossier.setViaPostal(1);
_log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms");
if (Validator.isNull(dossier)) {
throw new NotFoundException("Can't add DOSSIER");
}
_log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms");
//Create DossierMark
_log.debug("originality: "+originality);
String templateNo = dossier.getDossierTemplateNo();
_log.debug("templateNo: "+templateNo);
if (Validator.isNotNull(input.getDossierMarkArr())) {
JSONArray markArr = JSONFactoryUtil.createJSONArray(input.getDossierMarkArr());
if (markArr != null && markArr.length() > 0) {
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId());
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
for (int i = 0; i < markArr.length(); i++) {
JSONObject jsonMark = markArr.getJSONObject(i);
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[markArr.length()];
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(jsonMark.getString("partNo"));
model.setFileCheck(0);
model.setFileMark(jsonMark.getInt("fileMark"));
model.setFileComment(StringPool.BLANK);
model.setRecordCount(StringPool.BLANK);
marks[i] = model;
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
}
}
} else if (Validator.isNotNull(templateNo)) {
List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo);
// _log.info("partList: "+partList);
if (partList != null && partList.size() > 0) {
_log.debug("partList.size(): "+partList.size());
_log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms");
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()];
int count = 0;
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId());
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
for (DossierPart dossierPart : partList) {
int fileMark = dossierPart.getFileMark();
String dossierPartNo = dossierPart.getPartNo();
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(dossierPartNo);
model.setFileCheck(0);
model.setFileMark(fileMark);
model.setFileComment(StringPool.BLANK);
model.setRecordCount(StringPool.BLANK);
marks[count++] = model;
}
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
_log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms");
}
}
//Create dossier user
List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId());
List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId());
if (lstDus.size() == 0) {
DossierUserActions duActions = new DossierUserActionsImpl();
duActions.initDossierUser(groupId, dossier, process, lstProcessRoles);
}
// if (originality == DossierTerm.ORIGINALITY_DVCTT) {
// dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true);
// }
_log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms");
//Add to dossier user based on service process role
createDossierUsers(groupId, dossier, process, lstProcessRoles);
if (Validator.isNotNull(input.getVnpostalStatus())) {
dossier.setVnpostalStatus(input.getVnpostalStatus());
}
if (Validator.isNotNull(input.getVnpostalProfile())) {
dossier.setVnpostalProfile(input.getVnpostalProfile());
}
if (Validator.isNotNull(input.getServerNo())) {
dossier.setServerNo(input.getServerNo());
}
_log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms");
return dossierLocalService.updateDossier(dossier);
} else {
List<Dossier> oldDossiers = dossierLocalService.getByU_G_GAC_SC_DTNO_DS_O(
userId, groupId, input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo(), StringPool.BLANK, Integer.valueOf(input.getOriginality()));
Dossier dossier = null;
Dossier oldRefDossier = Validator.isNotNull(input.getReferenceUid()) ? dossierLocalService.getByRef(groupId, input.getReferenceUid()) : null;
if (originality == DossierTerm.ORIGINALITY_DVCTT) {
online = true;
}
boolean flagOldDossier = false;
_log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms");
if (oldRefDossier != null) {
//Check old cross dossier rollback
if (oldRefDossier.getOriginality() < 0 && Validator.isNotNull(input.getOriginDossierNo())) {
oldRefDossier.setOriginality(-oldRefDossier.getOriginality());
}
dossier = oldRefDossier;
dossier.setSubmitDate(new Date());
dossier.setReceiveDate(new Date());
ServiceProcess serviceProcess = process;
double durationCount = 0;
int durationUnit = 0;
if (serviceProcess != null ) {
durationCount = serviceProcess.getDurationCount();
durationUnit = serviceProcess.getDurationUnit();
dossier.setDurationCount(durationCount);
dossier.setDurationUnit(durationUnit);
}
if (durationCount > 0) {
// Date dueDate = HolidayUtils.getDueDate(new Date(), durationCount, durationUnit, groupId);
DueDateUtils dueDateUtils = new DueDateUtils(new Date(), durationCount, durationUnit, groupId);
Date dueDate = dueDateUtils.getDueDate();
dossier.setDueDate(dueDate);
}
//Delegate
//Delegate dossier
dossier.setDelegateType(input.getDelegateType() != null ? input.getDelegateType() : 0);
if (Validator.isNotNull(input.getDocumentNo())) {
dossier.setDocumentNo(input.getDocumentNo());
}
if (input.getDocumentDate() != null && 0 != input.getDocumentDate()) {
dossier.setDocumentDate(new Date(input.getDocumentDate()));
}
}
else if (oldDossiers.size() > 0) {
flagOldDossier = true;
dossier = oldDossiers.get(0);
dossier.setApplicantName(input.getApplicantName());
dossier.setApplicantNote(input.getApplicantNote());
dossier.setApplicantIdNo(input.getApplicantIdNo());
dossier.setAddress(input.getAddress());
dossier.setContactEmail(input.getContactEmail());
dossier.setContactName(input.getContactName());
dossier.setContactTelNo(input.getContactTelNo());
dossier.setDelegateName(input.getDelegateName());
dossier.setDelegateEmail(input.getDelegateEmail());
dossier.setDelegateAddress(input.getDelegateAddress());
dossier.setPostalAddress(input.getPostalAddress());
dossier.setPostalCityCode(input.getPostalCityCode());
dossier.setPostalCityName(postalCityName);
dossier.setPostalTelNo(input.getPostalTelNo());
dossier.setPostalServiceCode(input.getPostalServiceCode());
dossier.setPostalServiceName(input.getPostalServiceName());
dossier.setPostalDistrictCode(input.getPostalDistrictCode());
dossier.setPostalDistrictName(input.getPostalDistrictName());
dossier.setPostalWardCode(input.getPostalWardCode());
dossier.setPostalWardName(input.getPostalWardName());
dossier.setPostalTelNo(input.getPostalTelNo());
dossier.setViaPostal(viaPostal);
dossier.setOriginDossierNo(input.getOriginDossierNo());
if (Validator.isNotNull(registerBookCode)) {
dossier.setRegisterBookCode(registerBookCode);
}
dossier.setRegisterBookName(registerBookName);
dossier.setSampleCount(sampleCount);
dossier.setServiceCode(input.getServiceCode());
dossier.setGovAgencyCode(input.getGovAgencyCode());
dossier.setDossierTemplateNo(input.getDossierTemplateNo());
updateDelegateApplicant(dossier, input);
// dossier.setDossierNo(input.getDossierNo());
dossier.setSubmitDate(new Date());
// ServiceProcess serviceProcess = ServiceProcessLocalServiceUtil.fetchServiceProcess(serviceProcessId);
ServiceProcess serviceProcess = process;
double durationCount = 0;
int durationUnit = 0;
if (serviceProcess != null ) {
durationCount = serviceProcess.getDurationCount();
durationUnit = serviceProcess.getDurationUnit();
dossier.setDurationCount(durationCount);
dossier.setDurationUnit(durationUnit);
}
if (durationCount > 0) {
// Date dueDate = HolidayUtils.getDueDate(new Date(), durationCount, durationUnit, groupId);
DueDateUtils dueDateUtils = new DueDateUtils(new Date(), durationCount, durationUnit, groupId);
Date dueDate = dueDateUtils.getDueDate();
dossier.setDueDate(dueDate);
}
dossier.setOnline(online);
if (Validator.isNotNull(input.getDossierName()))
dossier.setDossierName(input.getDossierName());
if (serviceProcess != null) {
dossier.setProcessNo(serviceProcess.getProcessNo());
}
//Delegate dossier
dossier.setDelegateType(input.getDelegateType() != null ? input.getDelegateType() : 0);
if (Validator.isNotNull(input.getDocumentNo())) {
dossier.setDocumentNo(input.getDocumentNo());
}
if (input.getDocumentDate() != null && 0 != input.getDocumentDate()) {
dossier.setDocumentDate(new Date(input.getDocumentDate()));
}
// dossier = DossierLocalServiceUtil.updateDossier(dossier);
}
else {
SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
Date appIdDate = null;
try {
appIdDate = sdf.parse(input.getApplicantIdDate());
} catch (Exception e) {
_log.debug(e);
}
dossier = dossierLocalService.initDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName,
input.getGovAgencyCode(), govAgencyName, input.getApplicantName(), input.getApplicantIdType(),
input.getApplicantIdNo(), appIdDate, input.getAddress(), input.getCityCode(),
cityName, input.getDistrictCode(), districtName, input.getWardCode(), wardName,
input.getContactName(), input.getContactTelNo(), input.getContactEmail(),
input.getDossierTemplateNo(), password, viaPostal, input.getPostalAddress(), input.getPostalCityCode(), postalCityName,
input.getPostalTelNo(), online, process.getDirectNotification(), input.getApplicantNote(),
Integer.valueOf(input.getOriginality()),
service, process, option,
serviceContext);
dossier.setDelegateName(input.getDelegateName());
dossier.setDelegateEmail(input.getDelegateEmail());
dossier.setDelegateAddress(input.getDelegateAddress());
if (Validator.isNotNull(input.getDossierName())) {
dossier.setDossierName(input.getDossierName());
} else {
dossier.setDossierName(serviceName);
}
dossier.setPostalCityName(postalCityName);
dossier.setPostalTelNo(input.getPostalTelNo());
dossier.setPostalServiceCode(input.getPostalServiceCode());
dossier.setPostalServiceName(input.getPostalServiceName());
dossier.setPostalDistrictCode(input.getPostalDistrictCode());
dossier.setPostalDistrictName(input.getPostalDistrictName());
dossier.setPostalWardCode(input.getPostalWardCode());
dossier.setPostalWardName(input.getPostalWardName());
dossier.setOriginDossierNo(input.getOriginDossierNo());
//dossier.setRegisterBookCode(registerBookCode);
//dossier.setRegisterBookName(registerBookName);
dossier.setSampleCount(sampleCount);
dossier.setSystemId(input.getSystemId());
if (Validator.isNotNull(input.getMetaData()))
dossier.setMetaData(input.getMetaData());
//Delegate dossier
if (Validator.isNotNull(input.getDelegateType())) {
dossier.setDelegateType(input.getDelegateType());
}
if (Validator.isNotNull(input.getDocumentNo())) {
dossier.setDocumentNo(input.getDocumentNo());
}
if (input.getDocumentDate() != null && 0 != input.getDocumentDate()) {
dossier.setDocumentDate(new Date(input.getDocumentDate()));
}
updateDelegateApplicant(dossier, input);
//if (process != null) {
// dossier.setProcessNo(process.getProcessNo());
//}
// dossier = DossierLocalServiceUtil.updateDossier(dossier);
}
_log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms");
if (originality != DossierTerm.ORIGINALITY_LIENTHONG) {
Applicant applicant = ApplicantLocalServiceUtil.fetchByMappingID(serviceContext.getUserId());
if (applicant != null) {
updateApplicantInfo(dossier,
applicant.getApplicantIdDate(),
applicant.getApplicantIdNo(),
applicant.getApplicantIdType(),
applicant.getApplicantName(),
applicant.getAddress(),
applicant.getCityCode(),
applicant.getCityName(),
applicant.getDistrictCode(),
applicant.getDistrictName(),
applicant.getWardCode(),
applicant.getWardName(),
applicant.getContactEmail(),
applicant.getContactTelNo()
);
}
}
if (Validator.isNull(dossier)) {
throw new NotFoundException("Cant add DOSSIER");
}
_log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms");
//Create DossierMark
_log.debug("flagOldDossier: "+flagOldDossier);
_log.debug("originality: "+originality);
if ((originality == DossierTerm.ORIGINALITY_MOTCUA || originality == DossierTerm.ORIGINALITY_LIENTHONG)
&& !flagOldDossier) {
String templateNo = dossier.getDossierTemplateNo();
_log.debug("templateNo: "+templateNo);
if (Validator.isNotNull(templateNo)) {
List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo);
// _log.info("partList: "+partList);
if (partList != null && partList.size() > 0) {
_log.debug("partList.size(): "+partList.size());
_log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms");
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()];
int count = 0;
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId());
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
for (DossierPart dossierPart : partList) {
int fileMark = dossierPart.getFileMark();
String dossierPartNo = dossierPart.getPartNo();
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(dossierPartNo);
model.setFileCheck(0);
model.setFileMark(fileMark);
model.setFileComment(StringPool.BLANK);
marks[count++] = model;
// DossierMarkLocalServiceUtil.addDossierMark(groupId, dossier.getDossierId(), dossierPartNo,
// fileMark, 0, StringPool.BLANK, serviceContext);
}
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
_log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms");
}
}
}
//Create dossier user
List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId());
List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId());
if (lstDus.size() == 0) {
DossierUserActions duActions = new DossierUserActionsImpl();
// duActions.initDossierUser(groupId, dossier);
duActions.initDossierUser(groupId, dossier, process, lstProcessRoles);
}
if (originality == DossierTerm.ORIGINALITY_DVCTT) {
dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true);
}
_log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms");
// DossierLocalServiceUtil.updateDossier(dossier);
if (dossier != null) {
//
//Check if have DOSSIER-01 template
Notificationtemplate dossierTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, NotificationType.DOSSIER_01);
if (dossierTemplate != null) {
long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName());
NotificationQueue queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId);
//Process add notification queue
Date now = new Date();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1);
queue.setCreateDate(now);
queue.setModifiedDate(now);
queue.setGroupId(groupId);
queue.setCompanyId(company.getCompanyId());
queue.setNotificationType(NotificationType.DOSSIER_01);
queue.setClassName(Dossier.class.getName());
queue.setClassPK(String.valueOf(dossier.getPrimaryKey()));
queue.setToUsername(dossier.getUserName());
queue.setToUserId(dossier.getUserId());
if (isEmailNotify(dossier)) {
queue.setToEmail(dossier.getContactEmail());
}
if (isSmsNotify(dossier)) {
queue.setToTelNo(dossier.getContactTelNo());
}
JSONObject payload = JSONFactoryUtil.createJSONObject();
try {
// _log.info("START PAYLOAD: ");
payload.put(
KeyPayTerm.DOSSIER, JSONFactoryUtil.createJSONObject(
JSONFactoryUtil.looseSerialize(dossier)));
}
catch (JSONException parse) {
_log.error(parse);
}
// _log.info("payloadTest: "+payload.toJSONString());
queue.setPayload(payload.toJSONString());
queue.setExpireDate(cal.getTime());
NotificationQueueLocalServiceUtil.addNotificationQueue(queue);
}
}
_log.debug("CREATE DOSSIER 6: " + (System.currentTimeMillis() - start) + " ms");
//Add to dossier user based on service process role
createDossierUsers(groupId, dossier, process, lstProcessRoles);
if (Validator.isNotNull(input.getVnpostalStatus())) {
dossier.setVnpostalStatus(input.getVnpostalStatus());
}
if (Validator.isNotNull(input.getVnpostalProfile())) {
dossier.setVnpostalProfile(input.getVnpostalProfile());
}
if (Validator.isNotNull(input.getServerNo())) {
dossier.setServerNo(input.getServerNo());
}
_log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms");
dossierLocalService.updateDossier(dossier);
_log.debug("CREATE DOSSIER 8: " + (System.currentTimeMillis() - start) + " ms");
//Check verification applicant
Applicant checkApplicant = ApplicantLocalServiceUtil.fetchByMappingID(user.getUserId());
if (checkApplicant != null) {
int countDossier = DossierLocalServiceUtil.countByG_UID_DS(groupId, user.getUserId(), DossierTerm.DOSSIER_STATUS_RECEIVING);
_log.debug("APPLICANT NUMBER OF CREATE DOSSIER: " + countDossier);
if (countDossier >= DossierTerm.MAX_DOSSIER_WITHOUT_VERIFICATION) {
if (checkApplicant.getVerification() != ApplicantTerm.UNLOCKED) {
checkApplicant.setVerification(ApplicantTerm.LOCKED_DOSSIER);
ApplicantLocalServiceUtil.updateApplicant(checkApplicant);
}
}
}
return dossier;
}
}
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { SystemException.class, PortalException.class,
Exception.class })
public Dossier addMultipleDossier(long groupId, Company company, User user, ServiceContext serviceContext,
DossierMultipleInputModel input) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
DossierPermission dossierPermission = new DossierPermission();
long start = System.currentTimeMillis();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
ProcessOption option = getProcessOption(input.getServiceCode(), input.getGovAgencyCode(),
input.getDossierTemplateNo(), groupId);
long serviceProcessId = 0;
if (option != null) {
serviceProcessId = option.getServiceProcessId();
}
boolean flag = false;
long userId = serviceContext.getUserId();
Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId);
if (employee != null) {
long employeeId = employee.getEmployeeId();
if (employeeId > 0) {
List<EmployeeJobPos> empJobList = EmployeeJobPosLocalServiceUtil.findByF_EmployeeId(employeeId);
if (empJobList != null && empJobList.size() > 0) {
for (EmployeeJobPos employeeJobPos : empJobList) {
long jobPosId = employeeJobPos.getJobPostId();
if (jobPosId > 0) {
JobPos job = JobPosLocalServiceUtil.fetchJobPos(jobPosId);
if (job != null) {
ServiceProcessRolePK pk = new ServiceProcessRolePK(serviceProcessId,
job.getMappingRoleId());
ServiceProcessRole role = serviceProcessRoleLocalService
.fetchServiceProcessRole(pk);
if (role != null && role.getModerator()) {
flag = true;
break;
}
}
}
}
}
}
} else {
flag = true;
}
if (!flag) {
throw new UnauthenticationException("No permission create dossier");
}
_log.debug("CREATE DOSSIER 1: " + (System.currentTimeMillis() - start) + " ms");
dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(),
input.getGovAgencyCode(), input.getDossierTemplateNo());
Dossier dossier = null;
if (Validator.isNotNull(input.getDossiers())) {
JSONObject jsonDossier = JSONFactoryUtil.createJSONObject(input.getDossiers());
//Get params input dossier
String referenceUid = jsonDossier.getString(DossierTerm.REFERENCE_UID);
if (Validator.isNull(referenceUid) || referenceUid.trim().length() == 0)
referenceUid = DossierNumberGenerator.generateReferenceUID(groupId);
int counter = 0;
//boolean online = GetterUtil.getBoolean(input.getOnline());
boolean online = false;
int originality = input.getOriginality();
int viaPostal = Validator.isNotNull(jsonDossier.getString(DossierTerm.VIA_POSTAL))
? GetterUtil.getInteger(jsonDossier.getString(DossierTerm.VIA_POSTAL)): 0;
ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, input.getServiceCode(),
input.getGovAgencyCode());
if (config != null && Validator.isNotNull(viaPostal)) {
viaPostal = config.getPostService() ? (viaPostal == 0 ? 1 : viaPostal) : 0;
} else if (config != null) {
viaPostal = config.getPostService() ? 1 : 0;
}
//Get service process
ServiceProcess process = null;
if (option != null) {
process = serviceProcessLocalService.getServiceProcess(serviceProcessId);
if (process == null) {
throw new NotFoundException("Cant find process");
}
}
ServiceInfo service = serviceInfoLocalService.getByCode(groupId, input.getServiceCode());
String serviceName = service != null ? service.getServiceName(): StringPool.BLANK;
String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, input.getGovAgencyCode());
//DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(ADMINISTRATIVE_REGION, groupId);
//String cityName = getDictItemName(groupId, dc, input.getCityCode());
//String districtName = getDictItemName(groupId, dc, input.getDistrictCode());
//String wardName = getDictItemName(groupId, dc, input.getWardCode());
// _log.info("Service code: " + input.getServiceCode());
//_log.debug("===ADD DOSSIER CITY NAME:" + cityName);
String password = StringPool.BLANK;
if (Validator.isNotNull(jsonDossier.getString("password"))) {
password = jsonDossier.getString("password");
} else if (Validator.isNotNull(process.getGeneratePassword()) && process.getGeneratePassword()) {
if (OpenCPSConfigUtil.getDefaultDossierSecretLength() > DossierTerm.PIN_LENGTH) {
password = PwdGenerator.getPassword(OpenCPSConfigUtil.getDefaultDossierSecretLength(), PwdGenerator.KEY1);
}
else {
password = PwdGenerator.getPinNumber();
}
}
String postalCityName = StringPool.BLANK;
if (Validator.isNotNull(jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE))) {
postalCityName = getDictItemName(groupId, VNPOST_CITY_CODE, jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE));
}
int sampleCount = (option != null ? (int) option.getSampleCount() : 1);
String registerBookCode = (option != null
? (Validator.isNotNull(option.getRegisterBookCode()) ? option.getRegisterBookCode()
: StringPool.BLANK) : StringPool.BLANK);
//String registerBookName = (Validator.isNotNull(registerBookCode)
// ? getDictItemName(groupId, REGISTER_BOOK, registerBookCode) : StringPool.BLANK);
String registerBookName = StringPool.BLANK;
if (Validator.isNotNull(registerBookCode)) {
DynamicReport report = DynamicReportLocalServiceUtil.fetchByG_CODE(groupId, registerBookCode);
if (report != null) {
registerBookName = report.getReportName();
}
}
_log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms");
Long appIdDateLong = jsonDossier.getLong(DossierTerm.APPLICANT_ID_DATE);
Date appIdDate = null;
if (appIdDateLong > 0) {
appIdDate = new Date(appIdDateLong);
}
// Params add dossier
String applicantName = jsonDossier.getString(DossierTerm.APPLICANT_NAME);
String applicantIdType = jsonDossier.getString(DossierTerm.APPLICANT_ID_TYPE);
String applicantIdNo = jsonDossier.getString(DossierTerm.APPLICANT_ID_NO);
String address = jsonDossier.getString(DossierTerm.ADDRESS);
String contactName = jsonDossier.getString(DossierTerm.CONTACT_NAME);
String contactTelNo = jsonDossier.getString(DossierTerm.CONTACT_TEL_NO);
String contactEmail = jsonDossier.getString(DossierTerm.CONTACT_EMAIL);
//
String postalServiceCode = jsonDossier.getString(DossierTerm.POSTAL_SERVICE_CODE);
String postalServiceName = jsonDossier.getString(DossierTerm.POSTAL_SERVICE_NAME);
String postalAddress = jsonDossier.getString(DossierTerm.POSTAL_ADDRESS);
String postalCityCode = jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE);
String postalDistrictCode = jsonDossier.getString(DossierTerm.POSTAL_DISTRICT_CODE);
String postalDistrictName = jsonDossier.getString(DossierTerm.POSTAL_DISTRICT_NAME);
String postalWardCode = jsonDossier.getString(DossierTerm.POSTAL_WARD_CODE);
String postalWardName = jsonDossier.getString(DossierTerm.POSTAL_WARD_NAME);
String postalTelNo = jsonDossier.getString(DossierTerm.POSTAL_TEL_NO);
String applicantNote = jsonDossier.getString(DossierTerm.APPLICANT_NOTE);
String delegateIdNo = jsonDossier.getString(DossierTerm.DELEGATE_ID_NO);
String delegateName = jsonDossier.getString(DossierTerm.DELEGATE_NAME);
String delegateTelNo = jsonDossier.getString(DossierTerm.DELEGATE_TELNO);
String delegateEmail = jsonDossier.getString(DossierTerm.DELEGATE_EMAIL);
String delegateAddress = jsonDossier.getString(DossierTerm.DELEGATE_ADDRESS);
//TODO
String delegateCityCode = jsonDossier.getString(DossierTerm.DELEGATE_CITYCODE);
String delegateCityName = StringPool.BLANK;
if (Validator.isNotNull(delegateCityCode)) {
delegateCityName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateCityCode);
}
String delegateDistrictCode = jsonDossier.getString(DossierTerm.DELEGATE_DISTRICTCODE);
String delegateDistrictName = StringPool.BLANK;
if (Validator.isNotNull(delegateDistrictCode)) {
delegateDistrictName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateDistrictCode);
}
String delegateWardCode = jsonDossier.getString(DossierTerm.DELEGATE_WARDCODE);
String delegateWardName = StringPool.BLANK;
if (Validator.isNotNull(delegateWardCode)) {
delegateWardName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateWardCode);
}
//
String dossierName = Validator.isNotNull(jsonDossier.getString(DossierTerm.DOSSIER_NAME)) ? jsonDossier.getString(DossierTerm.DOSSIER_NAME) : serviceName;
Long receiveDateTimeStamp = jsonDossier.getLong(DossierTerm.RECEIVE_DATE);
Date receiveDate = null;
if (receiveDateTimeStamp > 0) {
receiveDate = new Date(receiveDateTimeStamp);
}
Long dueDateTimeStamp = jsonDossier.getLong(DossierTerm.DUE_DATE);
Date dueDate = null;
if (dueDateTimeStamp > 0) {
dueDate = new Date(dueDateTimeStamp);
}
String metaData = jsonDossier.getString(DossierTerm.META_DATA);
dossier = dossierLocalService.initMultipleDossier(groupId, 0l, referenceUid, counter,
input.getServiceCode(), serviceName, input.getGovAgencyCode(), govAgencyName, applicantName,
applicantIdType, applicantIdNo, appIdDate, address, contactName, contactTelNo, contactEmail,
input.getDossierTemplateNo(), password, viaPostal, postalServiceCode, postalServiceName,
postalAddress, postalCityCode, postalCityName, postalDistrictCode, postalDistrictName,
postalWardCode, postalWardName, postalTelNo, online, process.getDirectNotification(), applicantNote,
input.getOriginality(), delegateIdNo, delegateName, delegateTelNo, delegateEmail, delegateAddress,
delegateCityCode, delegateCityName, delegateDistrictCode, delegateDistrictName, delegateWardCode,
delegateWardName, registerBookCode, registerBookName, sampleCount, dossierName, service, process,
option, serviceContext);
if (receiveDate != null)
dossier.setReceiveDate(receiveDate);
if (dueDate != null)
dossier.setDueDate(dueDate);
if (Validator.isNotNull(metaData))
dossier.setMetaData(metaData);
//
dossier.setSystemId(input.getSystemId());
//TODO: Process then
//updateDelegateApplicant(dossier, input);
_log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms");
if (originality != DossierTerm.ORIGINALITY_LIENTHONG) {
Applicant applicant = ApplicantLocalServiceUtil.fetchByMappingID(serviceContext.getUserId());
if (applicant != null) {
updateApplicantInfo(dossier,
applicant.getApplicantIdDate(),
applicant.getApplicantIdNo(),
applicant.getApplicantIdType(),
applicant.getApplicantName(),
applicant.getAddress(),
applicant.getCityCode(),
applicant.getCityName(),
applicant.getDistrictCode(),
applicant.getDistrictName(),
applicant.getWardCode(),
applicant.getWardName(),
applicant.getContactEmail(),
applicant.getContactTelNo()
);
}
}
if (Validator.isNull(dossier)) {
throw new NotFoundException("Cant add DOSSIER");
}
_log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms");
//TODO
/** Create DossierMark */
//_log.debug("flagOldDossier: "+flagOldDossier);
_log.debug("originality: "+originality);
String templateNo = dossier.getDossierTemplateNo();
_log.debug("templateNo: "+templateNo);
long dossierId = dossier.getDossierId();
if (originality == DossierTerm.ORIGINALITY_MOTCUA || originality == DossierTerm.ORIGINALITY_LIENTHONG) {
if (Validator.isNotNull(input.getDossierMarkArr())) {
JSONArray markArr = JSONFactoryUtil.createJSONArray(input.getDossierMarkArr());
if (markArr != null && markArr.length() > 0) {
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossierId);
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[markArr.length()];
for (int i = 0; i < markArr.length(); i++) {
JSONObject jsonMark = markArr.getJSONObject(i);
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(jsonMark.getString("partNo"));
model.setFileCheck(0);
model.setFileMark(jsonMark.getInt("fileMark"));
model.setFileComment(StringPool.BLANK);
model.setRecordCount(StringPool.BLANK);
marks[i] = model;
}
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
}
} else if (Validator.isNotNull(templateNo)) {
List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo);
// _log.info("partList: "+partList);
if (partList != null && partList.size() > 0) {
_log.debug("partList.size(): "+partList.size());
_log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms");
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()];
int count = 0;
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossierId);
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
for (DossierPart dossierPart : partList) {
int fileMark = dossierPart.getFileMark();
String dossierPartNo = dossierPart.getPartNo();
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(dossierPartNo);
model.setFileCheck(0);
model.setFileMark(fileMark);
model.setFileComment(StringPool.BLANK);
model.setRecordCount(StringPool.BLANK);
marks[count++] = model;
}
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
_log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms");
}
}
}
/**
* Add dossier file
*/
String strDossierFileId = input.getDossierFileArr();
if (Validator.isNotNull(strDossierFileId)) {
String[] splitDossierFileId = strDossierFileId.split(StringPool.COMMA);
if (splitDossierFileId != null && splitDossierFileId.length > 0) {
for (String strFileId : splitDossierFileId) {
processCloneDossierFile(Long.valueOf(strFileId), dossier.getDossierId(), userId);
}
}
}
/**Create dossier user */
List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId());
List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId());
if (lstDus.size() == 0) {
DossierUserActions duActions = new DossierUserActionsImpl();
duActions.initDossierUser(groupId, dossier, process, lstProcessRoles);
}
if (originality == DossierTerm.ORIGINALITY_DVCTT) {
dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true);
}
_log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms");
// if (dossier != null) {
// //
// long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName());
//
// NotificationQueue queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId);
// //Process add notification queue
// Date now = new Date();
//
// Calendar cal = Calendar.getInstance();
// cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1);
//
// queue.setCreateDate(now);
// queue.setModifiedDate(now);
// queue.setGroupId(groupId);
// queue.setCompanyId(company.getCompanyId());
//
// queue.setNotificationType(NotificationType.DOSSIER_01);
// queue.setClassName(Dossier.class.getName());
// queue.setClassPK(String.valueOf(dossier.getPrimaryKey()));
// queue.setToUsername(dossier.getUserName());
// queue.setToUserId(dossier.getUserId());
// queue.setToEmail(dossier.getContactEmail());
// queue.setToTelNo(dossier.getContactTelNo());
//
// JSONObject payload = JSONFactoryUtil.createJSONObject();
// try {
//// _log.info("START PAYLOAD: ");
// payload.put(
// "Dossier", JSONFactoryUtil.createJSONObject(
// JSONFactoryUtil.looseSerialize(dossier)));
// }
// catch (JSONException parse) {
// _log.error(parse);
// }
//// _log.info("payloadTest: "+payload.toJSONString());
// queue.setPayload(payload.toJSONString());
// queue.setExpireDate(cal.getTime());
//
// NotificationQueueLocalServiceUtil.addNotificationQueue(queue);
// }
_log.debug("CREATE DOSSIER 6: " + (System.currentTimeMillis() - start) + " ms");
//Add to dossier user based on service process role
createDossierUsers(groupId, dossier, process, lstProcessRoles);
_log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms");
dossierLocalService.updateDossier(dossier);
_log.debug("CREATE DOSSIER 8: " + (System.currentTimeMillis() - start) + " ms");
String payload = StringPool.BLANK;
String actionCode = "1100";
if (dossier.getReceiveDate() == null) {
JSONObject jsonDate = JSONFactoryUtil.createJSONObject();
jsonDate.put(DossierTerm.RECEIVE_DATE, (new Date()).getTime());
Double durationCount = process.getDurationCount();
if (Validator.isNotNull(String.valueOf(durationCount)) && durationCount > 0d) {
// Date dueDateCal = HolidayUtils.getDueDate(new Date(), process.getDurationCount(),
// process.getDurationUnit(), groupId);
DueDateUtils dueDateUtils = new DueDateUtils(new Date(), process.getDurationCount(),
process.getDurationUnit(), groupId);
Date dueDateCal = dueDateUtils.getDueDate();
jsonDate.put(DossierTerm.DUE_DATE, dueDateCal != null ? dueDateCal.getTime() : 0);
}
if (Validator.isNotNull(jsonDate)) {
payload = jsonDate.toJSONString();
}
}
//
ProcessAction proAction = getProcessAction(user.getUserId(), groupId, dossier, actionCode,
serviceProcessId);
doAction(groupId, userId, dossier, option, proAction, actionCode, StringPool.BLANK, StringPool.BLANK,
payload, StringPool.BLANK, input.getPayment(), 0, serviceContext);
}
return dossier;
}
private void processCloneDossierFile(Long dossierFileId, long dossierId, long userId) throws PortalException {
DossierFile dossierFileParent = dossierFileLocalService.fetchDossierFile(dossierFileId);
if (dossierFileParent != null) {
long dossierFileChildrenId = counterLocalService.increment(DossierFile.class.getName());
DossierFile object = dossierFilePersistence.create(dossierFileChildrenId);
_log.debug("****End uploadFile file at:" + new Date());
Date now = new Date();
User userAction = null;
if (userId != 0) {
userAction = userLocalService.getUser(userId);
}
// Add audit fields
object.setCompanyId(dossierFileParent.getCompanyId());
object.setGroupId(dossierFileParent.getGroupId());
object.setCreateDate(now);
object.setModifiedDate(now);
object.setUserId(userAction != null ? userAction.getUserId() : 0l);
object.setUserName(userAction != null ? userAction.getFullName() : StringPool.BLANK);
// Add other fields
object.setDossierId(dossierId);
object.setReferenceUid(PortalUUIDUtil.generate());
object.setDossierTemplateNo(dossierFileParent.getDossierTemplateNo());
object.setFileEntryId(dossierFileParent.getFileEntryId());
object.setDossierPartNo(dossierFileParent.getDossierPartNo());
object.setFileTemplateNo(dossierFileParent.getFileTemplateNo());
object.setDossierPartType(dossierFileParent.getDossierPartType());
_log.debug("****Start autofill file at:" + new Date());
object.setDisplayName(dossierFileParent.getDisplayName());
object.setOriginal(false);
object.setIsNew(true);
object.setFormData(dossierFileParent.getFormData());
object.setEForm(dossierFileParent.getEForm());
object.setRemoved(false);
object.setSignCheck(dossierFileParent.getSignCheck());
object.setFormScript(dossierFileParent.getFormScript());
object.setFormReport(dossierFileParent.getFormReport());
object.setFormSchema(dossierFileParent.getFormSchema());
dossierFilePersistence.update(object);
}
}
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { SystemException.class, PortalException.class,
Exception.class })
public Dossier addFullDossier(long groupId, Company company, User user, ServiceContext serviceContext,
DossierMultipleInputModel input) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
DossierPermission dossierPermission = new DossierPermission();
long start = System.currentTimeMillis();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
ProcessOption option = getProcessOption(input.getServiceCode(), input.getGovAgencyCode(),
input.getDossierTemplateNo(), groupId);
long serviceProcessId = 0;
if (option != null) {
serviceProcessId = option.getServiceProcessId();
}
boolean flag = false;
long userId = serviceContext.getUserId();
Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId);
if (employee != null) {
long employeeId = employee.getEmployeeId();
if (employeeId > 0) {
List<EmployeeJobPos> empJobList = EmployeeJobPosLocalServiceUtil.findByF_EmployeeId(employeeId);
if (empJobList != null && empJobList.size() > 0) {
for (EmployeeJobPos employeeJobPos : empJobList) {
long jobPosId = employeeJobPos.getJobPostId();
if (jobPosId > 0) {
JobPos job = JobPosLocalServiceUtil.fetchJobPos(jobPosId);
if (job != null) {
ServiceProcessRolePK pk = new ServiceProcessRolePK(serviceProcessId,
job.getMappingRoleId());
ServiceProcessRole role = serviceProcessRoleLocalService
.fetchServiceProcessRole(pk);
if (role != null && role.getModerator()) {
flag = true;
break;
}
}
}
}
}
}
} else {
flag = true;
}
if (!flag) {
throw new UnauthenticationException("No permission create dossier");
}
_log.debug("CREATE DOSSIER 1: " + (System.currentTimeMillis() - start) + " ms");
dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(),
input.getGovAgencyCode(), input.getDossierTemplateNo());
Dossier dossier = null;
if (Validator.isNotNull(input.getDossiers())) {
JSONObject jsonDossier = JSONFactoryUtil.createJSONObject(input.getDossiers());
//Get params input dossier
String referenceUid = jsonDossier.getString(DossierTerm.REFERENCE_UID);
if (Validator.isNull(referenceUid) || referenceUid.trim().length() == 0)
referenceUid = DossierNumberGenerator.generateReferenceUID(groupId);
int counter = 0;
//boolean online = GetterUtil.getBoolean(input.getOnline());
boolean online = false;
int originality = input.getOriginality();
int viaPostal = Validator.isNotNull(jsonDossier.getString(DossierTerm.VIA_POSTAL))
? GetterUtil.getInteger(jsonDossier.getString(DossierTerm.VIA_POSTAL)): 0;
ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, input.getServiceCode(),
input.getGovAgencyCode());
if (config != null && Validator.isNotNull(viaPostal)) {
viaPostal = config.getPostService() ? (viaPostal == 0 ? 1 : viaPostal) : 0;
} else if (config != null) {
viaPostal = config.getPostService() ? 1 : 0;
}
//Get service process
ServiceProcess process = null;
if (option != null) {
process = serviceProcessLocalService.getServiceProcess(serviceProcessId);
if (process == null) {
throw new NotFoundException("Cant find process");
}
}
ServiceInfo service = serviceInfoLocalService.getByCode(groupId, input.getServiceCode());
String serviceName = service != null ? service.getServiceName(): StringPool.BLANK;
String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, input.getGovAgencyCode());
//DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(ADMINISTRATIVE_REGION, groupId);
//String cityName = getDictItemName(groupId, dc, input.getCityCode());
//String districtName = getDictItemName(groupId, dc, input.getDistrictCode());
//String wardName = getDictItemName(groupId, dc, input.getWardCode());
// _log.info("Service code: " + input.getServiceCode());
//_log.debug("===ADD DOSSIER CITY NAME:" + cityName);
String password = StringPool.BLANK;
if (Validator.isNotNull(jsonDossier.getString("password"))) {
password = jsonDossier.getString("password");
} else if (Validator.isNotNull(process.getGeneratePassword()) && process.getGeneratePassword()) {
if (OpenCPSConfigUtil.getDefaultDossierSecretLength() > DossierTerm.PIN_LENGTH) {
password = PwdGenerator.getPassword(OpenCPSConfigUtil.getDefaultDossierSecretLength(), PwdGenerator.KEY1);
}
else {
password = PwdGenerator.getPinNumber();
}
}
String postalCityName = StringPool.BLANK;
if (Validator.isNotNull(jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE))) {
postalCityName = getDictItemName(groupId, VNPOST_CITY_CODE, jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE));
}
int sampleCount = (option != null ? (int) option.getSampleCount() : 1);
String registerBookCode = (option != null
? (Validator.isNotNull(option.getRegisterBookCode()) ? option.getRegisterBookCode()
: StringPool.BLANK) : StringPool.BLANK);
//String registerBookName = (Validator.isNotNull(registerBookCode)
// ? getDictItemName(groupId, REGISTER_BOOK, registerBookCode) : StringPool.BLANK);
String registerBookName = StringPool.BLANK;
if (Validator.isNotNull(registerBookCode)) {
DynamicReport report = DynamicReportLocalServiceUtil.fetchByG_CODE(groupId, registerBookCode);
if (report != null) {
registerBookName = report.getReportName();
}
}
_log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms");
Long appIdDateLong = jsonDossier.getLong(DossierTerm.APPLICANT_ID_DATE);
Date appIdDate = null;
if (appIdDateLong > 0) {
appIdDate = new Date(appIdDateLong);
}
// Params add dossier
String applicantName = jsonDossier.getString(DossierTerm.APPLICANT_NAME);
String applicantIdType = jsonDossier.getString(DossierTerm.APPLICANT_ID_TYPE);
String applicantIdNo = jsonDossier.getString(DossierTerm.APPLICANT_ID_NO);
String address = jsonDossier.getString(DossierTerm.ADDRESS);
String contactName = jsonDossier.getString(DossierTerm.CONTACT_NAME);
String contactTelNo = jsonDossier.getString(DossierTerm.CONTACT_TEL_NO);
String contactEmail = jsonDossier.getString(DossierTerm.CONTACT_EMAIL);
//
String postalServiceCode = jsonDossier.getString(DossierTerm.POSTAL_SERVICE_CODE);
String postalServiceName = jsonDossier.getString(DossierTerm.POSTAL_SERVICE_NAME);
String postalAddress = jsonDossier.getString(DossierTerm.POSTAL_ADDRESS);
String postalCityCode = jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE);
String postalDistrictCode = jsonDossier.getString(DossierTerm.POSTAL_DISTRICT_CODE);
String postalDistrictName = jsonDossier.getString(DossierTerm.POSTAL_DISTRICT_NAME);
String postalWardCode = jsonDossier.getString(DossierTerm.POSTAL_WARD_CODE);
String postalWardName = jsonDossier.getString(DossierTerm.POSTAL_WARD_NAME);
String postalTelNo = jsonDossier.getString(DossierTerm.POSTAL_TEL_NO);
String applicantNote = jsonDossier.getString(DossierTerm.APPLICANT_NOTE);
String delegateIdNo = jsonDossier.getString(DossierTerm.DELEGATE_ID_NO);
String delegateName = jsonDossier.getString(DossierTerm.DELEGATE_NAME);
String delegateTelNo = jsonDossier.getString(DossierTerm.DELEGATE_TELNO);
String delegateEmail = jsonDossier.getString(DossierTerm.DELEGATE_EMAIL);
String delegateAddress = jsonDossier.getString(DossierTerm.DELEGATE_ADDRESS);
//TODO
String cityCode = jsonDossier.getString(DossierTerm.CITY_CODE);
String cityName = StringPool.BLANK;
if (Validator.isNotNull(cityCode)) {
cityName = getDictItemName(groupId, ADMINISTRATIVE_REGION, cityCode);
}
String districtCode = jsonDossier.getString(DossierTerm.DISTRICT_CODE);
String districtName = StringPool.BLANK;
if (Validator.isNotNull(districtCode)) {
districtName = getDictItemName(groupId, ADMINISTRATIVE_REGION, districtCode);
}
String wardCode = jsonDossier.getString(DossierTerm.WARD_CODE);
String wardName = StringPool.BLANK;
if (Validator.isNotNull(wardCode)) {
wardName = getDictItemName(groupId, ADMINISTRATIVE_REGION, wardCode);
}
//
String delegateCityCode = jsonDossier.getString(DossierTerm.DELEGATE_CITYCODE);
String delegateCityName = StringPool.BLANK;
if (Validator.isNotNull(delegateCityCode)) {
delegateCityName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateCityCode);
}
String delegateDistrictCode = jsonDossier.getString(DossierTerm.DELEGATE_DISTRICTCODE);
String delegateDistrictName = StringPool.BLANK;
if (Validator.isNotNull(delegateDistrictCode)) {
delegateDistrictName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateDistrictCode);
}
String delegateWardCode = jsonDossier.getString(DossierTerm.DELEGATE_WARDCODE);
String delegateWardName = StringPool.BLANK;
if (Validator.isNotNull(delegateWardCode)) {
delegateWardName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateWardCode);
}
//
String dossierName = Validator.isNotNull(jsonDossier.getString(DossierTerm.DOSSIER_NAME)) ? jsonDossier.getString(DossierTerm.DOSSIER_NAME) : serviceName;
Long receiveDateTimeStamp = jsonDossier.getLong(DossierTerm.RECEIVE_DATE);
Date receiveDate = null;
if (receiveDateTimeStamp > 0) {
receiveDate = new Date(receiveDateTimeStamp);
}
Long dueDateTimeStamp = jsonDossier.getLong(DossierTerm.DUE_DATE);
Date dueDate = null;
if (dueDateTimeStamp > 0) {
dueDate = new Date(dueDateTimeStamp);
}
String metaData = jsonDossier.getString(DossierTerm.META_DATA);
dossier = dossierLocalService.initMultipleDossier(groupId, 0l, referenceUid, counter,
input.getServiceCode(), serviceName, input.getGovAgencyCode(), govAgencyName, applicantName,
applicantIdType, applicantIdNo, appIdDate, address, contactName, contactTelNo, contactEmail,
input.getDossierTemplateNo(), password, viaPostal, postalServiceCode, postalServiceName,
postalAddress, postalCityCode, postalCityName, postalDistrictCode, postalDistrictName,
postalWardCode, postalWardName, postalTelNo, online, process.getDirectNotification(), applicantNote,
input.getOriginality(), delegateIdNo, delegateName, delegateTelNo, delegateEmail, delegateAddress,
delegateCityCode, delegateCityName, delegateDistrictCode, delegateDistrictName, delegateWardCode,
delegateWardName, registerBookCode, registerBookName, sampleCount, dossierName, service, process,
option, serviceContext);
if (receiveDate != null)
dossier.setReceiveDate(receiveDate);
if (dueDate != null)
dossier.setDueDate(dueDate);
if (Validator.isNotNull(metaData))
dossier.setMetaData(metaData);
if (Validator.isNotNull(address))
dossier.setAddress(address);
if (Validator.isNotNull(cityCode))
dossier.setCityCode(cityCode);
if (Validator.isNotNull(cityName))
dossier.setCityName(cityName);
if (Validator.isNotNull(districtCode))
dossier.setDistrictCode(districtCode);
if (Validator.isNotNull(districtName))
dossier.setDistrictName(districtName);
if (Validator.isNotNull(wardCode))
dossier.setWardCode(wardCode);
if (Validator.isNotNull(wardName))
dossier.setWardName(wardName);
//
dossier.setSystemId(input.getSystemId());
//TODO: Process then
//updateDelegateApplicant(dossier, input);
_log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms");
if (originality != DossierTerm.ORIGINALITY_LIENTHONG) {
Applicant applicant = ApplicantLocalServiceUtil.fetchByMappingID(serviceContext.getUserId());
if (applicant != null) {
updateApplicantInfo(dossier,
applicant.getApplicantIdDate(),
applicant.getApplicantIdNo(),
applicant.getApplicantIdType(),
applicant.getApplicantName(),
applicant.getAddress(),
applicant.getCityCode(),
applicant.getCityName(),
applicant.getDistrictCode(),
applicant.getDistrictName(),
applicant.getWardCode(),
applicant.getWardName(),
applicant.getContactEmail(),
applicant.getContactTelNo()
);
}
}
if (Validator.isNull(dossier)) {
throw new NotFoundException("Cant add DOSSIER");
}
_log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms");
/** Create DossierMark */
//_log.debug("flagOldDossier: "+flagOldDossier);
_log.debug("originality: "+originality);
String templateNo = dossier.getDossierTemplateNo();
_log.debug("templateNo: "+templateNo);
long dossierId = dossier.getDossierId();
if (originality == DossierTerm.ORIGINALITY_MOTCUA || originality == DossierTerm.ORIGINALITY_LIENTHONG) {
if (Validator.isNotNull(input.getDossierMarkArr())) {
JSONArray markArr = JSONFactoryUtil.createJSONArray(input.getDossierMarkArr());
if (markArr != null && markArr.length() > 0) {
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossierId);
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[markArr.length()];
for (int i = 0; i < markArr.length(); i++) {
JSONObject jsonMark = markArr.getJSONObject(i);
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(jsonMark.getString("partNo"));
model.setFileCheck(0);
model.setFileMark(jsonMark.getInt("fileMark"));
model.setFileComment(StringPool.BLANK);
model.setRecordCount(StringPool.BLANK);
marks[i] = model;
}
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
}
} else if (Validator.isNotNull(templateNo)) {
List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo);
// _log.info("partList: "+partList);
if (partList != null && partList.size() > 0) {
_log.debug("partList.size(): "+partList.size());
_log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms");
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()];
int count = 0;
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossierId);
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
for (DossierPart dossierPart : partList) {
int fileMark = dossierPart.getFileMark();
String dossierPartNo = dossierPart.getPartNo();
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(dossierPartNo);
model.setFileCheck(0);
model.setFileMark(fileMark);
model.setFileComment(StringPool.BLANK);
model.setRecordCount(StringPool.BLANK);
marks[count++] = model;
}
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
_log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms");
}
}
}
/**
* Add dossier file
*/
if (Validator.isNotNull(input.getDossierFileArr())) {
JSONArray dossierFileArr = JSONFactoryUtil.createJSONArray(input.getDossierFileArr());
if (dossierFileArr != null && dossierFileArr.length() > 0) {
for (int j = 0; j < dossierFileArr.length(); j++) {
JSONObject jsonFile = dossierFileArr.getJSONObject(j);
boolean eform = Boolean.valueOf(jsonFile.getString("eform"));
if (eform) {
//EFORM
_log.info("In dossier file create by eform");
try {
// String referenceUidFile = UUID.randomUUID().toString();
String partNo = jsonFile.getString(DossierPartTerm.PART_NO);
String formData = jsonFile.getString(ConstantUtils.FORM_DATA);
DossierFile dossierFile = null;
// DossierFileActions action = new DossierFileActionsImpl();
DossierPart dossierPart = dossierPartLocalService.fetchByTemplatePartNo(groupId, templateNo, partNo);
//_log.info("__file:" + file);
//DataHandler dataHandler = (file != null) ? file.getDataHandler() : null;
dossierFile = DossierFileLocalServiceUtil.getByGID_DID_PART_EFORM(groupId, dossierId,
partNo, true, false);
if (dossierFile == null) {
_log.info("dossierFile NULL");
dossierFile = dossierFileLocalService.addDossierFileEForm(groupId, dossierId, referenceUid,
templateNo, partNo, dossierPart.getFileTemplateNo(), dossierPart.getPartName(), dossierPart.getPartName(), 0,
null, StringPool.BLANK, "true", serviceContext);
}
if(Validator.isNotNull(formData)) {
dossierFile.setFormData(formData);
}
if(Validator.isNotNull(eform)) {
dossierFile.setEForm(eform);
}
_log.info("__Start update dossier file at:" + new Date());
DossierFileLocalServiceUtil.updateDossierFile(dossierFile);
dossierFileLocalService.updateFormData(groupId, dossierId, dossierFile.getReferenceUid(), formData,
serviceContext);
_log.info("__End update dossier file at:" + new Date());
} catch (Exception e) {
_log.debug(e);
}
}
}
}
}
/**Create dossier user */
List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId());
List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId());
if (lstDus.size() == 0) {
DossierUserActions duActions = new DossierUserActionsImpl();
duActions.initDossierUser(groupId, dossier, process, lstProcessRoles);
}
if (originality == DossierTerm.ORIGINALITY_DVCTT) {
dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true);
}
_log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms");
// if (dossier != null) {
// //
// long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName());
//
// NotificationQueue queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId);
// //Process add notification queue
// Date now = new Date();
//
// Calendar cal = Calendar.getInstance();
// cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1);
//
// queue.setCreateDate(now);
// queue.setModifiedDate(now);
// queue.setGroupId(groupId);
// queue.setCompanyId(company.getCompanyId());
//
// queue.setNotificationType(NotificationType.DOSSIER_01);
// queue.setClassName(Dossier.class.getName());
// queue.setClassPK(String.valueOf(dossier.getPrimaryKey()));
// queue.setToUsername(dossier.getUserName());
// queue.setToUserId(dossier.getUserId());
// queue.setToEmail(dossier.getContactEmail());
// queue.setToTelNo(dossier.getContactTelNo());
//
// JSONObject payload = JSONFactoryUtil.createJSONObject();
// try {
//// _log.info("START PAYLOAD: ");
// payload.put(
// "Dossier", JSONFactoryUtil.createJSONObject(
// JSONFactoryUtil.looseSerialize(dossier)));
// }
// catch (JSONException parse) {
// _log.error(parse);
// }
//// _log.info("payloadTest: "+payload.toJSONString());
// queue.setPayload(payload.toJSONString());
// queue.setExpireDate(cal.getTime());
//
// NotificationQueueLocalServiceUtil.addNotificationQueue(queue);
// }
_log.debug("CREATE DOSSIER 6: " + (System.currentTimeMillis() - start) + " ms");
//Add to dossier user based on service process role
createDossierUsers(groupId, dossier, process, lstProcessRoles);
_log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms");
dossierLocalService.updateDossier(dossier);
_log.debug("CREATE DOSSIER 8: " + (System.currentTimeMillis() - start) + " ms");
String payload = StringPool.BLANK;
String actionCode = "1100";
if (dossier.getReceiveDate() == null) {
JSONObject jsonDate = JSONFactoryUtil.createJSONObject();
jsonDate.put(DossierTerm.RECEIVE_DATE, (new Date()).getTime());
Double durationCount = process.getDurationCount();
if (Validator.isNotNull(String.valueOf(durationCount)) && durationCount > 0d) {
// Date dueDateCal = HolidayUtils.getDueDate(new Date(), process.getDurationCount(),
// process.getDurationUnit(), groupId);
DueDateUtils dueDateUtils = new DueDateUtils(new Date(), process.getDurationCount(),
process.getDurationUnit(), groupId);
Date dueDateCal = dueDateUtils.getDueDate();
jsonDate.put(DossierTerm.DUE_DATE, dueDateCal != null ? dueDateCal.getTime() : 0);
}
if (Validator.isNotNull(jsonDate)) {
payload = jsonDate.toJSONString();
}
}
//
ProcessAction proAction = getProcessAction(user.getUserId(), groupId, dossier, actionCode,
serviceProcessId);
doAction(groupId, userId, dossier, option, proAction, actionCode, StringPool.BLANK, StringPool.BLANK,
payload, StringPool.BLANK, input.getPayment(), 0, serviceContext);
}
return dossier;
}
private void createDossierUsers(long groupId, Dossier dossier, ServiceProcess process, List<ServiceProcessRole> lstProcessRoles) {
List<DossierUser> lstDaus = dossierUserLocalService.findByDID(dossier.getDossierId());
int count = 0;
long[] roleIds = new long[lstProcessRoles.size()];
for (ServiceProcessRole spr : lstProcessRoles) {
long roleId = spr.getRoleId();
roleIds[count++] = roleId;
}
List<JobPos> lstJobPoses = JobPosLocalServiceUtil.findByF_mappingRoleIds(groupId, roleIds);
Map<Long, JobPos> mapJobPoses = new HashMap<>();
long[] jobPosIds = new long[lstJobPoses.size()];
count = 0;
for (JobPos jp : lstJobPoses) {
mapJobPoses.put(jp.getJobPosId(), jp);
jobPosIds[count++] = jp.getJobPosId();
}
List<EmployeeJobPos> lstTemp = EmployeeJobPosLocalServiceUtil.findByF_G_jobPostIds(groupId, jobPosIds);
Map<Long, List<EmployeeJobPos>> mapEJPS = new HashMap<>();
for (EmployeeJobPos ejp : lstTemp) {
if (mapEJPS.get(ejp.getJobPostId()) != null) {
mapEJPS.get(ejp.getJobPostId()).add(ejp);
}
else {
List<EmployeeJobPos> lstEJPs = new ArrayList<>();
lstEJPs.add(ejp);
mapEJPS.put(ejp.getJobPostId(), lstEJPs);
}
}
for (ServiceProcessRole spr : lstProcessRoles) {
long roleId = spr.getRoleId();
int moderator = spr.getModerator() ? 1 : 0;
// JobPos jp = JobPosLocalServiceUtil.fetchByF_mappingRoleId(groupId, roleId);
JobPos jp = mapJobPoses.get(roleId);
if (jp != null) {
// List<EmployeeJobPos> lstEJPs = EmployeeJobPosLocalServiceUtil.getByJobPostId(groupId, jp.getJobPosId());
List<EmployeeJobPos> lstEJPs = mapEJPS.get(jp.getJobPosId());
long[] employeeIds = new long[lstEJPs.size()];
int countEmp = 0;
for (EmployeeJobPos ejp : lstEJPs) {
employeeIds[countEmp++] = ejp.getEmployeeId();
}
List<Employee> lstEmpls = EmployeeLocalServiceUtil.findByG_EMPID(groupId, employeeIds);
HashMap<Long, Employee> mapEmpls = new HashMap<>();
for (Employee e : lstEmpls) {
mapEmpls.put(e.getEmployeeId(), e);
}
List<Employee> lstEmployees = new ArrayList<>();
// for (EmployeeJobPos ejp : lstEJPs) {
// Employee employee = EmployeeLocalServiceUtil.fetchEmployee(ejp.getEmployeeId());
// if (employee != null) {
// lstEmployees.add(employee);
// }
// }
for (EmployeeJobPos ejp : lstEJPs) {
if (mapEmpls.get(ejp.getEmployeeId()) != null) {
lstEmployees.add(mapEmpls.get(ejp.getEmployeeId()));
}
}
HashMap<Long, DossierUser> mapDaus = new HashMap<>();
for (DossierUser du : lstDaus) {
mapDaus.put(du.getUserId(), du);
}
for (Employee e : lstEmployees) {
// DossierUserPK pk = new DossierUserPK();
// pk.setDossierId(dossier.getDossierId());
// pk.setUserId(e.getMappingUserId());
// DossierUser ds = DossierUserLocalServiceUtil.fetchDossierUser(pk);
if (mapDaus.get(e.getMappingUserId()) == null) {
// if (ds == null) {
dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), e.getMappingUserId(), moderator, Boolean.FALSE);
}
else {
DossierUser ds = mapDaus.get(e.getMappingUserId());
if (moderator == 1 && ds.getModerator() == 0) {
ds.setModerator(1);
dossierUserLocalService.updateDossierUser(ds);
}
}
}
}
}
}
private void updateApplicantInfo(Dossier dossier, Date applicantIdDate,
String applicantIdNo,
String applicantIdType,
String applicantName,
String address,
String cityCode,
String cityName,
String districtCode,
String districtName,
String wardCode,
String wardName,
String contactEmail,
String contactTelNo) {
dossier.setApplicantIdDate(applicantIdDate);
dossier.setApplicantIdNo(applicantIdNo);
dossier.setApplicantIdType(applicantIdType);
dossier.setApplicantName(applicantName);
dossier.setAddress(address);
dossier.setCityCode(cityCode);
dossier.setCityName(cityName);
dossier.setDistrictCode(districtCode);
dossier.setDistrictName(districtName);
dossier.setWardCode(wardCode);
dossier.setWardName(wardName);
dossier.setContactEmail(contactEmail);
dossier.setContactTelNo(contactTelNo);
dossier.setDelegateAddress(address);
dossier.setDelegateCityCode(cityCode);
dossier.setDelegateCityName(cityName);
dossier.setDelegateDistrictCode(districtCode);
dossier.setDelegateDistrictName(districtName);
dossier.setDelegateEmail(contactEmail);
dossier.setDelegateIdNo(applicantIdNo);
dossier.setDelegateName(applicantName);
dossier.setDelegateTelNo(contactTelNo);
dossier.setDelegateWardCode(wardCode);
dossier.setDelegateWardName(wardName);
}
private void updateDelegateApplicant(Dossier dossier, DossierInputModel input) {
if (Validator.isNotNull(input.getDelegateName())) {
dossier.setDelegateName(input.getDelegateName());
}
if (Validator.isNotNull(input.getDelegateIdNo())) {
dossier.setDelegateIdNo(input.getDelegateIdNo());
}
if (Validator.isNotNull(input.getDelegateTelNo())) {
dossier.setDelegateTelNo(input.getDelegateTelNo());
}
if (Validator.isNotNull(input.getDelegateEmail())) {
dossier.setDelegateEmail(input.getDelegateEmail());
}
if (Validator.isNotNull(input.getDelegateAddress())) {
dossier.setDelegateAddress(input.getDelegateAddress());
}
if (Validator.isNotNull(input.getDelegateCityCode())) {
dossier.setDelegateCityCode(input.getDelegateCityCode());
}
if (Validator.isNotNull(input.getDelegateCityName())) {
dossier.setDelegateCityName(input.getDelegateCityName());
}
if (Validator.isNotNull(input.getDelegateDistrictCode())) {
dossier.setDelegateDistrictCode(input.getDelegateDistrictCode());
}
if (Validator.isNotNull(input.getDelegateDistrictName())) {
dossier.setDelegateDistrictName(input.getDelegateDistrictName());
}
if (Validator.isNotNull(input.getDelegateWardCode())) {
dossier.setDelegateWardCode(input.getDelegateWardCode());
}
if (Validator.isNotNull(input.getDelegateWardName())) {
dossier.setDelegateWardCode(input.getDelegateWardName());
}
}
private String getDictItemName(long groupId, DictCollection dc, String itemCode) {
if (Validator.isNotNull(dc)) {
DictItem it = DictItemLocalServiceUtil.fetchByF_dictItemCode(itemCode, dc.getPrimaryKey(), groupId);
if(Validator.isNotNull(it)){
return it.getItemName();
}else{
return StringPool.BLANK;
}
} else {
return StringPool.BLANK;
}
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public DossierFile addDossierFileByDossierId(long groupId, Company company, User user, ServiceContext serviceContext,
Attachment file, String id, String referenceUid,
String dossierTemplateNo, String dossierPartNo, String fileTemplateNo, String displayName, String fileType,
String isSync, String formData, String removed, String eForm, Long modifiedDate) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
long dossierId = GetterUtil.getLong(id);
Dossier dossier = null;
if (dossierId != 0) {
dossier = dossierLocalService.fetchDossier(dossierId);
if (Validator.isNull(dossier)) {
dossier = dossierLocalService.getByRef(groupId, id);
}
} else {
dossier = dossierLocalService.getByRef(groupId, id);
}
DataHandler dataHandler = (file != null) ? file.getDataHandler() : null;
long originDossierId = dossier.getOriginDossierId();
DossierPart dossierPart = null;
String originDossierTemplateNo = StringPool.BLANK;
if (originDossierId != 0) {
//HSLT
Dossier hsltDossier = dossierLocalService.fetchDossier(dossier.getDossierId());
dossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId());
ServiceConfig serviceConfig = serviceConfigLocalService.getBySICodeAndGAC(groupId, dossier.getServiceCode(), hsltDossier.getGovAgencyCode());
List<ProcessOption> lstOptions = processOptionLocalService.getByServiceProcessId(serviceConfig.getServiceConfigId());
originDossierTemplateNo = dossier.getDossierTemplateNo();
if (serviceConfig != null) {
if (lstOptions.size() > 0) {
ProcessOption processOption = lstOptions.get(0);
DossierTemplate dossierTemplate = dossierTemplateLocalService.fetchDossierTemplate(processOption.getDossierTemplateId());
List<DossierPart> lstParts = dossierPartLocalService.getByTemplateNo(groupId, dossierTemplate.getTemplateNo());
for (DossierPart dp : lstParts) {
if (dp.getPartNo().equals(dossierPartNo) && dp.getFileTemplateNo().equals(fileTemplateNo)) {
dossierTemplateNo = dp.getTemplateNo();
dossierPart = dp;
break;
}
}
}
}
}
else {
List<DossierPart> lstParts = dossierPartLocalService.getByTemplateNo(groupId, dossier.getDossierTemplateNo());
for (DossierPart dp : lstParts) {
if (dp.getPartNo().equals(dossierPartNo)) {
fileTemplateNo = dp.getFileTemplateNo();
dossierTemplateNo = dossier.getDossierTemplateNo();
dossierPart = dp;
break;
}
}
}
if (originDossierId > 0) {
_log.debug("__Start add file at:" + new Date());
DossierFile dossierFile = null;
DossierFile oldDossierFile = null;
if (Validator.isNotNull(referenceUid)) {
oldDossierFile = dossierFileLocalService.getByDossierAndRef(dossier.getDossierId(), referenceUid);
} else if (dossierPart != null && !dossierPart.getMultiple()) {
// oldDossierFile = dossierFileLocalService.getByGID_DID_TEMP_PART_EFORM(groupId, dossier.getDossierId(),
// dossierTemplateNo, dossierPartNo, false, false);
oldDossierFile = dossierFileLocalService.getByGID_DID_TEMP_PART_EFORM(groupId, dossier.getDossierId(),
originDossierTemplateNo, dossierPartNo, false, false);
}
if (oldDossierFile != null && modifiedDate != null) {
if (oldDossierFile.getModifiedDate() != null && oldDossierFile.getModifiedDate().getTime() < modifiedDate) {
if (dataHandler != null && dataHandler.getInputStream() != null) {
dossierFile = dossierFileLocalService.updateDossierFile(groupId, dossier.getDossierId(),
oldDossierFile.getReferenceUid(), displayName, dataHandler.getName(), 0,
dataHandler.getInputStream(), fileType, isSync, serviceContext);
} else {
dossierFile = dossierFileLocalService.updateDossierFile(groupId, dossier.getDossierId(),
oldDossierFile.getReferenceUid(), displayName, displayName, 0, null, fileType, isSync,
serviceContext);
}
_log.debug("__End add file at:" + new Date());
if(Validator.isNotNull(formData)) {
dossierFile.setFormData(formData);
}
_log.debug("REMOVED:" + removed);
if(Validator.isNotNull(removed)) {
dossierFile.setRemoved(Boolean.parseBoolean(removed));
}
if(Validator.isNotNull(eForm)) {
dossierFile.setEForm(Boolean.parseBoolean(eForm));
}
if (Validator.isNull(eForm) || (Validator.isNotNull(eForm) && !Boolean.parseBoolean(eForm))) {
dossierFile.setFormData(StringPool.BLANK);
dossierFile.setIsNew(false);
}
_log.debug("__Start update dossier file at:" + new Date());
dossierFileLocalService.updateDossierFile(dossierFile);
_log.debug("__End update dossier file at:" + new Date());
_log.debug("__End bind to dossierFile" + new Date());
return dossierFile;
}
else {
throw new DataConflictException("Conflict dossier file");
}
}
else {
_log.debug("__Start add file at:" + new Date());
if (dataHandler != null && dataHandler.getInputStream() != null) {
// dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, dossierTemplateNo,
// dossierPartNo, fileTemplateNo, displayName, dataHandler.getName(), 0,
// dataHandler.getInputStream(), fileType, isSync, serviceContext);
dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, originDossierTemplateNo,
dossierPartNo, fileTemplateNo, displayName, dataHandler.getName(), 0,
dataHandler.getInputStream(), fileType, isSync, serviceContext);
} else {
// dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, dossierTemplateNo,
// dossierPartNo, fileTemplateNo, displayName, displayName, 0, null, fileType, isSync,
// serviceContext);
dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, originDossierTemplateNo,
dossierPartNo, fileTemplateNo, displayName, displayName, 0, null, fileType, isSync,
serviceContext);
}
_log.debug("__End add file at:" + new Date());
if(Validator.isNotNull(formData)) {
dossierFile.setFormData(formData);
}
if(Validator.isNotNull(removed)) {
dossierFile.setRemoved(Boolean.parseBoolean(removed));
}
if(Validator.isNotNull(eForm)) {
dossierFile.setEForm(Boolean.parseBoolean(eForm));
}
if (Validator.isNull(eForm) || (Validator.isNotNull(eForm) && !Boolean.parseBoolean(eForm))) {
dossierFile.setFormData(StringPool.BLANK);
dossierFile.setIsNew(false);
}
_log.debug("__Start update dossier file at:" + new Date());
dossierFileLocalService.updateDossierFile(dossierFile);
_log.debug("__End update dossier file at:" + new Date());
_log.debug("__End bind to dossierFile" + new Date());
return dossierFile;
}
} else {
// DossierFile lastDossierFile = DossierFileLocalServiceUtil.findLastDossierFile(dossier.getDossierId(), fileTemplateNo, dossierTemplateNo);
//_log.info("lastDossierFile: "+lastDossierFile);
DossierFile oldDossierFile = null;
if (Validator.isNotNull(referenceUid)) {
oldDossierFile = DossierFileLocalServiceUtil.getByDossierAndRef(dossier.getDossierId(), referenceUid);
} else if (dossierPart != null && !dossierPart.getMultiple()) {
oldDossierFile = dossierFileLocalService.getByGID_DID_TEMP_PART_EFORM(groupId, dossier.getDossierId(),
dossierTemplateNo, dossierPartNo, false, false);
_log.info("dossierPart.getMultiple: "+dossierPart.getMultiple());
}
_log.info("oldDossierFile: "+oldDossierFile);
if (oldDossierFile != null && modifiedDate != null) {
if (oldDossierFile.getModifiedDate() != null && oldDossierFile.getModifiedDate().getTime() < modifiedDate) {
_log.debug("__Start add file at:" + new Date());
DossierFile dossierFile = null;
if (dataHandler != null && dataHandler.getInputStream() != null) {
dossierFile = dossierFileLocalService.updateDossierFile(groupId, dossier.getDossierId(),
oldDossierFile.getReferenceUid(), displayName, dataHandler.getName(), 0,
dataHandler.getInputStream(), fileType, isSync, serviceContext);
} else {
dossierFile = dossierFileLocalService.updateDossierFile(groupId, dossier.getDossierId(),
oldDossierFile.getReferenceUid(), displayName, displayName, 0, null, fileType, isSync,
serviceContext);
}
_log.debug("__End add file at:" + new Date());
if(Validator.isNotNull(formData)) {
dossierFile.setFormData(formData);
}
if(Validator.isNotNull(removed)) {
dossierFile.setRemoved(Boolean.parseBoolean(removed));
}
if(Validator.isNotNull(eForm)) {
dossierFile.setEForm(Boolean.parseBoolean(eForm));
}
if (Validator.isNull(eForm) || (Validator.isNotNull(eForm) && !Boolean.parseBoolean(eForm))) {
dossierFile.setFormData(StringPool.BLANK);
dossierFile.setIsNew(false);
}
_log.debug("__Start update dossier file at:" + new Date());
DossierFileLocalServiceUtil.updateDossierFile(dossierFile);
_log.debug("__End update dossier file at:" + new Date());
_log.debug("__End bind to dossierFile" + new Date());
return dossierFile;
}
else {
throw new DataConflictException("Conflict dossier file");
}
}
else {
_log.debug("__Start add file at:" + new Date());
DossierFile dossierFile = null;
if (dataHandler != null && dataHandler.getInputStream() != null) {
dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, dossierTemplateNo,
dossierPartNo, fileTemplateNo, displayName, dataHandler.getName(), 0,
dataHandler.getInputStream(), fileType, isSync, serviceContext);
} else {
dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, dossierTemplateNo,
dossierPartNo, fileTemplateNo, displayName, displayName, 0, null, fileType, isSync,
serviceContext);
}
_log.debug("__End add file at:" + new Date());
if(Validator.isNotNull(formData)) {
dossierFile.setFormData(formData);
}
if(Validator.isNotNull(removed)) {
dossierFile.setRemoved(Boolean.parseBoolean(removed));
}
if(Validator.isNotNull(eForm)) {
dossierFile.setEForm(Boolean.parseBoolean(eForm));
}
if (Validator.isNull(eForm) || (Validator.isNotNull(eForm) && !Boolean.parseBoolean(eForm))) {
dossierFile.setFormData(StringPool.BLANK);
dossierFile.setIsNew(false);
}
_log.debug("__Start update dossier file at:" + new Date());
dossierFileLocalService.updateDossierFile(dossierFile);
_log.debug("__End update dossier file at:" + new Date());
_log.debug("__End bind to dossierFile" + new Date());
return dossierFile;
}
}
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public DossierFile updateDossierFile(long groupId, Company company, ServiceContext serviceContext, long id, String referenceUid, Attachment file)
throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
DataHandler dataHandle = file.getDataHandler();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
Dossier dossier = dossierLocalService.fetchDossier(id);
if (dossier != null) {
if (dossier.getOriginDossierId() != 0) {
dossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId());
id = dossier.getDossierId();
}
}
DossierFile dossierFile = dossierFileLocalService.updateDossierFile(groupId, id, referenceUid, dataHandle.getName(),
StringPool.BLANK,
dataHandle.getInputStream(), serviceContext);
return dossierFile;
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public DossierFile updateDossierFileFormData(long groupId, Company company,
ServiceContext serviceContext, long id, String referenceUid, String formdata) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
Dossier dossier = dossierLocalService.fetchDossier(id);
if (dossier != null) {
if (dossier.getOriginDossierId() != 0) {
dossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId());
id = dossier.getOriginDossierId();
}
}
DossierFile dossierFile = dossierFileLocalService.updateFormData(groupId, id, referenceUid, formdata,
serviceContext);
return dossierFile;
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public DossierFile resetformdataDossierFileFormData(long groupId, Company company,
ServiceContext serviceContext, long id, String referenceUid, String formdata) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
Dossier dossier = dossierLocalService.fetchDossier(id);
DossierFile dossierFile = null;
if (dossier != null) {
if (dossier.getOriginDossierId() != 0) {
dossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId());
//id = dossier.getOriginDossierId();
}
dossierFile = dossierFileLocalService.getDossierFileByReferenceUid(dossier.getDossierId(), referenceUid);
String defaultData = StringPool.BLANK;
if (Validator.isNotNull(dossierFile)) {
DossierPart part = dossierPartLocalService.getByFileTemplateNo(groupId,
dossierFile.getFileTemplateNo());
defaultData = AutoFillFormData.sampleDataBinding(part.getSampleData(), dossier.getDossierId(), serviceContext);
dossierFile = dossierFileLocalService.getByReferenceUid(referenceUid).get(0);
JSONObject defaultDataObj = JSONFactoryUtil.createJSONObject(defaultData);
defaultDataObj.put(KeyPayTerm.LicenceNo, dossierFile.getDeliverableCode());
defaultData = defaultDataObj.toJSONString();
}
dossierFile = dossierFileLocalService.updateFormData(groupId, dossier.getDossierId(), referenceUid, defaultData,
serviceContext);
String deliverableCode = dossierFile.getDeliverableCode();
if (Validator.isNotNull(deliverableCode)) {
Deliverable deliverable = deliverableLocalService.getByCode(deliverableCode);
deliverableLocalService.deleteDeliverable(deliverable);
}
}
return dossierFile;
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public PaymentFile createPaymentFileByDossierId(long groupId, ServiceContext serviceContext, String id, PaymentFileInputModel input) throws UnauthenticationException, PortalException, Exception {
long userId = serviceContext.getUserId();
BackendAuth auth = new BackendAuthImpl();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
Dossier dossier = getDossier(id, groupId);
PaymentFile paymentFile = null;
if (dossier != null) {
long dossierId = dossier.getPrimaryKey();
// if (!auth.hasResource(serviceContext, PaymentFile.class.getName(), ActionKeys.ADD_ENTRY)) {
// throw new UnauthorizationException();
// }
PaymentFile oldPaymentFile = paymentFileLocalService.getByDossierId(groupId, dossier.getDossierId());
String referenceUid = input.getReferenceUid();
if (Validator.isNull(referenceUid)) {
referenceUid = PortalUUIDUtil.generate();
}
if (oldPaymentFile != null) {
paymentFile = oldPaymentFile;
}
else {
paymentFile = paymentFileLocalService.createPaymentFiles(userId, groupId, dossierId, referenceUid,
input.getPaymentFee(), input.getAdvanceAmount(), input.getFeeAmount(), input.getServiceAmount(),
input.getShipAmount(), input.getPaymentAmount(), input.getPaymentNote(),
input.getEpaymentProfile(), input.getBankInfo(), 0,
input.getPaymentMethod(), serviceContext);
}
if (Validator.isNotNull(input.getInvoiceTemplateNo())) {
paymentFile.setInvoiceTemplateNo(input.getInvoiceTemplateNo());
}
if(Validator.isNotNull(input.getConfirmFileEntryId())){
paymentFile.setConfirmFileEntryId(input.getConfirmFileEntryId());
}
if(Validator.isNotNull(input.getPaymentStatus())){
paymentFile.setPaymentStatus(input.getPaymentStatus());
}
if(Validator.isNotNull(input.getEinvoice())) {
paymentFile.setEinvoice(input.getEinvoice());
}
if(Validator.isNotNull(input.getPaymentAmount())) {
paymentFile.setPaymentAmount(input.getPaymentAmount());
}
if(Validator.isNotNull(input.getPaymentMethod())){
paymentFile.setPaymentMethod(input.getPaymentMethod());
}
if(Validator.isNotNull(input.getServiceAmount())){
paymentFile.setServiceAmount(input.getServiceAmount());
}
if(Validator.isNotNull(input.getShipAmount())){
paymentFile.setShipAmount(input.getShipAmount());
}
if(Validator.isNotNull(input.getAdvanceAmount())){
paymentFile.setAdvanceAmount(input.getAdvanceAmount());
}
if(Validator.isNotNull(input.getFeeAmount())){
paymentFile.setFeeAmount(input.getFeeAmount());
}
if(Validator.isNotNull(input.getPaymentNote())){
paymentFile.setPaymentNote(input.getPaymentNote());
}
paymentFile = paymentFileLocalService.updatePaymentFile(paymentFile);
}
return paymentFile;
}
private Dossier getDossier(String id, long groupId) throws PortalException {
long dossierId = GetterUtil.getLong(id);
Dossier dossier = null;
if (dossierId != 0) {
dossier = dossierLocalService.fetchDossier(dossierId);
}
if (Validator.isNull(dossier)) {
dossier = dossierLocalService.getByRef(groupId, id);
}
return dossier;
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public Dossier addDossierPublish(long groupId, Company company,
User user, ServiceContext serviceContext, org.opencps.dossiermgt.input.model.DossierPublishModel input) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
DossierActions actions = new DossierActionsImpl();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
String referenceUid = input.getReferenceUid();
int counter = 0;
String serviceCode = input.getServiceCode();
String serviceName = input.getServiceName();
String govAgencyCode = input.getGovAgencyCode();
String govAgencyName = input.getGovAgencyName();
String applicantName = input.getApplicantName();
String applicantType = input.getApplicantIdType();
String applicantIdNo = input.getApplicantIdNo();
String applicantIdDate = input.getApplicantIdDate();
String address = input.getAddress();
String cityCode = input.getCityCode();
String cityName = input.getCityName();
String districtCode = input.getDistrictCode();
String districtName = input.getDistrictName();
String wardCode = input.getWardCode();
String wardName = input.getWardName();
String contactName = input.getContactName();
String contactTelNo = input.getContactTelNo();
String contactEmail = input.getContactEmail();
String dossierTemplateNo = input.getDossierTemplateNo();
String password = input.getPassword();
String online = input.getOnline();
String applicantNote = input.getApplicantNote();
int originality = 0;
long createDateLong = GetterUtil.getLong(input.getCreateDate());
long modifiedDateLong = GetterUtil.getLong(input.getModifiedDate());
long submitDateLong = GetterUtil.getLong(input.getSubmitDate());
long receiveDateLong = GetterUtil.getLong(input.getReceiveDate());
long dueDateLong = GetterUtil.getLong(input.getDueDate());
long releaseDateLong = GetterUtil.getLong(input.getReleaseDate());
long finishDateLong = GetterUtil.getLong(input.getFinishDate());
long cancellingDateLong = GetterUtil.getLong(input.getCancellingDate());
long correcttingDateLong = GetterUtil.getLong(input.getCorrecttingDate());
long endorsementDateLong = GetterUtil.getLong(input.getEndorsementDate());
long extendDateLong = GetterUtil.getLong(input.getExtendDate());
long processDateLong = GetterUtil.getLong(input.getProcessDate());
String submissionNote = input.getSubmissionNote();
String lockState = input.getLockState();
String dossierNo = input.getDossierNo();
Dossier oldDossier = null;
if (Validator.isNotNull(input.getReferenceUid())) {
oldDossier = getDossier(input.getReferenceUid(), groupId);
} else {
oldDossier = DossierLocalServiceUtil.getByDossierNo(groupId, dossierNo);
referenceUid = DossierNumberGenerator.generateReferenceUID(groupId);
}
if (oldDossier == null || oldDossier.getOriginality() == 0) {
Dossier dossier = actions.publishDossier(groupId, 0l, referenceUid, counter, serviceCode, serviceName,
govAgencyCode, govAgencyName, applicantName, applicantType, applicantIdNo, applicantIdDate, address,
cityCode, cityName, districtCode, districtName, wardCode, wardName, contactName, contactTelNo,
contactEmail, dossierTemplateNo, password, 0, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK,
StringPool.BLANK, Boolean.valueOf(online), false, applicantNote, originality,
createDateLong != 0 ? new Date(createDateLong) : null,
modifiedDateLong != 0 ? new Date(modifiedDateLong) : null,
submitDateLong != 0 ? new Date(submitDateLong) : null,
receiveDateLong != 0 ? new Date(receiveDateLong) : null,
dueDateLong != 0 ? new Date(dueDateLong) : null,
releaseDateLong != 0 ? new Date(releaseDateLong) : null,
finishDateLong != 0 ? new Date(finishDateLong) : null,
cancellingDateLong != 0 ? new Date(cancellingDateLong) : null,
correcttingDateLong != 0 ? new Date(correcttingDateLong) : null,
endorsementDateLong != 0 ? new Date(endorsementDateLong) : null,
extendDateLong != 0 ? new Date(extendDateLong) : null,
processDateLong != 0 ? new Date(processDateLong) : null, input.getDossierNo(),
input.getDossierStatus(), input.getDossierStatusText(), input.getDossierSubStatus(),
input.getDossierSubStatusText(),
input.getDossierActionId() != null ? input.getDossierActionId() : 0, submissionNote, lockState,
input.getDelegateName(), input.getDelegateIdNo(), input.getDelegateTelNo(),
input.getDelegateEmail(), input.getDelegateAddress(), input.getDelegateCityCode(),
input.getDelegateCityName(), input.getDelegateDistrictCode(), input.getDelegateDistrictName(),
input.getDelegateWardCode(), input.getDelegateWardName(), input.getDurationCount(),
input.getDurationUnit(), input.getDossierName(), input.getProcessNo(), input.getMetaData(), input.getVnpostalStatus(), input.getVnpostalProfile(), serviceContext);
return dossier;
}
return oldDossier;
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public Dossier addFullDossier(long groupId, Company company, User user, ServiceContext serviceContext,
DossierInputModel input) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
DossierPermission dossierPermission = new DossierPermission();
long start = System.currentTimeMillis();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
ProcessOption option = getProcessOption(input.getServiceCode(), input.getGovAgencyCode(),
input.getDossierTemplateNo(), groupId);
long serviceProcessId = 0;
if (option != null) {
serviceProcessId = option.getServiceProcessId();
}
boolean flag = false;
long userId = serviceContext.getUserId();
Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId);
if (employee != null) {
long employeeId = employee.getEmployeeId();
if (employeeId > 0) {
List<EmployeeJobPos> empJobList = EmployeeJobPosLocalServiceUtil.findByF_EmployeeId(employeeId);
if (empJobList != null && empJobList.size() > 0) {
for (EmployeeJobPos employeeJobPos : empJobList) {
long jobPosId = employeeJobPos.getJobPostId();
if (jobPosId > 0) {
JobPos job = JobPosLocalServiceUtil.fetchJobPos(jobPosId);
if (job != null) {
ServiceProcessRolePK pk = new ServiceProcessRolePK(serviceProcessId,
job.getMappingRoleId());
ServiceProcessRole role = serviceProcessRoleLocalService
.fetchServiceProcessRole(pk);
if (role != null && role.getModerator()) {
flag = true;
break;
}
}
}
}
}
}
} else {
flag = true;
}
if (!flag) {
throw new UnauthenticationException("No permission create dossier");
}
_log.debug("CREATE DOSSIER 1: " + (System.currentTimeMillis() - start) + " ms");
dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(),
input.getGovAgencyCode(), input.getDossierTemplateNo());
//int counter = DossierNumberGenerator.counterDossier(user.getUserId(), groupId);
String referenceUid = input.getReferenceUid();
int counter = 0;
// Create dossierNote
ServiceProcess process = null;
boolean online = GetterUtil.getBoolean(input.getOnline());
int originality = GetterUtil.getInteger(input.getOriginality());
Integer viaPostal = input.getViaPostal();
ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, input.getServiceCode(),
input.getGovAgencyCode());
if (config != null && Validator.isNotNull(viaPostal)) {
viaPostal = config.getPostService() ? (viaPostal == 0 ? 1 : viaPostal) : 0;
}
else if (config != null) {
viaPostal = config.getPostService() ? 1 : 0;
}
if (option != null) {
process = serviceProcessLocalService.getServiceProcess(serviceProcessId);
}
if (process == null) {
throw new NotFoundException("Cant find process");
}
if (Validator.isNull(referenceUid) || referenceUid.trim().length() == 0)
referenceUid = DossierNumberGenerator.generateReferenceUID(groupId);
//Dossier checkDossier = dossierLocalService.getByRef(groupId, referenceUid);
//if (checkDossier != null) {
// return checkDossier;
//}
ServiceInfo service = serviceInfoLocalService.getByCode(groupId, input.getServiceCode());
String serviceName = StringPool.BLANK;
if (service != null) {
serviceName = service.getServiceName();
}
String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, input.getGovAgencyCode());
DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(ADMINISTRATIVE_REGION, groupId);
String cityName = getDictItemName(groupId, dc, input.getCityCode());
String districtName = getDictItemName(groupId, dc, input.getDistrictCode());
String wardName = getDictItemName(groupId, dc, input.getWardCode());
// _log.info("Service code: " + input.getServiceCode());
_log.debug("===ADD DOSSIER CITY NAME:" + cityName);
String password = StringPool.BLANK;
if (Validator.isNotNull(input.getPassword())) {
password = input.getPassword();
} else if (Validator.isNotNull(process.getGeneratePassword()) && process.getGeneratePassword()) {
if (OpenCPSConfigUtil.getDefaultDossierSecretLength() > DossierTerm.PIN_LENGTH) {
password = PwdGenerator.getPassword(OpenCPSConfigUtil.getDefaultDossierSecretLength(), PwdGenerator.KEY1);
}
else {
password = PwdGenerator.getPinNumber();
}
}
String postalCityName = StringPool.BLANK;
if (Validator.isNotNull(input.getPostalCityCode())) {
postalCityName = getDictItemName(groupId, VNPOST_CITY_CODE, input.getPostalCityCode());
}
Long sampleCount = (option != null ? option.getSampleCount() : 1l);
// Process group dossier
if (originality == DossierTerm.ORIGINALITY_HOSONHOM) {
_log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date appIdDate = null;
try {
appIdDate = sdf.parse(input.getApplicantIdDate());
} catch (Exception e) {
_log.debug(e);
}
Dossier dossier = dossierLocalService.initDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName,
input.getGovAgencyCode(), govAgencyName, input.getApplicantName(), input.getApplicantIdType(),
input.getApplicantIdNo(), appIdDate, input.getAddress(), input.getCityCode(),
cityName, input.getDistrictCode(), districtName, input.getWardCode(), wardName,
input.getContactName(), input.getContactTelNo(), input.getContactEmail(),
input.getDossierTemplateNo(), password, viaPostal, input.getPostalAddress(), input.getPostalCityCode(), postalCityName,
input.getPostalTelNo(), online, process.getDirectNotification(), input.getApplicantNote(),
Integer.valueOf(input.getOriginality()),
service, process, option,
serviceContext);
if (Validator.isNotNull(input.getDossierName())) {
dossier.setDossierName(input.getDossierName());
} else {
dossier.setDossierName(serviceName);
}
dossier.setSampleCount(sampleCount);
updateDelegateApplicant(dossier, input);
// Process update dossierNo
LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();
params.put(DossierTerm.GOV_AGENCY_CODE, dossier.getGovAgencyCode());
params.put(DossierTerm.SERVICE_CODE, dossier.getServiceCode());
params.put(DossierTerm.DOSSIER_TEMPLATE_NO, dossier.getDossierTemplateNo());
params.put(DossierTerm.DOSSIER_STATUS, StringPool.BLANK);
if (option != null) {
//Process submition note
dossier.setSubmissionNote(option.getSubmissionNote());
String dossierRef = DossierNumberGenerator.generateDossierNumber(groupId, dossier.getCompanyId(),
dossier.getDossierId(), option.getProcessOptionId(), process.getDossierGroupPattern(), params);
dossier.setDossierNo(dossierRef.trim());
}
dossier.setViaPostal(1);
_log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms");
if (Validator.isNull(dossier)) {
throw new NotFoundException("Can't add DOSSIER");
}
_log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms");
//Create DossierMark
_log.debug("originality: "+originality);
String templateNo = dossier.getDossierTemplateNo();
_log.debug("templateNo: "+templateNo);
if (Validator.isNotNull(input.getDossierMarkArr())) {
JSONArray markArr = JSONFactoryUtil.createJSONArray(input.getDossierMarkArr());
if (markArr != null && markArr.length() > 0) {
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId());
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
for (int i = 0; i < markArr.length(); i++) {
JSONObject jsonMark = markArr.getJSONObject(i);
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[markArr.length()];
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(jsonMark.getString("partNo"));
model.setFileCheck(0);
model.setFileMark(jsonMark.getInt("fileMark"));
model.setFileComment(StringPool.BLANK);
model.setRecordCount(StringPool.BLANK);
marks[i] = model;
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
}
}
} else if (Validator.isNotNull(templateNo)) {
List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo);
// _log.info("partList: "+partList);
if (partList != null && partList.size() > 0) {
_log.debug("partList.size(): "+partList.size());
_log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms");
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()];
int count = 0;
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId());
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
for (DossierPart dossierPart : partList) {
int fileMark = dossierPart.getFileMark();
String dossierPartNo = dossierPart.getPartNo();
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(dossierPartNo);
model.setFileCheck(0);
model.setFileMark(fileMark);
model.setFileComment(StringPool.BLANK);
model.setRecordCount(StringPool.BLANK);
marks[count++] = model;
}
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
_log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms");
}
}
//Create dossier user
List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId());
List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId());
if (lstDus.size() == 0) {
DossierUserActions duActions = new DossierUserActionsImpl();
duActions.initDossierUser(groupId, dossier, process, lstProcessRoles);
}
// if (originality == DossierTerm.ORIGINALITY_DVCTT) {
// dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true);
// }
_log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms");
//Add to dossier user based on service process role
createDossierUsers(groupId, dossier, process, lstProcessRoles);
_log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms");
return dossierLocalService.updateDossier(dossier);
} else {
List<Dossier> oldDossiers = dossierLocalService.getByU_G_GAC_SC_DTNO_DS_O(
userId, groupId, input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo(), StringPool.BLANK, Integer.valueOf(input.getOriginality()));
Dossier dossier = null;
Dossier oldRefDossier = Validator.isNotNull(input.getReferenceUid()) ? dossierLocalService.getByRef(groupId, input.getReferenceUid()) : null;
if (originality == DossierTerm.ORIGINALITY_DVCTT) {
online = true;
}
boolean flagOldDossier = false;
String registerBookCode = (option != null ? (Validator.isNotNull(option.getRegisterBookCode()) ? option.getRegisterBookCode() : StringPool.BLANK) : StringPool.BLANK);
//String registerBookName = (Validator.isNotNull(registerBookCode) ? getDictItemName(groupId, REGISTER_BOOK, registerBookCode) : StringPool.BLANK);
String registerBookName = StringPool.BLANK;
if (Validator.isNotNull(registerBookCode)) {
DynamicReport report = DynamicReportLocalServiceUtil.fetchByG_CODE(groupId, registerBookCode);
if (report != null) {
registerBookName = report.getReportName();
}
}
_log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms");
if (oldRefDossier != null) {
dossier = oldRefDossier;
dossier.setSubmitDate(new Date());
ServiceProcess serviceProcess = process;
double durationCount = 0;
int durationUnit = 0;
if (serviceProcess != null ) {
durationCount = serviceProcess.getDurationCount();
durationUnit = serviceProcess.getDurationUnit();
dossier.setDurationCount(durationCount);
dossier.setDurationUnit(durationUnit);
}
if (durationCount > 0) {
// Date dueDate = HolidayUtils.getDueDate(new Date(), durationCount, durationUnit, groupId);
DueDateUtils dueDateUtils = new DueDateUtils(new Date(), durationCount, durationUnit, groupId);
Date dueDate = dueDateUtils.getDueDate();
dossier.setDueDate(dueDate);
}
}
else if (oldDossiers.size() > 0) {
flagOldDossier = true;
dossier = oldDossiers.get(0);
dossier.setApplicantName(input.getApplicantName());
dossier.setApplicantNote(input.getApplicantNote());
dossier.setApplicantIdNo(input.getApplicantIdNo());
dossier.setAddress(input.getAddress());
dossier.setContactEmail(input.getContactEmail());
dossier.setContactName(input.getContactName());
dossier.setContactTelNo(input.getContactTelNo());
dossier.setDelegateName(input.getDelegateName());
dossier.setDelegateEmail(input.getDelegateEmail());
dossier.setDelegateAddress(input.getDelegateAddress());
dossier.setPostalAddress(input.getPostalAddress());
dossier.setPostalCityCode(input.getPostalCityCode());
dossier.setPostalCityName(postalCityName);
dossier.setPostalTelNo(input.getPostalTelNo());
dossier.setPostalServiceCode(input.getPostalServiceCode());
dossier.setPostalServiceName(input.getPostalServiceName());
dossier.setPostalDistrictCode(input.getPostalDistrictCode());
dossier.setPostalDistrictName(input.getPostalDistrictName());
dossier.setPostalWardCode(input.getPostalWardCode());
dossier.setPostalWardName(input.getPostalWardName());
dossier.setPostalTelNo(input.getPostalTelNo());
dossier.setViaPostal(viaPostal);
dossier.setOriginDossierNo(input.getOriginDossierNo());
if (Validator.isNotNull(registerBookCode)) {
dossier.setRegisterBookCode(registerBookCode);
}
dossier.setRegisterBookName(registerBookName);
dossier.setSampleCount(sampleCount);
dossier.setServiceCode(input.getServiceCode());
dossier.setGovAgencyCode(input.getGovAgencyCode());
dossier.setDossierTemplateNo(input.getDossierTemplateNo());
updateDelegateApplicant(dossier, input);
// dossier.setDossierNo(input.getDossierNo());
dossier.setSubmitDate(new Date());
// ServiceProcess serviceProcess = ServiceProcessLocalServiceUtil.fetchServiceProcess(serviceProcessId);
ServiceProcess serviceProcess = process;
double durationCount = 0;
int durationUnit = 0;
if (serviceProcess != null ) {
durationCount = serviceProcess.getDurationCount();
durationUnit = serviceProcess.getDurationUnit();
dossier.setDurationCount(durationCount);
dossier.setDurationUnit(durationUnit);
}
if (durationCount > 0) {
// Date dueDate = HolidayUtils.getDueDate(new Date(), durationCount, durationUnit, groupId);
DueDateUtils dueDateUtils = new DueDateUtils(new Date(), durationCount, durationUnit, groupId);
Date dueDate = dueDateUtils.getDueDate();
dossier.setDueDate(dueDate);
}
dossier.setOnline(online);
if (Validator.isNotNull(input.getDossierName()))
dossier.setDossierName(input.getDossierName());
if (serviceProcess != null) {
dossier.setProcessNo(serviceProcess.getProcessNo());
}
// dossier = DossierLocalServiceUtil.updateDossier(dossier);
}
else {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date appIdDate = null;
try {
appIdDate = sdf.parse(input.getApplicantIdDate());
} catch (Exception e) {
_log.debug(e);
}
dossier = dossierLocalService.initDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName,
input.getGovAgencyCode(), govAgencyName, input.getApplicantName(), input.getApplicantIdType(),
input.getApplicantIdNo(), appIdDate, input.getAddress(), input.getCityCode(),
cityName, input.getDistrictCode(), districtName, input.getWardCode(), wardName,
input.getContactName(), input.getContactTelNo(), input.getContactEmail(),
input.getDossierTemplateNo(), password, viaPostal, input.getPostalAddress(), input.getPostalCityCode(), postalCityName,
input.getPostalTelNo(), online, process.getDirectNotification(), input.getApplicantNote(),
Integer.valueOf(input.getOriginality()),
service, process, option,
serviceContext);
dossier.setDelegateName(input.getDelegateName());
dossier.setDelegateEmail(input.getDelegateEmail());
dossier.setDelegateAddress(input.getDelegateAddress());
if (Validator.isNotNull(input.getDossierName())) {
dossier.setDossierName(input.getDossierName());
} else {
dossier.setDossierName(serviceName);
}
dossier.setPostalCityName(postalCityName);
dossier.setPostalTelNo(input.getPostalTelNo());
dossier.setPostalServiceCode(input.getPostalServiceCode());
dossier.setPostalServiceName(input.getPostalServiceName());
dossier.setPostalDistrictCode(input.getPostalDistrictCode());
dossier.setPostalDistrictName(input.getPostalDistrictName());
dossier.setPostalWardCode(input.getPostalWardCode());
dossier.setPostalWardName(input.getPostalWardName());
dossier.setOriginDossierNo(input.getOriginDossierNo());
if (Validator.isNotNull(registerBookCode)) {
dossier.setRegisterBookCode(registerBookCode);
}
dossier.setRegisterBookName(registerBookName);
dossier.setSampleCount(sampleCount);
updateDelegateApplicant(dossier, input);
if (process != null) {
dossier.setProcessNo(process.getProcessNo());
}
// dossier = DossierLocalServiceUtil.updateDossier(dossier);
}
_log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms");
if (originality != DossierTerm.ORIGINALITY_LIENTHONG) {
Applicant applicant = ApplicantLocalServiceUtil.fetchByMappingID(serviceContext.getUserId());
if (applicant != null) {
updateApplicantInfo(dossier,
applicant.getApplicantIdDate(),
applicant.getApplicantIdNo(),
applicant.getApplicantIdType(),
applicant.getApplicantName(),
applicant.getAddress(),
applicant.getCityCode(),
applicant.getCityName(),
applicant.getDistrictCode(),
applicant.getDistrictName(),
applicant.getWardCode(),
applicant.getWardName(),
applicant.getContactEmail(),
applicant.getContactTelNo()
);
}
}
if (Validator.isNull(dossier)) {
throw new NotFoundException("Cant add DOSSIER");
}
_log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms");
//Create DossierMark
_log.debug("flagOldDossier: "+flagOldDossier);
_log.debug("originality: "+originality);
if ((originality == DossierTerm.ORIGINALITY_MOTCUA || originality == DossierTerm.ORIGINALITY_LIENTHONG)
&& !flagOldDossier) {
String templateNo = dossier.getDossierTemplateNo();
_log.debug("templateNo: "+templateNo);
if (Validator.isNotNull(templateNo)) {
List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo);
// _log.info("partList: "+partList);
if (partList != null && partList.size() > 0) {
_log.debug("partList.size(): "+partList.size());
_log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms");
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()];
int count = 0;
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId());
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
for (DossierPart dossierPart : partList) {
int fileMark = dossierPart.getFileMark();
String dossierPartNo = dossierPart.getPartNo();
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(dossierPartNo);
model.setFileCheck(0);
model.setFileMark(fileMark);
model.setFileComment(StringPool.BLANK);
marks[count++] = model;
// DossierMarkLocalServiceUtil.addDossierMark(groupId, dossier.getDossierId(), dossierPartNo,
// fileMark, 0, StringPool.BLANK, serviceContext);
}
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
_log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms");
}
}
}
//Create dossier user
List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId());
List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId());
if (lstDus.size() == 0) {
DossierUserActions duActions = new DossierUserActionsImpl();
// duActions.initDossierUser(groupId, dossier);
duActions.initDossierUser(groupId, dossier, process, lstProcessRoles);
}
if (originality == DossierTerm.ORIGINALITY_DVCTT) {
dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true);
}
_log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms");
// DossierLocalServiceUtil.updateDossier(dossier);
if (dossier != null) {
//
long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName());
NotificationQueue queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId);
//Process add notification queue
Date now = new Date();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1);
queue.setCreateDate(now);
queue.setModifiedDate(now);
queue.setGroupId(groupId);
queue.setCompanyId(company.getCompanyId());
queue.setNotificationType(NotificationType.DOSSIER_01);
queue.setClassName(Dossier.class.getName());
queue.setClassPK(String.valueOf(dossier.getPrimaryKey()));
queue.setToUsername(dossier.getUserName());
queue.setToUserId(dossier.getUserId());
if (isEmailNotify(dossier)) {
queue.setToEmail(dossier.getContactEmail());
}
if (isSmsNotify(dossier)) {
queue.setToTelNo(dossier.getContactTelNo());
}
JSONObject payload = JSONFactoryUtil.createJSONObject();
try {
// _log.info("START PAYLOAD: ");
payload.put(
"Dossier", JSONFactoryUtil.createJSONObject(
JSONFactoryUtil.looseSerialize(dossier)));
}
catch (JSONException parse) {
_log.error(parse);
}
// _log.info("payloadTest: "+payload.toJSONString());
queue.setPayload(payload.toJSONString());
queue.setExpireDate(cal.getTime());
NotificationQueueLocalServiceUtil.addNotificationQueue(queue);
}
_log.debug("CREATE DOSSIER 6: " + (System.currentTimeMillis() - start) + " ms");
//Add to dossier user based on service process role
createDossierUsers(groupId, dossier, process, lstProcessRoles);
_log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms");
dossierLocalService.updateDossier(dossier);
_log.debug("CREATE DOSSIER 8: " + (System.currentTimeMillis() - start) + " ms");
return dossier;
}
}
public static final String GOVERNMENT_AGENCY = ReadFilePropertiesUtils.get(ConstantUtils.GOVERNMENT_AGENCY);
public static final String ADMINISTRATIVE_REGION = ReadFilePropertiesUtils.get(ConstantUtils.VALUE_ADMINISTRATIVE_REGION);
public static final String VNPOST_CITY_CODE = ReadFilePropertiesUtils.get(ConstantUtils.VNPOST_CITY_CODE);
public static final String REGISTER_BOOK = ReadFilePropertiesUtils.get(ConstantUtils.REGISTER_BOOK);
private static final long VALUE_CONVERT_DATE_TIMESTAMP = 1000 * 60 * 60 * 24;
private static final long VALUE_CONVERT_HOUR_TIMESTAMP = 1000 * 60 * 60;
private static ProcessAction getProcessAction(long userId, long groupId, Dossier dossier, String actionCode,
long serviceProcessId) throws PortalException {
//_log.debug("GET PROCESS ACTION____");
ProcessAction action = null;
DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId());
User systemUser = UserLocalServiceUtil.fetchUser(userId);
try {
List<ProcessAction> actions = ProcessActionLocalServiceUtil.getByActionCode(groupId, actionCode,
serviceProcessId);
//_log.debug("GET PROCESS ACTION____" + groupId + "," + actionCode + "," + serviceProcessId);
String dossierStatus = dossier.getDossierStatus();
String dossierSubStatus = dossier.getDossierSubStatus();
String preStepCode;
String curStepCode = StringPool.BLANK;
if (dossier.getDossierActionId() > 0) {
DossierAction curAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId());
if (curAction != null) {
curStepCode = curAction.getStepCode();
}
}
for (ProcessAction act : actions) {
preStepCode = act.getPreStepCode();
//_log.debug("LamTV_preStepCode: "+preStepCode);
if (Validator.isNotNull(curStepCode) && !preStepCode.contentEquals(curStepCode)) continue;
ProcessStep step = ProcessStepLocalServiceUtil.fetchBySC_GID(preStepCode, groupId, serviceProcessId);
// _log.info("LamTV_ProcessStep: "+step);
if (Validator.isNull(step) && dossierAction == null) {
action = act;
break;
} else {
String stepStatus = step != null ? step.getDossierStatus() : StringPool.BLANK;
String stepSubStatus = step != null ? step.getDossierSubStatus() : StringPool.BLANK;
boolean flagCheck = false;
if (dossierAction != null) {
if (act.getPreStepCode().equals(dossierAction.getStepCode())) {
flagCheck = true;
}
}
else {
flagCheck = true;
}
//_log.debug("LamTV_preStepCode: "+stepStatus + "," + stepSubStatus + "," + dossierStatus + "," + dossierSubStatus + "," + act.getPreCondition() + "," + flagCheck);
if (stepStatus.contentEquals(dossierStatus)
&& StringUtil.containsIgnoreCase(stepSubStatus, dossierSubStatus)
&& flagCheck) {
if (Validator.isNotNull(act.getPreCondition()) && DossierMgtUtils.checkPreCondition(act.getPreCondition().split(StringPool.COMMA), dossier, systemUser)) {
action = act;
break;
}
else if (Validator.isNull(act.getPreCondition())) {
action = act;
break;
}
}
}
}
} catch (Exception e) {
_log.debug(e);
}
return action;
}
private JSONObject getFileAttachMailForApplicant (Dossier dossier, ProcessAction proAction) {
// processAction
// returnDossierFile
JSONObject filesAttach = JSONFactoryUtil.createJSONObject();
JSONArray files = JSONFactoryUtil.createJSONArray();
JSONArray documents = JSONFactoryUtil.createJSONArray();
JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
_log.debug("============getFileAttachMailForApplicant=================");
try {
List<String> returnFileTempNoList = ListUtil.toList(StringUtil.split(proAction.getReturnDossierFiles()));
_log.debug("==========proAction.getReturnDossierFiles()===========" + proAction.getReturnDossierFiles());
if (returnFileTempNoList.size() > 0) {
List<DossierFile> dossierFiles = dossierFileLocalService.getDossierFilesByD_DP(dossier.getDossierId(), DossierPartTerm.DOSSIER_PART_TYPE_OUTPUT);
for (DossierFile dossierFile : dossierFiles) {
// TODO: xu ly loc dossierFIle de dinh kem mail thong bao bo sung
_log.info("================DOSSIERFILE=============" + dossierFile.getFileEntryId());
if (returnFileTempNoList.indexOf(dossierFile.getFileTemplateNo()) >= 0) {
_log.debug("=============dossierFile.getFileTemplateNo()================");
FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(dossierFile.getFileEntryId());
if (fileEntry != null) {
jsonObject = JSONFactoryUtil.createJSONObject();
jsonObject.put("name", fileEntry.getFileName());
jsonObject.put("url", "documents/" + fileEntry.getGroupId() + StringPool.FORWARD_SLASH + fileEntry.getFolderId() + StringPool.FORWARD_SLASH + fileEntry.getTitle());
files.put(jsonObject);
}
}
}
List<DossierDocument> dossierDocuments = DossierDocumentLocalServiceUtil.getDossierDocumentList(dossier.getDossierId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS);
for (DossierDocument dossierDocument : dossierDocuments) {
// TODO: xu ly loc dossierDocument de dinh kem mail thong bao bo sung
_log.info("================dossierDocument=============" + dossierDocument.getDocumentFileId());
if (returnFileTempNoList.indexOf(dossierDocument.getDocumentType()) >= 0) {
_log.info("================dossierDocument.getDocumentType()=============");
FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(dossierDocument.getDocumentFileId());
if (fileEntry != null) {
jsonObject = JSONFactoryUtil.createJSONObject();
jsonObject.put("name", fileEntry.getFileName());
jsonObject.put("url", "documents/" + fileEntry.getGroupId() + StringPool.FORWARD_SLASH + fileEntry.getFolderId() + StringPool.FORWARD_SLASH + fileEntry.getTitle());
documents.put(jsonObject);
}
}
}
}
}
catch (Exception e) {
_log.error(e);
e.printStackTrace();
}
filesAttach.put("dossierFiles", files);
filesAttach.put("dossierDocuments", documents);
return filesAttach;
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public Dossier eparPublish(long groupId, Company company,
User user, ServiceContext serviceContext, long id, org.opencps.dossiermgt.input.model.DossierPublishModel input) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
// String referenceUid = input.getReferenceUid();
int counter = 0;
String serviceCode = input.getServiceCode();
String serviceName = input.getServiceName();
String govAgencyCode = input.getGovAgencyCode();
String govAgencyName = input.getGovAgencyName();
String applicantName = input.getApplicantName();
String applicantType = input.getApplicantIdType();
String applicantIdNo = input.getApplicantIdNo();
String applicantIdDate = input.getApplicantIdDate();
String address = input.getAddress();
String cityCode = input.getCityCode();
String cityName = input.getCityName();
String districtCode = input.getDistrictCode();
String districtName = input.getDistrictName();
String wardCode = input.getWardCode();
String wardName = input.getWardName();
String contactName = input.getContactName();
String contactTelNo = input.getContactTelNo();
String contactEmail = input.getContactEmail();
String dossierTemplateNo = input.getDossierTemplateNo();
String password = input.getPassword();
String online = input.getOnline();
String applicantNote = input.getApplicantNote();
int originality = 0;
long createDateLong = GetterUtil.getLong(input.getCreateDate());
long modifiedDateLong = GetterUtil.getLong(input.getModifiedDate());
long submitDateLong = GetterUtil.getLong(input.getSubmitDate());
long receiveDateLong = GetterUtil.getLong(input.getReceiveDate());
long dueDateLong = GetterUtil.getLong(input.getDueDate());
long releaseDateLong = GetterUtil.getLong(input.getReleaseDate());
long finishDateLong = GetterUtil.getLong(input.getFinishDate());
long cancellingDateLong = GetterUtil.getLong(input.getCancellingDate());
long correcttingDateLong = GetterUtil.getLong(input.getCorrecttingDate());
long endorsementDateLong = GetterUtil.getLong(input.getEndorsementDate());
long extendDateLong = GetterUtil.getLong(input.getExtendDate());
long processDateLong = GetterUtil.getLong(input.getProcessDate());
String submissionNote = input.getSubmissionNote();
String lockState = input.getLockState();
Dossier oldDossier = null;
oldDossier = DossierLocalServiceUtil.fetchDossier(id);
if (oldDossier != null && oldDossier.getOriginality() == DossierTerm.ORIGINALITY_DVCTT) {
Date appIdDate = null;
SimpleDateFormat sdf = new SimpleDateFormat(APIDateTimeUtils._NORMAL_DATE);
try {
appIdDate = sdf.parse(applicantIdDate);
} catch (Exception e) {
_log.debug(e);
}
Dossier dossier = dossierLocalService.eparPublishDossier(groupId, 0l, oldDossier.getReferenceUid(), counter, serviceCode, serviceName,
govAgencyCode, govAgencyName, applicantName, applicantType, applicantIdNo, appIdDate, address,
cityCode, cityName, districtCode, districtName, wardCode, wardName, contactName, contactTelNo,
contactEmail, dossierTemplateNo, password, 0, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK,
StringPool.BLANK, Boolean.valueOf(online), false, applicantNote, originality,
createDateLong != 0 ? new Date(createDateLong) : null,
modifiedDateLong != 0 ? new Date(modifiedDateLong) : null,
submitDateLong != 0 ? new Date(submitDateLong) : null,
receiveDateLong != 0 ? new Date(receiveDateLong) : null,
dueDateLong != 0 ? new Date(dueDateLong) : null,
releaseDateLong != 0 ? new Date(releaseDateLong) : null,
finishDateLong != 0 ? new Date(finishDateLong) : null,
cancellingDateLong != 0 ? new Date(cancellingDateLong) : null,
correcttingDateLong != 0 ? new Date(correcttingDateLong) : null,
endorsementDateLong != 0 ? new Date(endorsementDateLong) : null,
extendDateLong != 0 ? new Date(extendDateLong) : null,
processDateLong != 0 ? new Date(processDateLong) : null, input.getDossierNo(),
input.getDossierStatus(), input.getDossierStatusText(), input.getDossierSubStatus(),
input.getDossierSubStatusText(),
input.getDossierActionId() != null ? input.getDossierActionId() : 0, submissionNote, lockState,
input.getDelegateName(), input.getDelegateIdNo(), input.getDelegateTelNo(),
input.getDelegateEmail(), input.getDelegateAddress(), input.getDelegateCityCode(),
input.getDelegateCityName(), input.getDelegateDistrictCode(), input.getDelegateDistrictName(),
input.getDelegateWardCode(), input.getDelegateWardName(), input.getDurationCount(),
input.getDurationUnit(), input.getDossierName(), input.getProcessNo(), input.getMetaData(), serviceContext);
return dossier;
}
return oldDossier;
}
private Dossier setDossierNoNDueDate(Dossier dossier, ServiceProcess serviceProcess, ProcessOption option,
boolean setDossierNo, boolean setDueDate, Date dueDateStart,
LinkedHashMap<String, Object> params) {
if (setDueDate) {
Double durationCount = serviceProcess.getDurationCount();
int durationUnit = serviceProcess.getDurationUnit();
Date dueDate = null;
if (Validator.isNotNull(durationCount) && durationCount > 0 && !areEqualDouble(durationCount, 0.00d, 3)) {
// dueDate = HolidayUtils.getDueDate(now, durationCount, durationUnit,
// dossier.getGroupId());
DueDateUtils dueDateUtils = new DueDateUtils(dueDateStart, durationCount, durationUnit, dossier.getGroupId());
dueDate = dueDateUtils.getDueDate();
}
if (Validator.isNotNull(dueDate)) {
dossier.setDueDate(dueDate);
// DossierLocalServiceUtil.updateDueDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), dueDate, context);
// bResult.put(DossierTerm.DUE_DATE, true);
}
dossier.setDurationCount(durationCount);
dossier.setDurationUnit(durationUnit);
}
if (setDossierNo) {
if (dossier.getCounter() == 0 && Validator.isNotNull(dossier.getRegisterBookCode())) {
long counterCode = DossierNumberGenerator.countByRegiterBookCode(dossier.getGroupId(),
dossier.getRegisterBookCode());
dossier.setCounter(counterCode);
}
if (Validator.isNull(dossier.getDossierNo())) {
try {
String dossierRef = DossierNumberGenerator.generateDossierNumber(dossier.getGroupId(), dossier.getCompanyId(),
dossier.getDossierId(), option.getProcessOptionId(), serviceProcess.getDossierNoPattern(),
params);
dossier.setDossierNo(dossierRef.trim());
} catch (Exception e) {
_log.debug(e);
}
}
if (Validator.isNull(dossier.getDossierCounter()) && Validator.isNotNull(serviceProcess.getCounterCode())) {
ConfigCounter counterConfig = ConfigCounterLocalServiceUtil.fetchByCountrCode(dossier.getGroupId(),
serviceProcess.getCounterCode());
if (counterConfig != null) {
if (Validator.isNotNull(counterConfig.getStartCounter()) && counterConfig.getStartCounter() > 0) {
String patternCode = counterConfig.getPatternCode();
try {
_log.info("dossierId: " + dossier.getDossierId() + "| option.getProcessOptionId(): "
+ option.getProcessOptionId() + "| serviceProcess.getCounterCode(): "
+ serviceProcess.getCounterCode() + "| getStartCounter(): "
+ counterConfig.getStartCounter());
String dossierCounter = ConfigCounterNumberGenerator.generateCounterNumber(dossier.getGroupId(),
dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(),
patternCode, counterConfig, params);
dossier.setDossierCounter(dossierCounter.trim());
_log.info("dossierCounter: " + dossierCounter);
} catch (Exception e) {
_log.debug(e);
}
} else {
String patternCode = counterConfig.getPatternCode();
try {
_log.info("dossierId: " + dossier.getDossierId() + "| option.getProcessOptionId(): "
+ option.getProcessOptionId() + "| serviceProcess.getCounterCode(): "
+ serviceProcess.getCounterCode());
String dossierCounter = ConfigCounterNumberGenerator.generateCounterNumber(dossier.getGroupId(),
dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(),
patternCode, counterConfig, params);
dossier.setDossierCounter(dossierCounter.trim());
_log.info("dossierCounter: " + dossierCounter);
} catch (Exception e) {
_log.debug(e);
}
}
}
}
}
return dossier;
}
private static Log _log = LogFactoryUtil.getLog(CPSDossierBusinessLocalServiceImpl.class);
}
|
modules/backend-dossiermgt/backend-dossiermgt-service/src/main/java/org/opencps/dossiermgt/service/impl/CPSDossierBusinessLocalServiceImpl.java
|
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* 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.
*/
package org.opencps.dossiermgt.service.impl;
import com.liferay.counter.kernel.service.CounterLocalServiceUtil;
import com.liferay.document.library.kernel.service.DLAppLocalServiceUtil;
import com.liferay.petra.string.StringPool;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.exception.NoSuchUserException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageBusUtil;
import com.liferay.portal.kernel.model.Company;
import com.liferay.portal.kernel.model.Role;
import com.liferay.portal.kernel.model.User;
import com.liferay.portal.kernel.repository.model.FileEntry;
import com.liferay.portal.kernel.search.Field;
import com.liferay.portal.kernel.search.SearchException;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.service.SubscriptionLocalServiceUtil;
import com.liferay.portal.kernel.service.UserLocalServiceUtil;
import com.liferay.portal.kernel.servlet.HttpMethods;
import com.liferay.portal.kernel.transaction.Isolation;
import com.liferay.portal.kernel.transaction.Propagation;
import com.liferay.portal.kernel.transaction.Transactional;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ListUtil;
import com.liferay.portal.kernel.util.LocaleUtil;
import com.liferay.portal.kernel.util.PwdGenerator;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.uuid.PortalUUIDUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.activation.DataHandler;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.opencps.adminconfig.model.DynamicReport;
import org.opencps.adminconfig.service.DynamicReportLocalServiceUtil;
import org.opencps.auth.api.BackendAuth;
import org.opencps.auth.api.BackendAuthImpl;
import org.opencps.auth.api.exception.UnauthenticationException;
import org.opencps.auth.api.keys.NotificationType;
import org.opencps.auth.utils.APIDateTimeUtils;
import org.opencps.cache.actions.CacheActions;
import org.opencps.cache.actions.impl.CacheActionsImpl;
import org.opencps.communication.constants.NotificationTemplateTerm;
import org.opencps.communication.model.NotificationQueue;
import org.opencps.communication.model.Notificationtemplate;
import org.opencps.communication.model.ServerConfig;
import org.opencps.communication.service.NotificationQueueLocalServiceUtil;
import org.opencps.communication.service.NotificationtemplateLocalServiceUtil;
import org.opencps.communication.service.ServerConfigLocalServiceUtil;
import org.opencps.datamgt.model.DictCollection;
import org.opencps.datamgt.model.DictItem;
import org.opencps.datamgt.service.DictCollectionLocalServiceUtil;
import org.opencps.datamgt.service.DictItemLocalServiceUtil;
import org.opencps.datamgt.util.BetimeUtils;
import org.opencps.datamgt.util.DueDatePhaseUtil;
import org.opencps.datamgt.util.DueDateUtils;
import org.opencps.dossiermgt.action.DossierActions;
import org.opencps.dossiermgt.action.DossierUserActions;
import org.opencps.dossiermgt.action.impl.DVCQGIntegrationActionImpl;
import org.opencps.dossiermgt.action.impl.DossierActionsImpl;
import org.opencps.dossiermgt.action.impl.DossierPermission;
import org.opencps.dossiermgt.action.impl.DossierUserActionsImpl;
import org.opencps.dossiermgt.action.util.AutoFillFormData;
import org.opencps.dossiermgt.action.util.ConfigCounterNumberGenerator;
import org.opencps.dossiermgt.action.util.ConstantUtils;
import org.opencps.dossiermgt.action.util.DocumentTypeNumberGenerator;
import org.opencps.dossiermgt.action.util.DossierActionUtils;
import org.opencps.dossiermgt.action.util.DossierMgtUtils;
import org.opencps.dossiermgt.action.util.DossierNumberGenerator;
import org.opencps.dossiermgt.action.util.DossierPaymentUtils;
import org.opencps.dossiermgt.action.util.KeyPay;
import org.opencps.dossiermgt.action.util.NotificationUtil;
import org.opencps.dossiermgt.action.util.OpenCPSConfigUtil;
import org.opencps.dossiermgt.action.util.PaymentUrlGenerator;
import org.opencps.dossiermgt.action.util.ReadFilePropertiesUtils;
import org.opencps.dossiermgt.constants.ActionConfigTerm;
import org.opencps.dossiermgt.constants.CInvoiceTerm;
import org.opencps.dossiermgt.constants.CacheTerm;
import org.opencps.dossiermgt.constants.DossierActionTerm;
import org.opencps.dossiermgt.constants.DossierActionUserTerm;
import org.opencps.dossiermgt.constants.DossierDocumentTerm;
import org.opencps.dossiermgt.constants.DossierFileTerm;
import org.opencps.dossiermgt.constants.DossierPartTerm;
import org.opencps.dossiermgt.constants.DossierSyncTerm;
import org.opencps.dossiermgt.constants.DossierTerm;
import org.opencps.dossiermgt.constants.KeyPayTerm;
import org.opencps.dossiermgt.constants.NotarizationTerm;
import org.opencps.dossiermgt.constants.PaymentFileTerm;
import org.opencps.dossiermgt.constants.ProcessActionTerm;
import org.opencps.dossiermgt.constants.PublishQueueTerm;
import org.opencps.dossiermgt.constants.ServerConfigTerm;
import org.opencps.dossiermgt.constants.ServiceInfoTerm;
import org.opencps.dossiermgt.constants.StepConfigTerm;
import org.opencps.dossiermgt.constants.VTPayTerm;
import org.opencps.dossiermgt.constants.VnpostCollectionTerm;
import org.opencps.dossiermgt.exception.DataConflictException;
import org.opencps.dossiermgt.exception.NoSuchDossierUserException;
import org.opencps.dossiermgt.exception.NoSuchPaymentFileException;
import org.opencps.dossiermgt.input.model.DossierInputModel;
import org.opencps.dossiermgt.input.model.DossierMultipleInputModel;
import org.opencps.dossiermgt.input.model.PaymentFileInputModel;
import org.opencps.dossiermgt.model.ActionConfig;
import org.opencps.dossiermgt.model.ConfigCounter;
import org.opencps.dossiermgt.model.Deliverable;
import org.opencps.dossiermgt.model.DocumentType;
import org.opencps.dossiermgt.model.Dossier;
import org.opencps.dossiermgt.model.DossierAction;
import org.opencps.dossiermgt.model.DossierActionUser;
import org.opencps.dossiermgt.model.DossierDocument;
import org.opencps.dossiermgt.model.DossierFile;
import org.opencps.dossiermgt.model.DossierMark;
import org.opencps.dossiermgt.model.DossierPart;
import org.opencps.dossiermgt.model.DossierTemplate;
import org.opencps.dossiermgt.model.DossierUser;
import org.opencps.dossiermgt.model.Notarization;
import org.opencps.dossiermgt.model.PaymentConfig;
import org.opencps.dossiermgt.model.PaymentFile;
import org.opencps.dossiermgt.model.ProcessAction;
import org.opencps.dossiermgt.model.ProcessOption;
import org.opencps.dossiermgt.model.ProcessSequence;
import org.opencps.dossiermgt.model.ProcessStep;
import org.opencps.dossiermgt.model.ProcessStepRole;
import org.opencps.dossiermgt.model.PublishQueue;
import org.opencps.dossiermgt.model.ServiceConfig;
import org.opencps.dossiermgt.model.ServiceInfo;
import org.opencps.dossiermgt.model.ServiceProcess;
import org.opencps.dossiermgt.model.ServiceProcessRole;
import org.opencps.dossiermgt.model.StepConfig;
import org.opencps.dossiermgt.rest.utils.ExecuteOneActionTerm;
import org.opencps.dossiermgt.rest.utils.SyncServerTerm;
import org.opencps.dossiermgt.scheduler.InvokeREST;
import org.opencps.dossiermgt.scheduler.RESTFulConfiguration;
import org.opencps.dossiermgt.service.ActionConfigLocalServiceUtil;
import org.opencps.dossiermgt.service.ConfigCounterLocalServiceUtil;
import org.opencps.dossiermgt.service.DocumentTypeLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierActionLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierActionUserLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierDocumentLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierFileLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierMarkLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierPartLocalServiceUtil;
import org.opencps.dossiermgt.service.NotarizationLocalServiceUtil;
import org.opencps.dossiermgt.service.PaymentFileLocalServiceUtil;
import org.opencps.dossiermgt.service.ProcessActionLocalServiceUtil;
import org.opencps.dossiermgt.service.ProcessSequenceLocalServiceUtil;
import org.opencps.dossiermgt.service.ProcessStepLocalServiceUtil;
import org.opencps.dossiermgt.service.PublishQueueLocalServiceUtil;
import org.opencps.dossiermgt.service.ServiceInfoLocalServiceUtil;
import org.opencps.dossiermgt.service.ServiceProcessLocalServiceUtil;
import org.opencps.dossiermgt.service.StepConfigLocalServiceUtil;
import org.opencps.dossiermgt.service.base.CPSDossierBusinessLocalServiceBaseImpl;
import org.opencps.dossiermgt.service.persistence.DossierActionUserPK;
import org.opencps.dossiermgt.service.persistence.DossierUserPK;
import org.opencps.dossiermgt.service.persistence.ServiceProcessRolePK;
import org.opencps.usermgt.constants.ApplicantDataTerm;
import org.opencps.usermgt.constants.ApplicantTerm;
import org.opencps.usermgt.model.Applicant;
import org.opencps.usermgt.model.Employee;
import org.opencps.usermgt.model.EmployeeJobPos;
import org.opencps.usermgt.model.FileItem;
import org.opencps.usermgt.model.JobPos;
import org.opencps.usermgt.model.WorkingUnit;
import org.opencps.usermgt.service.ApplicantDataLocalServiceUtil;
import org.opencps.usermgt.service.ApplicantLocalServiceUtil;
import org.opencps.usermgt.service.EmployeeJobPosLocalServiceUtil;
import org.opencps.usermgt.service.EmployeeLocalServiceUtil;
import org.opencps.usermgt.service.FileItemLocalServiceUtil;
import org.opencps.usermgt.service.JobPosLocalServiceUtil;
import org.opencps.usermgt.service.WorkingUnitLocalServiceUtil;
import backend.auth.api.exception.NotFoundException;
/**
* The implementation of the cps dossier business local service.
*
* <p>
* All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {@link org.opencps.dossiermgt.service.CPSDossierBusinessLocalService} interface.
*
* <p>
* This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM.
* </p>
*
* @author huymq
* @see CPSDossierBusinessLocalServiceBaseImpl
* @see org.opencps.dossiermgt.service.CPSDossierBusinessLocalServiceUtil
*/
@Transactional(isolation = Isolation.PORTAL, rollbackFor = {
PortalException.class, SystemException.class
})
public class CPSDossierBusinessLocalServiceImpl
extends CPSDossierBusinessLocalServiceBaseImpl {
/*
* NOTE FOR DEVELOPERS:
*
* Never reference this class directly. Always use {@link org.opencps.dossiermgt.service.CPSDossierBusinessLocalServiceUtil} to access the cps dossier business local service.
*/
private static final String BN_TELEPHONE = "BN_telephone";
private static final String BN_ADDRESS = "BN_address";
private static final String BN_EMAIL = "BN_email";
public static final String DOSSIER_SATUS_DC_CODE = "DOSSIER_STATUS";
public static final String DOSSIER_SUB_SATUS_DC_CODE = "DOSSIER_SUB_STATUS";
public static final String DEFAULT_DATE_FORMAT = "dd/MM/yyyy";
public static final String PAYLOAD_KEY_COMPLEMENT_DATE = "complementDate";
public static final String PAYLOAD_KEY_dOSSIER_DOCUMENT = "dossierDocument";
public static final String CACHE_NOTIFICATION_TEMPLATE = "NotificationTemplate";
CacheActions cache = new CacheActionsImpl();
int ttl = OpenCPSConfigUtil.getCacheTTL();
private Dossier createCrossDossier(long groupId, ProcessAction proAction, ProcessStep curStep, DossierAction previousAction, Employee employee, Dossier dossier, User user,
JSONObject payloadObj,
ServiceContext context)
throws PortalException {
if (Validator.isNotNull(proAction.getCreateDossiers())) {
//Create new HSLT
String GOVERNMENT_AGENCY = ReadFilePropertiesUtils.get(ConstantUtils.GOVERNMENT_AGENCY);
String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, proAction.getCreateDossiers());
String createDossiers = proAction.getCreateDossiers();
String govAgencyCode = StringPool.BLANK;
String serviceCode = dossier.getServiceCode();
String dossierTemplateNo = dossier.getDossierTemplateNo();
if (createDossiers.contains(StringPool.POUND)) {
String[] splitCDs = createDossiers.split(StringPool.POUND);
if (splitCDs.length == 2) {
govAgencyCode = splitCDs[0];
if (splitCDs[1].contains(StringPool.AT)) {
if (splitCDs[1].split(StringPool.AT).length != 2) {
throw new PortalException(ReadFilePropertiesUtils.get(ConstantUtils.MSG_ERROR));
}
else {
dossierTemplateNo = splitCDs[1].split(StringPool.AT)[0];
serviceCode = splitCDs[1].split(StringPool.AT)[1];
}
}
else {
govAgencyCode = splitCDs[0];
dossierTemplateNo = splitCDs[1];
}
}
}
else {
if (createDossiers.contains(StringPool.AT)) {
if (createDossiers.split(StringPool.AT).length != 2) {
throw new PortalException(ReadFilePropertiesUtils.get(ConstantUtils.MSG_ERROR));
}
else {
govAgencyCode = createDossiers.split(StringPool.AT)[0];
serviceCode = createDossiers.split(StringPool.AT)[1];
}
}
else {
govAgencyCode = createDossiers;
}
}
ServiceConfig serviceConfig = serviceConfigLocalService.getBySICodeAndGAC(groupId, dossier.getServiceCode(), govAgencyCode);
if (serviceConfig != null) {
List<ProcessOption> lstOptions = processOptionLocalService.getByServiceProcessId(serviceConfig.getServiceConfigId());
//
ProcessOption foundOption = null;
if (createDossiers.contains(StringPool.POUND)) {
for (ProcessOption po : lstOptions) {
DossierTemplate dt = dossierTemplateLocalService.fetchDossierTemplate(po.getDossierTemplateId());
if (dt.getTemplateNo().equals(dossierTemplateNo)) {
foundOption = po;
break;
}
}
}
else {
if (lstOptions.size() > 0) {
foundOption = lstOptions.get(0);
}
}
if (foundOption != null) {
ServiceProcess ltProcess = serviceProcessLocalService.fetchServiceProcess(foundOption.getServiceProcessId());
DossierTemplate dossierTemplate = dossierTemplateLocalService.fetchDossierTemplate(foundOption.getDossierTemplateId());
// String delegateName = dossier.getDelegateName();
//String delegateName = dossier.getGovAgencyName();
//String delegateAddress = dossier.getDelegateAddress();
//String delegateTelNo = dossier.getDelegateTelNo();
//String delegateEmail = dossier.getDelegateEmail();
//String delegateIdNo = dossier.getGovAgencyCode();
JSONObject crossDossierObj = JSONFactoryUtil.createJSONObject();
crossDossierObj.put(DossierTerm.DOSSIER_TEMPLATE_NO, dossierTemplate.getTemplateNo());
crossDossierObj.put(DossierTerm.GOV_AGENCY_CODE, govAgencyCode);
crossDossierObj.put(DossierTerm.SERVICE_CODE, serviceCode);
payloadObj.put(DossierTerm.CROSS_DOSSIER, crossDossierObj);
Dossier oldHslt = DossierLocalServiceUtil.getByG_AN_SC_GAC_DTNO_ODID(groupId, dossier.getApplicantIdNo(), dossier.getServiceCode(), govAgencyCode, dossierTemplate.getTemplateNo(), dossier.getDossierId());
Dossier hsltDossier = null;
if (oldHslt != null) {
if (oldHslt.getOriginality() < 0) {
oldHslt.setOriginality(-oldHslt.getOriginality());
}
hsltDossier = oldHslt;
}
if (hsltDossier == null) {
hsltDossier = dossierLocalService.initDossier(groupId, 0l, UUID.randomUUID().toString(),
dossier.getCounter(), dossier.getServiceCode(),
dossier.getServiceName(), govAgencyCode, govAgencyName, dossier.getApplicantName(),
dossier.getApplicantIdType(), dossier.getApplicantIdNo(), dossier.getApplicantIdDate(),
dossier.getAddress(), dossier.getCityCode(), dossier.getCityName(), dossier.getDistrictCode(),
dossier.getDistrictName(), dossier.getWardCode(), dossier.getWardName(), dossier.getContactName(),
dossier.getContactTelNo(), dossier.getContactEmail(), dossierTemplate.getTemplateNo(),
dossier.getPassword(), dossier.getViaPostal(), dossier.getPostalAddress(), dossier.getPostalCityCode(),
dossier.getPostalCityName(), dossier.getPostalTelNo(),
dossier.getOnline(), dossier.getNotification(), dossier.getApplicantNote(), DossierTerm.ORIGINALITY_DVCTT, context);
}
WorkingUnit wu = WorkingUnitLocalServiceUtil.fetchByF_govAgencyCode(dossier.getGroupId(), dossier.getGovAgencyCode());
String delegateName = null;
String delegateAddress = null;
String delegateTelNo = null;
String delegateEmail = null;
String delegateIdNo = null;
delegateIdNo = dossier.getGovAgencyCode();
if (wu != null) {
delegateName = wu.getName();
delegateAddress = wu.getAddress();
delegateTelNo = wu.getTelNo();
delegateEmail = wu.getEmail();
//new 3.0 comment
// delegateIdNo = wu.getGovAgencyCode();
}
else if (user != null && employee != null) {
delegateName = employee.getFullName();
delegateAddress = dossier.getGovAgencyName();
delegateTelNo = employee.getTelNo();
delegateEmail = employee.getEmail();
}
if (hsltDossier != null) {
hsltDossier.setDelegateName(delegateName != null ? delegateName : StringPool.BLANK);
hsltDossier.setDelegateAddress(delegateAddress != null ? delegateAddress : StringPool.BLANK);
hsltDossier.setDelegateTelNo(delegateTelNo != null ? delegateTelNo : StringPool.BLANK);
hsltDossier.setDelegateEmail(delegateEmail != null ? delegateEmail : StringPool.BLANK);
hsltDossier.setDelegateIdNo(delegateIdNo != null ? delegateIdNo : StringPool.BLANK);
hsltDossier.setNew(false);
hsltDossier = dossierLocalService.updateDossier(hsltDossier);
}
//
String dossierNote = StringPool.BLANK;
if (previousAction != null) {
dossierNote = previousAction.getActionNote();
if (Validator.isNotNull(dossierNote)) {
dossierNote = previousAction.getStepInstruction();
}
}
if (hsltDossier != null) {
//Set HSLT dossierId to origin dossier
hsltDossier.setOriginDossierId(dossier.getDossierId());
if (ltProcess.getServerNo().contains(StringPool.COMMA)) {
if (!serviceCode.equals(dossier.getServiceCode())) {
String serverNoProcess = ltProcess.getServerNo().split(StringPool.COMMA)[0];
hsltDossier.setServerNo(serverNoProcess + StringPool.AT + serviceCode + StringPool.COMMA + ltProcess.getServerNo().split(StringPool.COMMA)[1]);
hsltDossier = dossierLocalService.updateDossier(hsltDossier);
}
}
else {
hsltDossier.setServerNo(ltProcess.getServerNo());
}
//Update DossierName
hsltDossier.setDossierName(dossier.getDossierName());
hsltDossier.setOriginDossierNo(dossier.getDossierNo());
dossierLocalService.updateDossier(hsltDossier);
JSONObject jsonDataStatusText = getStatusText(groupId, ReadFilePropertiesUtils.get(ConstantUtils.DOSSIER_STATUS), ReadFilePropertiesUtils.get(ConstantUtils.STATUS_NEW), StringPool.BLANK);
hsltDossier = dossierLocalService.updateStatus(groupId, hsltDossier.getDossierId(), hsltDossier.getReferenceUid(),
ReadFilePropertiesUtils.get(ConstantUtils.STATUS_NEW),
jsonDataStatusText != null ? jsonDataStatusText.getString(ReadFilePropertiesUtils.get(ConstantUtils.STATUS_NEW)) : StringPool.BLANK, StringPool.BLANK,
StringPool.BLANK, StringPool.BLANK, dossierNote, context);
}
else {
return null;
}
JSONObject jsonDataStatusText = getStatusText(groupId, ReadFilePropertiesUtils.get(ConstantUtils.DOSSIER_STATUS), DossierTerm.DOSSIER_STATUS_INTEROPERATING, StringPool.BLANK);
if (curStep != null) {
dossier = dossierLocalService.updateStatus(groupId, dossier.getDossierId(),
dossier.getReferenceUid(), DossierTerm.DOSSIER_STATUS_INTEROPERATING,
jsonDataStatusText != null ? jsonDataStatusText.getString(DossierTerm.DOSSIER_STATUS_INTEROPERATING) : StringPool.BLANK, StringPool.BLANK,
StringPool.BLANK, curStep.getLockState(), dossierNote, context);
dossier.setDossierStatus(DossierTerm.DOSSIER_STATUS_INTEROPERATING);
dossier.setDossierStatusText(jsonDataStatusText != null ? jsonDataStatusText.getString(DossierTerm.DOSSIER_STATUS_INTEROPERATING) : StringPool.BLANK);
dossier.setDossierSubStatus(StringPool.BLANK);
dossier.setDossierSubStatusText(StringPool.BLANK);
if (dossier != null && !DossierTerm.PAUSE_OVERDUE_LOCK_STATE.equals(dossier.getLockState())) {
dossier.setLockState(curStep.getLockState());
}
dossier.setDossierNote(dossierNote);;
}
return hsltDossier;
}
else {
return null;
}
}
else {
return null;
}
}
else {
return null;
}
}
private void createDossierDocument(long groupId, long userId, ActionConfig actionConfig,
Dossier dossier, DossierAction dossierAction,
JSONObject payloadObject, Employee employee, User user,
ServiceContext context) throws com.liferay.portal.kernel.search.ParseException, JSONException, SearchException {
//Check if generate dossier document
ActionConfig ac = actionConfig;
if (ac != null) {
if (dossier.getOriginality() != DossierTerm.ORIGINALITY_DVCTT) {
if (Validator.isNotNull(ac.getDocumentType()) && !ac.getActionCode().startsWith(StringPool.AT)) {
//Generate document
String[] documentTypes = ac.getDocumentType().split(StringPool.COMMA);
for (String documentType : documentTypes) {
DocumentType dt = DocumentTypeLocalServiceUtil.getByTypeCode(groupId, documentType.trim());
if (dt != null) {
String documentCode = DocumentTypeNumberGenerator.generateDossierDocumentNumber(groupId,
dossier.getCompanyId(), dossier.getServiceCode(), dossier.getGovAgencyCode(),
dt.getCodePattern());
String refUid = UUID.randomUUID().toString();
if (Validator.isNotNull(dossier.getOriginDossierNo()) && dossier.getOriginDossierId() == 0) {
refUid = DossierTerm.PREFIX_UUID + refUid;
}
DossierDocument dossierDocument = DossierDocumentLocalServiceUtil.addDossierDoc(groupId,
dossier.getDossierId(), refUid, dossierAction.getDossierActionId(),
dt.getTypeCode(), dt.getDocumentName(), documentCode, 0L, dt.getDocSync(), context);
//Generate PDF
String formData = dossierAction.getPayload();
JSONObject payloadTmp = JSONFactoryUtil.createJSONObject(formData);
if (payloadTmp != null && payloadTmp.has(PAYLOAD_KEY_COMPLEMENT_DATE)) {
if (payloadTmp.getLong(PAYLOAD_KEY_COMPLEMENT_DATE) > 0) {
Timestamp ts = new Timestamp(payloadTmp.getLong(PAYLOAD_KEY_COMPLEMENT_DATE));
SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
payloadTmp.put(PAYLOAD_KEY_COMPLEMENT_DATE, format.format(ts));
}
}
JSONObject formDataObj = processMergeDossierFormData(dossier, payloadTmp);
formDataObj = processMergeDossierProcessRole(dossier, 1, formDataObj, dossierAction);
formDataObj.put(ConstantUtils.VALUE_URL, context.getPortalURL());
if (employee != null) {
formDataObj.put(Field.USER_NAME, employee.getFullName());
} else {
formDataObj.put(Field.USER_NAME, user.getFullName());
}
Message message = new Message();
// _log.info("Document script: " + dt.getDocumentScript());
JSONObject msgData = JSONFactoryUtil.createJSONObject();
msgData.put(ConstantUtils.CLASS_NAME, DossierDocument.class.getName());
msgData.put(Field.CLASS_PK, dossierDocument.getDossierDocumentId());
msgData.put(ConstantUtils.JRXML_TEMPLATE, dt.getDocumentScript());
msgData.put(ConstantUtils.FORM_DATA, formDataObj.toJSONString());
msgData.put(Field.USER_ID, userId);
message.put(ConstantUtils.MSG_ENG, msgData);
MessageBusUtil.sendMessage(ConstantUtils.JASPER_DESTINATION, message);
payloadObject.put(DossierDocumentTerm.DOSSIER_DOCUMENT_ID, dossierDocument.getDossierDocumentId());
}
}
}
}
}
}
private boolean createDossierDocumentPostAction(long groupId, long userId,
Dossier dossier, DossierAction dossierAction,
JSONObject payloadObject, Employee employee, User user, String documentTypeList,
ServiceContext context) throws com.liferay.portal.kernel.search.ParseException, JSONException, SearchException {
//Check if generate dossier document
if (dossier.getOriginality() != DossierTerm.ORIGINALITY_DVCTT) {
// Generate document
String[] documentTypes = documentTypeList.split(StringPool.COMMA);
for (String documentType : documentTypes) {
DocumentType dt = DocumentTypeLocalServiceUtil.getByTypeCode(groupId, documentType.trim());
if (dt != null) {
String documentCode = DocumentTypeNumberGenerator.generateDossierDocumentNumber(groupId,
dossier.getCompanyId(), dossier.getServiceCode(), dossier.getGovAgencyCode(),
dt.getCodePattern());
DossierDocument dossierDocument = DossierDocumentLocalServiceUtil.addDossierDoc(groupId,
dossier.getDossierId(), UUID.randomUUID().toString(), dossierAction.getDossierActionId(),
dt.getTypeCode(), dt.getDocumentName(), documentCode, 0L, dt.getDocSync(), context);
// Generate PDF
String formData = dossierAction.getPayload();
JSONObject payloadTmp = JSONFactoryUtil.createJSONObject(formData);
if (payloadTmp != null && payloadTmp.has(PAYLOAD_KEY_COMPLEMENT_DATE)) {
if (payloadTmp.getLong(PAYLOAD_KEY_COMPLEMENT_DATE) > 0) {
Timestamp ts = new Timestamp(payloadTmp.getLong(PAYLOAD_KEY_COMPLEMENT_DATE));
SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
payloadTmp.put(PAYLOAD_KEY_COMPLEMENT_DATE, format.format(ts));
}
}
JSONObject formDataObj = processMergeDossierFormData(dossier, payloadTmp);
formDataObj = processMergeDossierProcessRole(dossier, 1, formDataObj, dossierAction);
formDataObj.put(ConstantUtils.VALUE_URL, context.getPortalURL());
formDataObj.put(DossierDocumentTerm.DOCUMENT_CODE, documentCode);
if (employee != null) {
formDataObj.put(Field.USER_NAME, employee.getFullName());
} else {
formDataObj.put(Field.USER_NAME, user.getFullName());
}
Message message = new Message();
// _log.info("Document script: " + dt.getDocumentScript());
JSONObject msgData = JSONFactoryUtil.createJSONObject();
msgData.put(ConstantUtils.CLASS_NAME, DossierDocument.class.getName());
msgData.put(Field.CLASS_PK, dossierDocument.getDossierDocumentId());
msgData.put(ConstantUtils.JRXML_TEMPLATE, dt.getDocumentScript());
msgData.put(ConstantUtils.FORM_DATA, formDataObj.toJSONString());
msgData.put(Field.USER_ID, userId);
message.put(ConstantUtils.MSG_ENG, msgData);
MessageBusUtil.sendMessage(ConstantUtils.JASPER_DESTINATION, message);
payloadObject.put(PAYLOAD_KEY_dOSSIER_DOCUMENT, dossierDocument.getDossierDocumentId());
}
}
}
return true;
}
private void createDossierSync(long groupId, long userId, ActionConfig actionConfig, ProcessAction proAction, DossierAction dossierAction, Dossier dossier, int syncType,
ProcessOption option,
JSONObject payloadObject, Map<String, Boolean> flagChanged,
String actionCode, String actionUser, String actionNote, ServiceProcess serviceProcess,
ServiceContext context) throws PortalException {
//Create DossierSync
String dossierRefUid = dossier.getReferenceUid();
String syncRefUid = UUID.randomUUID().toString();
if (syncType > 0) {
int state = DossierActionUtils.getSyncState(syncType, dossier);
//If state = 1 set pending dossier
if (state == DossierSyncTerm.STATE_WAITING_SYNC) {
if (dossierAction != null) {
dossierAction.setPending(true);
dossierActionLocalService.updateDossierAction(dossierAction);
}
}
else {
if (dossierAction != null) {
dossierAction.setPending(false);
dossierActionLocalService.updateDossierAction(dossierAction);
}
}
//Update payload
JSONArray dossierFilesArr = JSONFactoryUtil.createJSONArray();
List<DossierFile> lstFiles = DossierFileLocalServiceUtil.findByDID(dossier.getDossierId());
if (actionConfig.getSyncType() == DossierSyncTerm.SYNCTYPE_REQUEST) {
if (dossier.getOriginDossierId() == 0) {
if (lstFiles.size() > 0) {
for (DossierFile df : lstFiles) {
JSONObject dossierFileObj = JSONFactoryUtil.createJSONObject();
dossierFileObj.put(DossierFileTerm.REFERENCE_UID, df.getReferenceUid());
dossierFilesArr.put(dossierFileObj);
}
}
}
else {
// ServiceConfig serviceConfig = ServiceConfigLocalServiceUtil.getBySICodeAndGAC(groupId, dossier.getServiceCode(), dossier.getGovAgencyCode());
// List<ProcessOption> lstOptions = ProcessOptionLocalServiceUtil.getByServiceProcessId(serviceConfig.getServiceConfigId());
// if (serviceConfig != null) {
// if (lstOptions.size() > 0) {
// ProcessOption processOption = lstOptions.get(0);
ProcessOption processOption = option;
DossierTemplate dossierTemplate = dossierTemplateLocalService.fetchDossierTemplate(processOption.getDossierTemplateId());
List<DossierPart> lstParts = dossierPartLocalService.getByTemplateNo(groupId, dossierTemplate.getTemplateNo());
List<DossierFile> lstOriginFiles = dossierFileLocalService.findByDID(dossier.getOriginDossierId());
if (lstOriginFiles.size() > 0) {
List<String> lstCheckParts = new ArrayList<String>();
if (payloadObject.has(DossierSyncTerm.PAYLOAD_SYNC_DOSSIER_PARTS)) {
try {
JSONArray partArrs = payloadObject.getJSONArray(DossierSyncTerm.PAYLOAD_SYNC_DOSSIER_PARTS);
for (int tempI = 0; tempI <= partArrs.length(); tempI++) {
JSONObject partObj = partArrs.getJSONObject(tempI);
lstCheckParts.add(partObj.getString(DossierPartTerm.PART_NO));
}
}
catch (Exception e) {
_log.debug(e);
}
}
for (DossierFile df : lstOriginFiles) {
boolean flagHslt = false;
for (DossierPart dp : lstParts) {
if (dp.getPartNo().equals(df.getDossierPartNo())
&& (lstCheckParts.size() == 0 || (lstCheckParts.size() > 0 && lstCheckParts.contains(dp.getPartNo())))) {
flagHslt = true;
break;
}
}
if (flagHslt) {
JSONObject dossierFileObj = JSONFactoryUtil.createJSONObject();
dossierFileObj.put(DossierFileTerm.REFERENCE_UID, df.getReferenceUid());
dossierFilesArr.put(dossierFileObj);
}
}
}
// }
// }
}
}
else {
//Sync result files
if (Validator.isNotNull(dossier.getDossierNo())) {
payloadObject.put(DossierTerm.DOSSIER_NO, dossier.getDossierNo());
}
}
if (actionConfig.getSyncType() == DossierSyncTerm.SYNCTYPE_REQUEST ||
actionConfig.getSyncType() == DossierSyncTerm.SYNCTYPE_INFORM) {
payloadObject.put(DossierTerm.CONSTANT_DOSSIER_FILES, dossierFilesArr);
if (Validator.isNotNull(proAction.getReturnDossierFiles())) {
List<DossierFile> lsDossierFile = lstFiles;
dossierFilesArr = JSONFactoryUtil.createJSONArray();
// check return file
List<String> returnDossierFileTemplateNos = ListUtil
.toList(StringUtil.split(proAction.getReturnDossierFiles()));
for (DossierFile dossierFile : lsDossierFile) {
if (returnDossierFileTemplateNos.contains(dossierFile.getFileTemplateNo())) {
JSONObject dossierFileObj = JSONFactoryUtil.createJSONObject();
dossierFileObj.put(DossierFileTerm.REFERENCE_UID, dossierFile.getReferenceUid());
dossierFilesArr.put(dossierFileObj);
}
}
payloadObject.put(DossierTerm.CONSTANT_DOSSIER_FILES, dossierFilesArr);
}
List<DossierDocument> lstDossierDocuments = dossierDocumentLocalService.getDossierDocumentList(dossier.getDossierId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS);
JSONArray dossierDocumentArr = JSONFactoryUtil.createJSONArray();
for (DossierDocument dossierDocument : lstDossierDocuments) {
JSONObject dossierDocumentObj = JSONFactoryUtil.createJSONObject();
dossierDocumentObj.put(DossierDocumentTerm.REFERENCE_UID, dossierDocument.getReferenceUid());
dossierDocumentArr.put(dossierDocumentObj);
}
payloadObject.put(DossierTerm.CONSTANT_DOSSIER_FILES, dossierFilesArr);
payloadObject.put(DossierTerm.CONSTANT_DOSSIER_DOC, dossierDocumentArr);
//Put dossier note
payloadObject.put(DossierTerm.DOSSIER_NOTE, dossier.getDossierNote());
//Put dossier note
payloadObject.put(DossierTerm.SUBMIT_DATE, dossier.getSubmitDate() != null ? dossier.getSubmitDate().getTime() : 0);
// _log.info("Flag changed: " + flagChanged);
payloadObject = DossierActionUtils.buildChangedPayload(payloadObject, flagChanged, dossier);
//Always inform due date
if (actionConfig.getSyncType() == DossierSyncTerm.SYNCTYPE_INFORM && Validator.isNotNull(dossier.getDueDate())) {
payloadObject.put(DossierTerm.DUE_DATE, dossier.getDueDate().getTime());
}
if (actionConfig.getSyncType() == DossierSyncTerm.SYNCTYPE_INFORM && Validator.isNotNull(dossier.getReceiveDate())) {
payloadObject.put(DossierTerm.RECEIVE_DATE, dossier.getReceiveDate().getTime());
}
if (Validator.isNotNull(dossier.getServerNo())
&& dossier.getServerNo().split(StringPool.COMMA).length > 1) {
String serverNo = dossier.getServerNo().split(StringPool.COMMA)[0].split(StringPool.AT)[0];
dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid,
dossierAction.getPrimaryKey(), actionCode, proAction.getActionName(), actionUser, actionNote,
syncType, actionConfig.getInfoType(), payloadObject.toJSONString(), serverNo, state);
}
else {
dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid,
dossierAction.getPrimaryKey(), actionCode, proAction.getActionName(), actionUser, actionNote,
syncType, actionConfig.getInfoType(), payloadObject.toJSONString(), dossier.getServerNo(), state);
}
//Gửi thông tin hồ sơ để tra cứu
if (state == DossierSyncTerm.STATE_NOT_SYNC
&& actionConfig != null && actionConfig.getEventType() == ActionConfigTerm.EVENT_TYPE_SENT
&& OpenCPSConfigUtil.isPublishEventEnable()) {
publishEvent(dossier, context, dossierAction.getDossierActionId());
}
}
else if (actionConfig.getSyncType() == DossierSyncTerm.SYNCTYPE_INFORM_DOSSIER) {
if (Validator.isNotNull(dossier.getDossierNo())) {
payloadObject.put(DossierTerm.DOSSIER_NO, dossier.getDossierNo());
}
//
payloadObject.put("dossierFiles", dossierFilesArr);
if (Validator.isNotNull(proAction.getReturnDossierFiles())) {
List<DossierFile> lsDossierFile = lstFiles;
dossierFilesArr = JSONFactoryUtil.createJSONArray();
// check return file
List<String> returnDossierFileTemplateNos = ListUtil
.toList(StringUtil.split(proAction.getReturnDossierFiles()));
for (DossierFile dossierFile : lsDossierFile) {
if (returnDossierFileTemplateNos.contains(dossierFile.getFileTemplateNo())) {
JSONObject dossierFileObj = JSONFactoryUtil.createJSONObject();
dossierFileObj.put(DossierFileTerm.REFERENCE_UID, dossierFile.getReferenceUid());
dossierFilesArr.put(dossierFileObj);
}
}
payloadObject.put("dossierFiles", dossierFilesArr);
}
payloadObject = DossierActionUtils.buildChangedPayload(payloadObject, flagChanged, dossier);
if (Validator.isNotNull(dossier.getServerNo())
&& dossier.getServerNo().split(StringPool.COMMA).length > 1) {
String serverNo = dossier.getServerNo().split(StringPool.COMMA)[0].split(StringPool.AT)[0];
dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid,
dossierAction.getPrimaryKey(), actionCode, proAction.getActionName(), actionUser, actionNote,
syncType, actionConfig.getInfoType(), payloadObject.toJSONString(), serverNo, state);
}
else {
dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid,
dossierAction.getPrimaryKey(), actionCode, proAction.getActionName(), actionUser, actionNote,
syncType, actionConfig.getInfoType(), payloadObject.toJSONString(), dossier.getServerNo(), state);
}
}
}
else if (actionConfig != null && actionConfig.getEventType() == ActionConfigTerm.EVENT_TYPE_SENT
&& OpenCPSConfigUtil.isPublishEventEnable()) {
publishEvent(dossier, context, dossierAction.getDossierActionId());
}
}
private void doMappingAction(long groupId, long userId, Employee employee, Dossier dossier,
ActionConfig actionConfig, String actionUser, String actionNote, String payload, String assignUsers,
String payment,ServiceContext context) throws PortalException, Exception {
if (Validator.isNotNull(actionConfig) && Validator.isNotNull(actionConfig.getMappingAction())) {
ActionConfig mappingConfig = actionConfigLocalService.getByCode(groupId, actionConfig.getMappingAction());
if (dossier.getOriginDossierId() != 0) {
Dossier hslt = dossierLocalService.fetchDossier(dossier.getOriginDossierId());
ProcessOption optionHslt = getProcessOption(hslt.getServiceCode(), hslt.getGovAgencyCode(),
hslt.getDossierTemplateNo(), groupId);
ProcessAction actionHslt = getProcessAction(groupId, hslt.getDossierId(), hslt.getReferenceUid(), actionConfig.getMappingAction(), optionHslt.getServiceProcessId());
String actionUserHslt = actionUser;
if (employee != null) {
actionUserHslt = actionUser;
}
if (DossierTerm.DOSSIER_STATUS_NEW.equals(hslt.getDossierStatus())) {
Date now = new Date();
hslt.setSubmitDate(now);
hslt = dossierLocalService.updateDossier(hslt);
try {
JSONObject payloadObj = JSONFactoryUtil.createJSONObject(payload);
payloadObj.put(DossierTerm.SUBMIT_DATE, now.getTime());
payload = payloadObj.toJSONString();
}
catch (JSONException e) {
_log.debug(e);
}
}
doAction(groupId, userId, hslt, optionHslt, actionHslt, actionConfig.getMappingAction(), actionUserHslt, actionNote, payload, assignUsers, payment, mappingConfig.getSyncType(), context);
}
else {
Dossier originDossier = dossierLocalService.getByOrigin(groupId, dossier.getDossierId());
if (originDossier != null) {
ProcessOption optionOrigin = getProcessOption(originDossier.getServiceCode(), originDossier.getGovAgencyCode(),
originDossier.getDossierTemplateNo(), groupId);
ProcessAction actionOrigin = getProcessAction(groupId, originDossier.getDossierId(), originDossier.getReferenceUid(), actionConfig.getMappingAction(), optionOrigin.getServiceProcessId());
doAction(groupId, userId, originDossier, optionOrigin, actionOrigin, actionConfig.getMappingAction(), actionUser, actionNote, payload, assignUsers, payment, mappingConfig.getSyncType(), context);
}
}
}
}
private DossierAction createActionAndAssignUser(long groupId, long userId, ProcessStep curStep,
ActionConfig actionConfig, DossierAction dossierAction, DossierAction previousAction,
ProcessAction proAction, Dossier dossier, String actionCode, String actionUser, String actionNote,
String payload, String assignUsers, String payment, ServiceProcess serviceProcess, ProcessOption option,
Map<String, Boolean> flagChanged, Integer dateOption, ServiceContext context) throws PortalException {
int actionOverdue = getActionDueDate(groupId, dossier.getDossierId(), dossier.getReferenceUid(), proAction.getProcessActionId());
String actionName = proAction.getActionName();
String prevStatus = dossier.getDossierStatus();
if (curStep != null) {
String curStatus = curStep.getDossierStatus();
String curSubStatus = curStep.getDossierSubStatus();
String stepCode = curStep.getStepCode();
String stepName = curStep.getStepName();
String stepInstruction = curStep.getStepInstruction();
String sequenceNo = curStep.getSequenceNo();
JSONObject jsonDataStatusText = getStatusText(groupId, DOSSIER_SATUS_DC_CODE, curStatus, curSubStatus);
String fromStepCode = previousAction != null ? previousAction.getStepCode() : StringPool.BLANK;
String fromStepName = previousAction != null ? previousAction.getStepName() : StringPool.BLANK;
String fromSequenceNo = previousAction != null ? previousAction.getSequenceNo() : StringPool.BLANK;
int state = DossierActionTerm.STATE_WAITING_PROCESSING;
int eventStatus = (actionConfig != null ? (actionConfig.getEventType() == ActionConfigTerm.EVENT_TYPE_NOT_SENT ? DossierActionTerm.EVENT_STATUS_NOT_CREATED : DossierActionTerm.EVENT_STATUS_WAIT_SENDING) : DossierActionTerm.EVENT_STATUS_NOT_CREATED);
boolean rollbackable = false;
if (actionConfig != null) {
if (actionConfig.getRollbackable()) {
rollbackable = true;
}
else {
}
}
else {
if (proAction.isRollbackable()) {
rollbackable = true;
}
else {
}
}
dossierAction = dossierActionLocalService.updateDossierAction(groupId, 0, dossier.getDossierId(),
serviceProcess.getServiceProcessId(), dossier.getDossierActionId(),
fromStepCode, fromStepName, fromSequenceNo,
actionCode, actionUser, actionName, actionNote, actionOverdue,
stepCode, stepName,
sequenceNo,
null, 0l, payload, stepInstruction,
state, eventStatus, rollbackable,
context);
dossier.setDossierActionId(dossierAction.getDossierActionId());
String dossierNote = StringPool.BLANK;
if (dossierAction != null) {
dossierNote = dossierAction.getActionNote();
if (Validator.isNotNull(dossierNote)) {
dossierNote = dossierAction.getStepInstruction();
}
}
//Update previous action nextActionId
Date now = new Date();
if (previousAction != null && dossierAction != null) {
previousAction.setNextActionId(dossierAction.getDossierActionId());
previousAction.setState(DossierActionTerm.STATE_ALREADY_PROCESSED);
previousAction.setModifiedDate(now);
previousAction = dossierActionLocalService.updateDossierAction(previousAction);
}
updateStatus(dossier, curStatus,
jsonDataStatusText != null ? jsonDataStatusText.getString(curStatus) : StringPool.BLANK, curSubStatus,
jsonDataStatusText != null ? jsonDataStatusText.getString(curSubStatus) : StringPool.BLANK, curStep.getLockState(), dossierNote, context);
//Cập nhật cờ đồng bộ ngày tháng sang các hệ thống khác
Map<String, Boolean> resultFlagChanged = updateProcessingDate(dossierAction, previousAction, curStep,
dossier, curStatus, curSubStatus, prevStatus,
dateOption != null ? dateOption : (actionConfig != null ? actionConfig.getDateOption() : 0), option, serviceProcess, context);
for (Map.Entry<String, Boolean> entry : resultFlagChanged.entrySet()) {
flagChanged.put(entry.getKey(), entry.getValue());
}
dossierAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId());
}
//Thiết lập quyền thao tác hồ sơ
int allowAssignUser = proAction.getAllowAssignUser();
JSONArray assignedUsersArray = JSONFactoryUtil.createJSONArray(assignUsers);
if (allowAssignUser != ProcessActionTerm.NOT_ASSIGNED) {
if (Validator.isNotNull(assignUsers) && assignedUsersArray.length() > 0) {
// JSONArray assignedUsersArray = JSONFactoryUtil.createJSONArray(assignUsers);
assignDossierActionUser(dossier, allowAssignUser,
dossierAction, userId, groupId, proAction.getAssignUserId(),
assignedUsersArray);
if (OpenCPSConfigUtil.isNotificationEnable()) {
createNotificationSMS(userId, groupId, dossier, assignedUsersArray, dossierAction, context);
}
} else {
initDossierActionUser(proAction, dossier, allowAssignUser, dossierAction, userId, groupId,
proAction.getAssignUserId());
}
} else {
//Process role as step
if (curStep != null && Validator.isNotNull(curStep.getRoleAsStep())) {
copyRoleAsStep(curStep, dossier);
}
else {
initDossierActionUser(proAction, dossier, allowAssignUser, dossierAction, userId, groupId,
proAction.getAssignUserId());
}
}
return dossierAction;
}
public static final String CACHE_ServiceProcess = "ServiceProcess";
public static final String CREATE_DOCUMENT = "CREATE_DOCUMENT";
public static final String CHANGE_DATE = "CHANGE_DATE";
public static final String CALL_API = "CALL_API";
private DossierAction doActionInsideProcess(long groupId, long userId, Dossier dossier, ActionConfig actionConfig, ProcessOption option, ProcessAction proAction,
String actionCode, String actionUser, String actionNote, String payload, String assignUsers,
String payment,
int syncType,
ServiceContext context) throws PortalException, SystemException, Exception {
context.setUserId(userId);
DossierAction dossierAction = null;
Map<String, Boolean> flagChanged = new HashMap<>();
JSONObject payloadObject = JSONFactoryUtil.createJSONObject();
User user = userLocalService.fetchUser(userId);
String dossierStatus = dossier.getDossierStatus().toLowerCase();
Employee employee = null;
Serializable employeeCache = cache.getFromCache(CacheTerm.MASTER_DATA_EMPLOYEE, groupId +StringPool.UNDERLINE+ userId);
// _log.info("EMPLOYEE CACHE: " + employeeCache);
if (employeeCache == null) {
employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId);
if (employee != null) {
cache.addToCache(CacheTerm.MASTER_DATA_EMPLOYEE,
groupId + StringPool.UNDERLINE + userId, (Serializable) employee,
ttl);
}
} else {
employee = (Employee) employeeCache;
}
try {
payloadObject = JSONFactoryUtil.createJSONObject(payload);
}
catch (JSONException e) {
_log.debug(e);
}
if (Validator.isNotNull(dossierStatus)) {
if(!ReadFilePropertiesUtils.get(ConstantUtils.STATUS_NEW).equals(dossierStatus)) {
} else if (dossier.getOriginality() == DossierTerm.ORIGINALITY_DVCTT) {
dossier.setSubmitDate(new Date());
}
}
long dossierId = dossier.getDossierId();
ServiceProcess serviceProcess = null;
DossierAction previousAction = null;
if (dossier.getDossierActionId() != 0) {
previousAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId());
}
//Cập nhật thông tin hồ sơ dựa vào payload truyền vào khi thực hiện thao tác
if (Validator.isNotNull(payload)) {
JSONObject pl = payloadObject;
updateDossierPayload(dossier, pl);
}
if ((option != null || previousAction != null) && proAction != null) {
long serviceProcessId = (option != null ? option.getServiceProcessId() : previousAction.getServiceProcessId());
Serializable serviceProcessCache = cache.getFromCache(CACHE_ServiceProcess, groupId +StringPool.UNDERLINE+ serviceProcessId);
if (serviceProcessCache == null) {
serviceProcess = serviceProcessLocalService.fetchServiceProcess(serviceProcessId);
if (serviceProcess != null) {
cache.addToCache(CACHE_ServiceProcess,
groupId +StringPool.UNDERLINE+ serviceProcessId, (Serializable) serviceProcess,
ttl);
}
} else {
serviceProcess = (ServiceProcess) serviceProcessCache;
}
String paymentFee = StringPool.BLANK;
String postStepCode = proAction.getPostStepCode();
String postAction = proAction.getPostAction();
boolean flagDocument = false;
Integer dateOption = null;
String documentTypeList = StringPool.BLANK;
if (Validator.isNotNull(postAction)) {
JSONObject jsonPostData = JSONFactoryUtil.createJSONObject(postAction);
if (jsonPostData != null) {
JSONObject jsonDocument = JSONFactoryUtil.createJSONObject(jsonPostData.getString(CREATE_DOCUMENT));
if (jsonDocument != null && jsonDocument.has(DossierDocumentTerm.DOCUMENT_TYPE)) {
documentTypeList = jsonDocument.getString(DossierDocumentTerm.DOCUMENT_TYPE);
flagDocument = true;
}
JSONObject jsonChangeDate = JSONFactoryUtil.createJSONObject(jsonPostData.getString(CHANGE_DATE));
if (jsonChangeDate != null && jsonChangeDate.has(DossierTerm.DATE_OPTION)) {
String strDateOption = jsonChangeDate.getString(DossierTerm.DATE_OPTION);
if (Validator.isNotNull(strDateOption)) {
dateOption = Integer.valueOf(strDateOption);
}
}
JSONObject jsonCallAPI = JSONFactoryUtil.createJSONObject(jsonPostData.getString(CALL_API));
if (jsonCallAPI != null && jsonCallAPI.has(DossierTerm.SERVER_NO)) {
String serverNo = jsonCallAPI.getString(DossierTerm.SERVER_NO);
if (Validator.isNotNull(serverNo)) {
ServerConfig serverConfig = ServerConfigLocalServiceUtil.getByCode(groupId, serverNo);
if (serverConfig != null) {
JSONObject configObj = JSONFactoryUtil.createJSONObject(serverConfig.getConfigs());
//
String method = StringPool.BLANK;
if (configObj != null && configObj.has(KeyPayTerm.METHOD)) {
method = configObj.getString(KeyPayTerm.METHOD);
System.out.println("method: "+method);
}
//params
JSONObject jsonParams = null;
if (configObj != null && configObj.has(KeyPayTerm.PARAMS)) {
jsonParams = JSONFactoryUtil.createJSONObject(configObj.getString(KeyPayTerm.PARAMS));
}
if (jsonParams != null) {
JSONObject jsonHeader = JSONFactoryUtil.createJSONObject(jsonParams.getString(KeyPayTerm.HEADER));
JSONObject jsonBody = JSONFactoryUtil.createJSONObject(jsonParams.getString(KeyPayTerm.BODY));
String authStrEnc = StringPool.BLANK;
String apiUrl = StringPool.BLANK;
StringBuilder sb = new StringBuilder();
try {
URL urlVal = null;
String groupIdRequest = StringPool.BLANK;
StringBuilder postData = new StringBuilder();
Iterator<?> keys = jsonBody.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (!StringPool.BLANK.equals(postData.toString())) {
postData.append(StringPool.AMPERSAND);
}
postData.append(key);
postData.append(StringPool.EQUAL);
postData.append(jsonBody.get(key));
}
if (configObj.has(SyncServerTerm.SERVER_USERNAME)
&& configObj.has(SyncServerTerm.SERVER_SECRET)
&& Validator.isNotNull(configObj.getString(SyncServerTerm.SERVER_USERNAME))
&& Validator.isNotNull(configObj.getString(SyncServerTerm.SERVER_SECRET))) {
authStrEnc = Base64.getEncoder()
.encodeToString((configObj.getString(SyncServerTerm.SERVER_USERNAME)
+ StringPool.COLON + configObj.getString(SyncServerTerm.SERVER_SECRET))
.getBytes());
}
if (configObj.has(SyncServerTerm.SERVER_URL)) {
apiUrl = configObj.getString(SyncServerTerm.SERVER_URL);
if (apiUrl.contains("{_dossierId}")) {
apiUrl = apiUrl.replace("{_dossierId}", String.valueOf(dossierId));
}
if (apiUrl.contains("{_dossierCounter}")) {
apiUrl = apiUrl.replace("{_dossierCounter}", String.valueOf(dossier.getDossierCounter()));
}
}
if (configObj.has(SyncServerTerm.SERVER_GROUP_ID)) {
groupIdRequest = configObj.getString(SyncServerTerm.SERVER_GROUP_ID);
}
if (jsonHeader != null && Validator.isNotNull(groupIdRequest)) {
if (jsonHeader.has(Field.GROUP_ID)) {
groupIdRequest = String.valueOf(jsonHeader.getLong(Field.GROUP_ID));
}
}
if (HttpMethods.GET.equals(method)) {
if (Validator.isNotNull(postData.toString())) {
urlVal = new URL(apiUrl + StringPool.QUESTION + postData.toString());
} else {
urlVal = new URL(apiUrl);
}
} else {
urlVal = new URL(apiUrl);
}
_log.debug("API URL: " + apiUrl);
java.net.HttpURLConnection conn = (java.net.HttpURLConnection) urlVal
.openConnection();
conn.setRequestProperty(Field.GROUP_ID, groupIdRequest);
conn.setRequestMethod(method);
conn.setRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
if (Validator.isNotNull(authStrEnc)) {
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, "Basic " + authStrEnc);
}
if (HttpMethods.POST.equals(method) || HttpMethods.PUT.equals(method)) {
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
conn.setRequestProperty(HttpHeaders.CONTENT_LENGTH,
StringPool.BLANK + Integer.toString(postData.toString().getBytes().length));
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
_log.debug("POST DATA: " + postData.toString());
OutputStream os = conn.getOutputStream();
os.write(postData.toString().getBytes());
os.close();
}
BufferedReader brf = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
int cp;
while ((cp = brf.read()) != -1) {
sb.append((char) cp);
}
_log.debug("RESULT PROXY: " + sb.toString());
} catch (IOException e) {
_log.debug(e);
// _log.debug("Something went wrong while reading/writing in stream!!");
}
}
}
}
}
}
}
//Xử lý phiếu thanh toán
processPaymentFile(groupId, userId, payment, option, proAction, previousAction, dossier, context);
//Bước sau không có thì mặc định quay lại bước trước đó
if (Validator.isNull(postStepCode)) {
postStepCode = previousAction.getFromStepCode();
ProcessStep backCurStep = processStepLocalService.fetchBySC_GID(postStepCode, groupId, serviceProcessId);
String curStatus = backCurStep.getDossierStatus();
String curSubStatus = backCurStep.getDossierSubStatus();
JSONObject jsonDataStatusText = getStatusText(groupId, ReadFilePropertiesUtils.get(ConstantUtils.DOSSIER_STATUS), curStatus, curSubStatus);
//update dossierStatus
dossier = DossierLocalServiceUtil.updateStatus(groupId, dossierId, dossier.getReferenceUid(), curStatus,
jsonDataStatusText != null ? jsonDataStatusText.getString(curStatus) : StringPool.BLANK, curSubStatus,
jsonDataStatusText != null ? jsonDataStatusText.getString(curSubStatus) : StringPool.BLANK, backCurStep.getLockState(), dossier.getDossierNote(), context);
dossier.setDossierActionId(previousAction.getPreviousActionId());
dossierLocalService.updateDossier(dossier);
// chỉ cán bộ thao tác trước đó có moderator = 1
List<DossierActionUser> lstDaus =
DossierActionUserLocalServiceUtil.getByDossierAndStepCode(
dossier.getDossierId(), previousAction.getStepCode());
for (DossierActionUser dau : lstDaus) {
if (dau.getUserId() == backCurStep.getUserId()) {
dau.setModerator(1);
} else {
dau.setModerator(0);
}
DossierActionUserLocalServiceUtil.updateDossierActionUser(dau);
}
return previousAction;
}
ProcessStep curStep = processStepLocalService.fetchBySC_GID(postStepCode, groupId, serviceProcessId);
//Kiểm tra cấu hình cần tạo hồ sơ liên thông
Dossier hsltDossier = createCrossDossier(groupId, proAction, curStep, previousAction, employee, dossier, user, payloadObject, context);
if (Validator.isNotNull(proAction.getCreateDossiers())) {
if (Validator.isNull(hsltDossier)) {
return null;
}
}
//Cập nhật hành động và quyền người dùng với hồ sơ
dossierAction = createActionAndAssignUser(groupId, userId, curStep, actionConfig, dossierAction,
previousAction, proAction, dossier, actionCode, actionUser, actionNote, payload, assignUsers,
paymentFee, serviceProcess, option, flagChanged, dateOption, context);
// dossier = dossierLocalService.updateDossier(dossier);
//Tạo văn bản đính kèm
if (OpenCPSConfigUtil.isDossierDocumentEnable()) {
if (!flagDocument) {
createDossierDocument(groupId, userId, actionConfig, dossier, dossierAction, payloadObject, employee, user, context);
} else {
createDossierDocumentPostAction(groupId, userId, dossier, dossierAction,
payloadObject, employee, user, documentTypeList, context);
}
}
//Kiểm tra xem có gửi dịch vụ vận chuyển hay không
if (proAction.getPreCondition().toLowerCase().contains(ProcessActionTerm.PRECONDITION_SEND_VIAPOSTAL)) {
vnpostEvent(dossier, dossierAction.getDossierActionId());
}
if (proAction.getPreCondition().toLowerCase().contains(ProcessActionTerm.PRECONDITION_SEND_COLLECTION_VNPOST)) {
collectVnpostEvent(dossier, dossierAction.getDossierActionId());
}
if (proAction.getPreCondition().toLowerCase().contains(ProcessActionTerm.PRECONDITION_REC_COLLECTION_VNPOST)
&& dossier.getVnpostalStatus() == VnpostCollectionTerm.VNPOSTAL_STAUS_2) {
dossier.setVnpostalStatus(VnpostCollectionTerm.VNPOSTAL_STAUS_3);
}
}
else {
}
//Create notification
if (OpenCPSConfigUtil.isNotificationEnable()) {
JSONObject notificationPayload = buildNotificationPayload(dossier, payloadObject);
createNotificationQueue(user, groupId, dossier, proAction, actionConfig, dossierAction, notificationPayload, context);
}
//Create subcription
createSubcription(userId, groupId, dossier, actionConfig, dossierAction, context);
//Tạo thông tin đồng bộ hồ sơ
createDossierSync(groupId, userId, actionConfig, proAction, dossierAction, dossier, syncType, option, payloadObject, flagChanged, actionCode, actionUser, actionNote, serviceProcess, context);
JSONObject newObj = JSONFactoryUtil.createJSONObject(payload);
if (payloadObject.has(DossierTerm.CROSS_DOSSIER)) {
newObj.put(DossierTerm.CROSS_DOSSIER, payloadObject.getJSONObject(DossierTerm.CROSS_DOSSIER));
}
//Add by TrungNT - Fix tam theo y/k cua a TrungDK va Duantv
if (dossier.isOnline() && proAction != null && "listener".equals(proAction.getAutoEvent().toString()) && OpenCPSConfigUtil.isPublishEventEnable()) {
publishEvent(dossier, context, dossierAction.getDossierActionId());
}
//Thực hiện thao tác lên hồ sơ gốc hoặc hồ sơ liên thông trong trường hợp có cấu hình mappingAction
doMappingAction(groupId, userId, employee, dossier, actionConfig, actionUser, actionNote, newObj.toJSONString(), assignUsers, payment, context);
//Update dossier
dossierLocalService.updateDossier(dossier);
// Indexer<Dossier> indexer = IndexerRegistryUtil
// .nullSafeGetIndexer(Dossier.class);
// indexer.reindex(dossier);
return dossierAction;
}
private JSONObject buildNotificationPayload(Dossier dossier, JSONObject payloadObject) {
JSONObject returnObject;
try {
returnObject = JSONFactoryUtil.createJSONObject(payloadObject.toJSONString());
_log.debug("=======> BUILD NOTIFICATION QUEUE SMS PAYLOAD");
if (dossier.getReceiveDate() != null) {
returnObject.put(DossierTerm.RECEIVE_DATE, APIDateTimeUtils.convertDateToString(dossier.getReceiveDate(), APIDateTimeUtils._NORMAL_DATE_TIME));
_log.debug("=======> BUILD NOTIFICATION QUEUE SMS RECEIVE DATE: " + returnObject.get(DossierTerm.RECEIVE_DATE));
}
else {
returnObject.put(DossierTerm.RECEIVE_DATE, StringPool.BLANK);
}
if (!returnObject.has(DossierTerm.DOSSIER_NO)) {
if (Validator.isNotNull(dossier.getDossierNo())) {
returnObject.put(DossierTerm.DOSSIER_NO, dossier.getDossierNo());
}
}
int durationUnit = dossier.getDurationUnit();
double durationCount = dossier.getDurationCount();
String durationText = StringPool.BLANK;
if (durationUnit == DossierTerm.DURATION_UNIT_DAY) {
durationText = String.valueOf(durationCount);
}
else if (durationUnit == DossierTerm.DURATION_UNIT_HOUR) {
durationText = String.valueOf(durationCount * 1.0 / DossierTerm.WORKING_HOUR_PER_DAY);
}
returnObject.put(DossierTerm.DURATION_TEXT, durationText);
if (!returnObject.has(DossierTerm.GOV_AGENCY_NAME)) {
returnObject.put(DossierTerm.GOV_AGENCY_NAME, dossier.getGovAgencyName());
}
if (!returnObject.has(DossierTerm.POSTAL_ADDRESS)) {
returnObject.put(DossierTerm.POSTAL_ADDRESS, dossier.getPostalAddress());
}
PaymentFile pf = paymentFileLocalService.getByDossierId(dossier.getGroupId(), dossier.getDossierId());
if (pf != null) {
if (!returnObject.has(PaymentFileTerm.PAYMENT_AMOUNT)) {
returnObject.put(PaymentFileTerm.PAYMENT_AMOUNT, String.valueOf(pf.getPaymentAmount()));
}
}
return returnObject;
} catch (JSONException e) {
_log.debug(e);
return payloadObject;
}
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public DossierAction doAction(long groupId, long userId, Dossier dossier, ProcessOption option, ProcessAction proAction,
String actionCode, String actionUser, String actionNote, String payload, String assignUsers,
String payment,
int syncType,
ServiceContext context) throws PortalException, SystemException, Exception {
context.setUserId(userId);
DossierAction dossierAction = null;
ActionConfig actionConfig = null;
actionConfig = actionConfigLocalService.getByCode(groupId, actionCode);
if (actionConfig != null && !actionConfig.getInsideProcess()) {
dossierAction = doActionOutsideProcess(groupId, userId, dossier, actionConfig, option, proAction, actionCode, actionUser, actionNote, payload, assignUsers, payment, syncType, context);
}
else {
dossierAction = doActionInsideProcess(groupId, userId, dossier, actionConfig, option, proAction, actionCode, actionUser, actionNote, payload, assignUsers, payment, syncType, context);
}
return dossierAction;
}
private void createNotificationQueue(User user, long groupId, Dossier dossier, ProcessAction proAction, ActionConfig actionConfig,
DossierAction dossierAction, JSONObject payloadObject, ServiceContext context) throws PortalException {
// DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId());
// User u = UserLocalServiceUtil.fetchUser(userId);
JSONObject payloadObj = JSONFactoryUtil.createJSONObject(payloadObject.toJSONString());
try {
JSONObject dossierObj = JSONFactoryUtil.createJSONObject(
JSONFactoryUtil.looseSerialize(dossier));
dossierObj = buildNotificationPayload(dossier, dossierObj);
payloadObj.put(
KeyPayTerm.DOSSIER, dossierObj);
// payloadObj.put(
// KeyPayTerm.DOSSIER, JSONFactoryUtil.createJSONObject(
// JSONFactoryUtil.looseSerialize(dossier)));
if (dossierAction != null) {
payloadObj.put(DossierActionTerm.ACTION_CODE, dossierAction.getActionCode());
payloadObj.put(DossierActionTerm.ACTION_USER, dossierAction.getActionUser());
payloadObj.put(DossierActionTerm.ACTION_NAME, dossierAction.getActionName());
payloadObj.put(DossierActionTerm.ACTION_NOTE, dossierAction.getActionNote());
}
//
if (payloadObject != null) {
Iterator<String> keys = payloadObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (PAYLOAD_KEY_COMPLEMENT_DATE.equalsIgnoreCase(key)) {
Long complementDate = payloadObject.getLong(PAYLOAD_KEY_COMPLEMENT_DATE);
if (complementDate != null && complementDate > 0) {
String strDate = APIDateTimeUtils.convertDateToString(new Date(complementDate),
APIDateTimeUtils._NORMAL_PARTTERN);
payloadObj.put(key, strDate);
}
} else {
payloadObj.put(key, payloadObject.getString(key));
}
}
}
}
catch (Exception e) {
_log.error(e);
}
String notificationType = StringPool.BLANK;
String preCondition = StringPool.BLANK;
if (actionConfig != null && Validator.isNotNull(actionConfig.getNotificationType())) {
_log.info("NOTIFICATION TYPE: " + actionConfig.getNotificationType());
if (actionConfig.getNotificationType().contains(StringPool.AT)) {
String[] split = StringUtil.split(actionConfig.getNotificationType(), StringPool.AT);
if (split.length == 2) {
notificationType = split[0];
preCondition = split[1];
}
}
else {
notificationType = actionConfig.getNotificationType();
}
_log.info("NOTIFICATION TYPE: " + notificationType + ", CONDITION: " + preCondition);
boolean isSendSMS = NotificationUtil.isSendSMS(preCondition);
boolean isSendEmail = NotificationUtil.isSendEmail(preCondition);
boolean isSendNotiSMS = true;
boolean isSendNotiEmail = true;
if (Validator.isNotNull(preCondition)) {
if (!DossierMgtUtils.checkPreCondition(new String[] { preCondition } , dossier, null)) {
if (isSendSMS) {
isSendNotiSMS = false;
isSendNotiEmail = true;
}
else {
isSendNotiSMS = false;
isSendNotiEmail = false;
}
}
else {
isSendNotiSMS = isSendSMS;
isSendNotiEmail = isSendEmail;
}
}
// Notificationtemplate notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, actionConfig.getNotificationType());
Serializable notiCache = cache.getFromCache(CACHE_NOTIFICATION_TEMPLATE, groupId +StringPool.UNDERLINE+ notificationType);
Notificationtemplate notiTemplate = null;
// notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, actionConfig.getNotificationType());
if (notiCache == null) {
notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, notificationType);
if (notiTemplate != null) {
cache.addToCache(CACHE_NOTIFICATION_TEMPLATE,
groupId +StringPool.UNDERLINE+ notificationType, (Serializable) notiTemplate,
ttl);
}
} else {
notiTemplate = (Notificationtemplate) notiCache;
}
Date now = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(now);
if (notiTemplate != null) {
if (KeyPayTerm.MINUTELY.equals(notiTemplate.getInterval())) {
cal.add(Calendar.MINUTE, notiTemplate.getExpireDuration());
}
else if (KeyPayTerm.HOURLY.equals(notiTemplate.getInterval())) {
cal.add(Calendar.HOUR, notiTemplate.getExpireDuration());
}
else {
cal.add(Calendar.MINUTE, notiTemplate.getExpireDuration());
}
Date expired = cal.getTime();
if (notificationType.startsWith(KeyPayTerm.APLC)) {
if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA
|| dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) {
try {
// Applicant applicant = ApplicantLocalServiceUtil.fetchByAppId(dossier.getApplicantIdNo());
List<Applicant> applicants = ApplicantLocalServiceUtil.findByAppIds(dossier.getApplicantIdNo());
Applicant foundApplicant = (applicants.isEmpty() ? null : applicants.get(0));
for (Applicant applicant : applicants) {
long toUserId = (applicant != null ? applicant.getMappingUserId() : 0l);
if (toUserId != 0) {
foundApplicant = applicant;
break;
}
}
if (foundApplicant != null) {
JSONObject filesAttach = getFileAttachMailForApplicant(dossier, proAction);
payloadObj.put("filesAttach", filesAttach);
String fromFullName = user.getFullName();
if (Validator.isNotNull(OpenCPSConfigUtil.getMailToApplicantFrom())) {
fromFullName = OpenCPSConfigUtil.getMailToApplicantFrom();
}
NotificationQueueLocalServiceUtil.addNotificationQueue(
user.getUserId(), groupId,
notificationType,
Dossier.class.getName(),
String.valueOf(dossier.getDossierId()),
payloadObj.toJSONString(),
fromFullName,
dossier.getApplicantName(),
foundApplicant.getMappingUserId(),
isSendNotiEmail ? dossier.getContactEmail() : StringPool.BLANK,
isSendNotiSMS ? dossier.getContactTelNo() : StringPool.BLANK,
now,
expired,
context);
}
} catch (NoSuchUserException e) {
_log.debug(e);
}
}
}
else if (notificationType.startsWith(KeyPayTerm.USER)) {
}
else if (notificationType.startsWith("EMPL")) {
_log.debug("ADD NOTI EMPL");
List<DossierActionUser> lstDaus = DossierActionUserLocalServiceUtil.getByDossierAndStepCode(dossier.getDossierId(), dossierAction.getStepCode());
_log.debug("ADD NOTI LIST DAU: " + lstDaus.size());
for (DossierActionUser dau : lstDaus) {
_log.debug("ADD NOTI DAU: " + dau.getAssigned());
if (dau.getAssigned() == DossierActionUserTerm.ASSIGNED_TH || dau.getAssigned() == DossierActionUserTerm.ASSIGNED_PH) {
// Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId());
Serializable employeeCache = cache.getFromCache("Employee", groupId +"_"+ dau.getUserId());
Employee employee = null;
// employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId());
if (employeeCache == null) {
employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId());
if (employee != null) {
cache.addToCache("Employee",
groupId +"_"+ dau.getUserId(), (Serializable) employee,
ttl);
}
} else {
employee = (Employee) employeeCache;
}
_log.debug("ADD NOTI EMPLOYEE: " + employee);
if (employee != null) {
String telNo = employee != null ? employee.getTelNo() : StringPool.BLANK;
String fullName = employee != null ? employee.getFullName() : StringPool.BLANK;
long start = System.currentTimeMillis();
_log.debug("BEFORE ADD NOTI EMPLOYEE: " + actionConfig.getNotificationType());
NotificationQueueLocalServiceUtil.addNotificationQueue(
user.getUserId(), groupId,
notificationType,
Dossier.class.getName(),
String.valueOf(dossier.getDossierId()),
payloadObj.toJSONString(),
user.getFullName(),
fullName,
dau.getUserId(),
employee.getEmail(),
telNo,
now,
expired,
context);
_log.debug("ADD NOTI QUEUE: " + (System.currentTimeMillis() - start));
}
}
}
}
}
}
// Notificationtemplate emplTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, NotificationTemplateTerm.EMPL_01);
Serializable emplCache = cache.getFromCache(CACHE_NOTIFICATION_TEMPLATE, groupId +StringPool.UNDERLINE+ NotificationTemplateTerm.EMPL_01);
//Notificationtemplate emplTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, NotificationTemplateTerm.EMPL_01);
Notificationtemplate emplTemplate = null;
if (emplCache == null) {
emplTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, NotificationTemplateTerm.EMPL_01);
if (emplTemplate != null) {
cache.addToCache(CACHE_NOTIFICATION_TEMPLATE,
groupId +StringPool.UNDERLINE+ actionConfig.getNotificationType(), (Serializable) emplTemplate,
ttl);
}
} else {
emplTemplate = (Notificationtemplate) emplCache;
}
Date now = new Date();
Calendar calEmpl = Calendar.getInstance();
calEmpl.setTime(now);
if (emplTemplate != null) {
if (KeyPayTerm.MINUTELY.equals(emplTemplate.getInterval())) {
calEmpl.add(Calendar.MINUTE, emplTemplate.getExpireDuration());
}
else if (KeyPayTerm.HOURLY.equals(emplTemplate.getInterval())) {
calEmpl.add(Calendar.HOUR, emplTemplate.getExpireDuration());
}
else {
calEmpl.add(Calendar.MINUTE, emplTemplate.getExpireDuration());
}
Date expired = calEmpl.getTime();
if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA
|| dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) {
try {
String stepCode = dossierAction.getStepCode();
StringBuilder buildX = new StringBuilder(stepCode);
if (stepCode.length() > 0) {
buildX.setCharAt(stepCode.length() - 1, 'x');
}
String stepCodeX = buildX.toString();
StepConfig stepConfig = StepConfigLocalServiceUtil.getByCode(groupId, dossierAction.getStepCode());
StepConfig stepConfigX = StepConfigLocalServiceUtil.getByCode(groupId, stepCodeX);
if ((stepConfig != null && stepConfig.getStepType() == StepConfigTerm.STEP_TYPE_DISPLAY_MENU_BY_PROCESSED)
|| (stepConfigX != null && stepConfigX.getStepType() == StepConfigTerm.STEP_TYPE_DISPLAY_MENU_BY_PROCESSED)) {
List<DossierActionUser> lstDaus = DossierActionUserLocalServiceUtil.getByDossierAndStepCode(dossier.getDossierId(), dossierAction.getStepCode());
for (DossierActionUser dau : lstDaus) {
if (dau.getAssigned() == DossierActionUserTerm.ASSIGNED_TH || dau.getAssigned() == DossierActionUserTerm.ASSIGNED_PH) {
// Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId());
Serializable employeeCache = cache.getFromCache(CacheTerm.MASTER_DATA_EMPLOYEE, groupId +StringPool.UNDERLINE+ dau.getUserId());
Employee employee = null;
// employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId());
if (employeeCache == null) {
employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId());
if (employee != null) {
cache.addToCache(CacheTerm.MASTER_DATA_EMPLOYEE,
groupId +StringPool.UNDERLINE+ dau.getUserId(), (Serializable) employee,
ttl);
}
} else {
employee = (Employee) employeeCache;
}
if (employee != null) {
String telNo = employee != null ? employee.getTelNo() : StringPool.BLANK;
String fullName = employee != null ? employee.getFullName() : StringPool.BLANK;
long start = System.currentTimeMillis();
NotificationQueueLocalServiceUtil.addNotificationQueue(
user.getUserId(), groupId,
NotificationTemplateTerm.EMPL_01,
Dossier.class.getName(),
String.valueOf(dossier.getDossierId()),
payloadObj.toJSONString(),
user.getFullName(),
fullName,
dau.getUserId(),
employee.getEmail(),
telNo,
now,
expired,
context);
_log.debug("ADD NOTI QUEUE: " + (System.currentTimeMillis() - start));
}
}
}
}
} catch (NoSuchUserException e) {
_log.error(e);
//_log.error(e);
// e.printStackTrace();
}
}
}
}
private void updateDossierPayload(Dossier dossier, JSONObject obj) {
if (obj.has(DossierTerm.DOSSIER_NOTE)) {
if (!obj.getString(DossierTerm.DOSSIER_NOTE).equals(dossier.getDossierNote())) {
dossier.setDossierNote(obj.getString(DossierTerm.DOSSIER_NOTE));
}
}
if (obj.has(DossierTerm.EXTEND_DATE) && Validator.isNotNull(obj.get(DossierTerm.EXTEND_DATE))
&& GetterUtil.getLong(obj.get(DossierTerm.EXTEND_DATE)) > 0) {
if (dossier.getExtendDate() == null || obj.getLong(DossierTerm.EXTEND_DATE) != dossier.getExtendDate().getTime()) {
dossier.setExtendDate(new Date(obj.getLong(DossierTerm.EXTEND_DATE)));
}
}
if (obj.has(DossierTerm.DOSSIER_NO)) {
//_log.info("Sync dossier no");
if (Validator.isNotNull(obj.getString(DossierTerm.DOSSIER_NO)) && !obj.getString(DossierTerm.DOSSIER_NO).equals(dossier.getDossierNo())) {
//_log.info("Sync set dossier no");
dossier.setDossierNo(obj.getString(DossierTerm.DOSSIER_NO));
}
}
if (obj.has(DossierTerm.DUE_DATE) && Validator.isNotNull(obj.get(DossierTerm.DUE_DATE))
&& GetterUtil.getLong(obj.get(DossierTerm.DUE_DATE)) > 0) {
if (dossier.getDueDate() == null || obj.getLong(DossierTerm.DUE_DATE) != dossier.getDueDate().getTime()) {
dossier.setDueDate(new Date(obj.getLong(DossierTerm.DUE_DATE)));
}
}
if (obj.has(DossierTerm.FINISH_DATE) && Validator.isNotNull(obj.get(DossierTerm.FINISH_DATE))
&& GetterUtil.getLong(obj.get(DossierTerm.FINISH_DATE)) > 0) {
if (dossier.getFinishDate() == null || obj.getLong(DossierTerm.FINISH_DATE) != dossier.getFinishDate().getTime()) {
dossier.setFinishDate(new Date(obj.getLong(DossierTerm.FINISH_DATE)));
}
}
if (obj.has(DossierTerm.RECEIVE_DATE) && Validator.isNotNull(obj.get(DossierTerm.RECEIVE_DATE))
&& GetterUtil.getLong(obj.get(DossierTerm.RECEIVE_DATE)) > 0) {
if (dossier.getReceiveDate() == null || obj.getLong(DossierTerm.RECEIVE_DATE) != dossier.getReceiveDate().getTime()) {
dossier.setReceiveDate(new Date(obj.getLong(DossierTerm.RECEIVE_DATE)));
}
}
if (obj.has(DossierTerm.SUBMIT_DATE) && Validator.isNotNull(obj.get(DossierTerm.SUBMIT_DATE))
&& GetterUtil.getLong(obj.get(DossierTerm.SUBMIT_DATE)) > 0) {
if (dossier.getSubmitDate() == null || (dossier.getSubmitDate() != null && obj.getLong(DossierTerm.SUBMIT_DATE) != dossier.getSubmitDate().getTime())) {
dossier.setSubmitDate(new Date(obj.getLong(DossierTerm.SUBMIT_DATE)));
}
}
if (obj.has(DossierTerm.EXTEND_DATE) && Validator.isNotNull(obj.get(DossierTerm.EXTEND_DATE))
&& GetterUtil.getLong(obj.get(DossierTerm.EXTEND_DATE)) > 0) {
if (dossier.getExtendDate() == null || obj.getLong(DossierTerm.EXTEND_DATE) != dossier.getExtendDate().getTime()) {
dossier.setExtendDate(new Date(obj.getLong(DossierTerm.EXTEND_DATE)));
}
}
if (obj.has(DossierTerm.DOSSIER_NOTE)) {
if (dossier.getDossierNote() == null || !obj.getString(DossierTerm.DOSSIER_NOTE).equals(dossier.getDossierNote())) {
dossier.setDossierNote(obj.getString(DossierTerm.DOSSIER_NOTE));
}
}
if (obj.has(DossierTerm.SUBMISSION_NOTE)) {
if (!obj.getString(DossierTerm.SUBMISSION_NOTE).equals(dossier.getDossierNote())) {
dossier.setSubmissionNote(obj.getString(DossierTerm.SUBMISSION_NOTE));
}
}
if (obj.has(DossierTerm.RELEASE_DATE) && Validator.isNotNull(obj.get(DossierTerm.RELEASE_DATE))
&& GetterUtil.getLong(obj.get(DossierTerm.RELEASE_DATE)) > 0) {
if (dossier.getReleaseDate() == null || obj.getLong(DossierTerm.RELEASE_DATE) != dossier.getReleaseDate().getTime()) {
dossier.setReleaseDate(new Date(obj.getLong(DossierTerm.RELEASE_DATE)));
}
}
if (obj.has(DossierTerm.LOCK_STATE)) {
if (!obj.getString(DossierTerm.LOCK_STATE).equals(dossier.getLockState())) {
dossier.setLockState(obj.getString(DossierTerm.LOCK_STATE));
}
}
if (obj.has(DossierTerm.BRIEF_NOTE)) {
if (!obj.getString(DossierTerm.BRIEF_NOTE).equals(dossier.getBriefNote())) {
dossier.setBriefNote(obj.getString(DossierTerm.BRIEF_NOTE));
}
}
}
private void processPaymentFile(long groupId, long userId, String payment, ProcessOption option,
ProcessAction proAction, DossierAction previousAction, Dossier dossier, ServiceContext context)
throws PortalException {
// long serviceProcessId = (option != null ? option.getServiceProcessId() : previousAction.getServiceProcessId());
// ServiceProcess serviceProcess = ServiceProcessLocalServiceUtil.fetchServiceProcess(serviceProcessId);
String paymentMethod = "";
try {
JSONObject paymentObj = JSONFactoryUtil.createJSONObject(payment);
if (paymentObj.has("paymentMethod")) {
paymentMethod = paymentObj.getString("paymentMethod");
}
}
catch (Exception e) {
_log.debug(e);
}
//Yêu cầu nộp tạm ứng
if (proAction.getRequestPayment() == ProcessActionTerm.REQUEST_PAYMENT_YEU_CAU_NOP_TAM_UNG
|| proAction.getRequestPayment() == ProcessActionTerm.REQUEST_PAYMENT_YEU_CAU_QUYET_TOAN_PHI && Validator.isNotNull(payment)) {
createPaymentFile(groupId, userId, payment, option, proAction, previousAction, dossier, context);
} else if (proAction.getRequestPayment() == ProcessActionTerm.REQUEST_PAYMENT_XAC_NHAN_HOAN_THANH_THU_PHI) {
// neu chua co payment file thi phai tao payment file
PaymentFile oldPaymentFile = paymentFileLocalService.getByDossierId(groupId, dossier.getDossierId());
if (Validator.isNull(oldPaymentFile)) {
oldPaymentFile = createPaymentFile(groupId, userId, payment, option, proAction, previousAction, dossier, context);
}
try {
_log.debug("groupId=" + groupId + " dossierId=" + dossier.getDossierId());
ExecuteOneActionTerm.invokeSInvoice(groupId, dossier, context);
} catch (Exception e) {
// TODO: do sth
_log.error(e);
}
String CINVOICEUrl = "postal/invoice";
JSONObject resultObj = null;
Map<String, Object> params = new HashMap<>();
int intpaymentMethod = 0;
if (Validator.isNotNull(proAction.getPreCondition())) {
intpaymentMethod = checkPaymentMethodinPrecondition(proAction.getPreCondition());
}
if (oldPaymentFile != null && proAction.getPreCondition().toLowerCase().contains("sendinvoice=1")){
params = createParamsInvoice(oldPaymentFile, dossier, intpaymentMethod);
InvokeREST callRest = new InvokeREST();
String baseUrl = RESTFulConfiguration.SERVER_PATH_BASE;
HashMap<String, String> properties = new HashMap<String, String>();
resultObj = callRest.callPostAPI(groupId, HttpMethod.POST, MediaType.APPLICATION_JSON, baseUrl,
CINVOICEUrl, StringPool.BLANK, StringPool.BLANK, properties, params, context);
}
if (Validator.isNotNull(oldPaymentFile) ) {
// String paymentMethod = "";
// if (intpaymentMethod != 0) {
// paymentMethod = checkPaymentMethod(intpaymentMethod);
// }
if(resultObj != null) {
oldPaymentFile.setEinvoice(resultObj.toString());
oldPaymentFile.setInvoicePayload(params.toString());
// if (Validator.isNotNull(paymentMethod)) {
// oldPaymentFile.setPaymentMethod(paymentMethod);
// }
if (Validator.isNotNull(paymentMethod)) {
oldPaymentFile.setPaymentMethod(paymentMethod);
}
}
if (Validator.isNotNull(payment)) {
try {
JSONObject paymentObj = JSONFactoryUtil.createJSONObject(payment);
if (paymentObj.has(KeyPayTerm.PAYMENTNOTE)) {
if (oldPaymentFile != null)
oldPaymentFile.setPaymentNote(paymentObj.getString(KeyPayTerm.PAYMENTNOTE));
String epaymentProfile = oldPaymentFile != null ? oldPaymentFile.getEpaymentProfile() : StringPool.BLANK;
if (Validator.isNotNull(epaymentProfile)) {
JSONObject jsonEpayment = JSONFactoryUtil.createJSONObject(epaymentProfile);
jsonEpayment.put(KeyPayTerm.PAYMENTNOTE, paymentObj.getString(KeyPayTerm.PAYMENTNOTE));
if (oldPaymentFile != null)
oldPaymentFile.setEpaymentProfile(jsonEpayment.toJSONString());
}
}
} catch (JSONException e) {
_log.debug(e);
}
}
if (oldPaymentFile != null) {
oldPaymentFile.setPaymentStatus(proAction.getRequestPayment());
paymentFileLocalService.updatePaymentFile(oldPaymentFile);
}
}
} else if (proAction.getRequestPayment() == ProcessActionTerm.REQUEST_PAYMENT_BAO_DA_NOP_PHI) {
PaymentFile oldPaymentFile = paymentFileLocalService.getByDossierId(groupId, dossier.getDossierId());
// int intpaymentMethod = checkPaymentMethodinPrecondition(proAction.getPreCondition());
// String paymentMethod = checkPaymentMethod(intpaymentMethod);
if (oldPaymentFile != null) {
oldPaymentFile.setPaymentStatus(proAction.getRequestPayment());
// oldPaymentFile.setPaymentMethod(paymentMethod);
if (Validator.isNotNull(paymentMethod)) {
oldPaymentFile.setPaymentMethod(paymentMethod);
}
paymentFileLocalService.updatePaymentFile(oldPaymentFile);
}
}
}
private PaymentFile createPaymentFile (long groupId, long userId, String payment, ProcessOption option,
ProcessAction proAction, DossierAction previousAction, Dossier dossier, ServiceContext context) throws PortalException {
String paymentFee = StringPool.BLANK;
Long feeAmount = 0l, serviceAmount = 0l, shipAmount = 0l;
String paymentNote = StringPool.BLANK;
long advanceAmount = 0l;
//long paymentAmount = 0l;
String epaymentProfile = StringPool.BLANK;
String bankInfo = StringPool.BLANK;
int paymentStatus = 0;
String paymentMethod = StringPool.BLANK;
NumberFormat fmt = NumberFormat.getNumberInstance(LocaleUtil.getDefault());
DecimalFormatSymbols customSymbol = new DecimalFormatSymbols();
customSymbol.setDecimalSeparator(',');
customSymbol.setGroupingSeparator('.');
((DecimalFormat)fmt).setDecimalFormatSymbols(customSymbol);
fmt.setGroupingUsed(true);
try {
JSONObject paymentObj = JSONFactoryUtil.createJSONObject(payment);
if (paymentObj.has(KeyPayTerm.PAYMENTNOTE)) {
paymentNote = paymentObj.getString(KeyPayTerm.PAYMENTNOTE);
}
if (paymentObj.has(KeyPayTerm.FEEAMOUNT)) {
feeAmount = (Long)fmt.parse(paymentObj.getString(KeyPayTerm.FEEAMOUNT));
}
if (paymentObj.has(KeyPayTerm.SERVICEAMOUNT)) {
serviceAmount = (Long)fmt.parse(paymentObj.getString(KeyPayTerm.SERVICEAMOUNT));
}
if (paymentObj.has(KeyPayTerm.SHIPAMOUNT)) {
shipAmount = (Long)fmt.parse(paymentObj.getString(KeyPayTerm.SHIPAMOUNT));
}
if (paymentObj.has(KeyPayTerm.REQUESTPAYMENT)) {
paymentStatus = paymentObj.getInt(KeyPayTerm.REQUESTPAYMENT);
}
if (paymentObj.has(KeyPayTerm.ADVANCEAMOUNT)) {
advanceAmount = (Long)fmt.parse(paymentObj.getString(KeyPayTerm.ADVANCEAMOUNT));
}
JSONObject paymentObj2 = JSONFactoryUtil.createJSONObject(proAction.getPaymentFee());
if (paymentObj2.has("paymentFee")) {
paymentFee = paymentObj2.getString("paymentFee");
}
if (paymentObj.has("paymentMethod")) {
paymentMethod = paymentObj.getString("paymentMethod");
}
}
catch (JSONException e) {
_log.debug(e);
} catch (ParseException e) {
_log.debug(e);
}
PaymentFile oldPaymentFile = paymentFileLocalService.getByDossierId(groupId, dossier.getDossierId());
if (oldPaymentFile != null) {
if (Validator.isNotNull(paymentMethod)) {
oldPaymentFile.setPaymentMethod(paymentMethod);
}
if (Validator.isNotNull(paymentNote))
oldPaymentFile.setPaymentNote(paymentNote);
try {
PaymentFile paymentFile = paymentFileLocalService.updateApplicantFeeAmount(
oldPaymentFile.getPaymentFileId(), proAction.getRequestPayment(), feeAmount, serviceAmount,
shipAmount, paymentNote, dossier.getOriginality());
String generatorPayURL = PaymentUrlGenerator.generatorPayURL(groupId,
paymentFile.getPaymentFileId(), paymentFee, dossier.getDossierId());
JSONObject epaymentProfileJsonNew = JSONFactoryUtil.createJSONObject(paymentFile.getEpaymentProfile());
epaymentProfileJsonNew.put(KeyPayTerm.KEYPAYURL, generatorPayURL);
PaymentConfig paymentConfig = paymentConfigLocalService.getPaymentConfigByGovAgencyCode(groupId,
dossier.getGovAgencyCode());
JSONObject epaymentConfigJSON = paymentConfig != null ? JSONFactoryUtil.createJSONObject(paymentConfig.getEpaymentConfig()) : JSONFactoryUtil.createJSONObject();
_log.debug("==========VTPayTerm.VTP_CONFIG========"+epaymentConfigJSON);
if (epaymentConfigJSON.has(VTPayTerm.VTP_CONFIG)) {
try {
JSONObject schema = epaymentConfigJSON.getJSONObject(VTPayTerm.VTP_CONFIG);
JSONObject data = JSONFactoryUtil.createJSONObject();
data.put(schema.getJSONObject(VTPayTerm.PRIORITY).getString(VTPayTerm.KEY),
schema.getJSONObject(VTPayTerm.PRIORITY).getString(VTPayTerm.VALUE));
data.put(schema.getJSONObject(VTPayTerm.VERSION).getString(VTPayTerm.KEY),
schema.getJSONObject(VTPayTerm.VERSION).getString(VTPayTerm.VALUE));
data.put(schema.getJSONObject(VTPayTerm.TYPE).getString(VTPayTerm.KEY),
schema.getJSONObject(VTPayTerm.TYPE).getString(VTPayTerm.VALUE));
data.put(schema.getJSONObject(VTPayTerm.BILLCODE).getString(VTPayTerm.KEY), VTPayTerm.createBillCode(dossier.getGovAgencyCode(), paymentFile.getInvoiceNo()));
data.put(schema.getJSONObject(VTPayTerm.ORDER_ID).getString(VTPayTerm.KEY), VTPayTerm.createOrderId(dossier.getDossierId(), dossier.getDossierNo()));
data.put(schema.getJSONObject(VTPayTerm.AMOUNT).getString(VTPayTerm.KEY), paymentFile.getPaymentAmount());
data.put(schema.getJSONObject(VTPayTerm.MERCHANT_CODE).getString(VTPayTerm.KEY),
schema.getJSONObject(VTPayTerm.MERCHANT_CODE).getString(VTPayTerm.VALUE));
epaymentProfileJsonNew.put(VTPayTerm.VTPAY_GENQR, data);
} catch (Exception e) {
_log.error(e);
}
}
paymentFileLocalService.updateEProfile(dossier.getDossierId(), paymentFile.getReferenceUid(), epaymentProfileJsonNew.toJSONString(),
context);
} catch (IOException e) {
_log.error(e);
}
catch (JSONException e) {
_log.debug(e);
}
} else {
long paymentAmount = feeAmount + serviceAmount + shipAmount - advanceAmount;
PaymentFile paymentFile = paymentFileLocalService.createPaymentFiles(userId, groupId,
dossier.getDossierId(), dossier.getReferenceUid(), paymentFee, advanceAmount, feeAmount,
serviceAmount, shipAmount, paymentAmount, paymentNote, epaymentProfile, bankInfo,
paymentStatus, paymentMethod, context);
long counterPaymentFile = CounterLocalServiceUtil.increment(PaymentFile.class.getName() + "paymentFileNo");
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
int prefix = cal.get(Calendar.YEAR);
String invoiceNo = Integer.toString(prefix) + String.format("%010d", counterPaymentFile);
paymentFile.setInvoiceNo(invoiceNo);
PaymentConfig paymentConfig = paymentConfigLocalService.getPaymentConfigByGovAgencyCode(groupId,
dossier.getGovAgencyCode());
if (Validator.isNotNull(paymentConfig)) {
paymentFile.setInvoiceTemplateNo(paymentConfig.getInvoiceTemplateNo());
paymentFile.setGovAgencyTaxNo(paymentConfig.getGovAgencyTaxNo());
paymentFile.setGovAgencyCode(paymentConfig.getGovAgencyCode());
paymentFile.setGovAgencyName(paymentConfig.getGovAgencyName());
}
paymentFileLocalService.updatePaymentFile(paymentFile);
JSONObject epaymentConfigJSON = paymentConfig != null ? JSONFactoryUtil.createJSONObject(paymentConfig.getEpaymentConfig()) : JSONFactoryUtil.createJSONObject();
JSONObject epaymentProfileJSON = JSONFactoryUtil.createJSONObject();
if (epaymentConfigJSON.has("paymentKeypayDomain")) {
try {
String generatorPayURL = PaymentUrlGenerator.generatorPayURL(groupId,
paymentFile.getPaymentFileId(), paymentFee, dossier.getDossierId());
epaymentProfileJSON.put(KeyPayTerm.KEYPAYURL, generatorPayURL);
String pattern1 = KeyPayTerm.GOOD_CODE_EQ;
String pattern2 = StringPool.AMPERSAND;
String regexString = Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2);
Pattern p = Pattern.compile(regexString);
Matcher m = p.matcher(generatorPayURL);
if (m.find()) {
String goodCode = m.group(1);
epaymentProfileJSON.put(KeyPayTerm.KEYPAYGOODCODE, goodCode);
} else {
epaymentProfileJSON.put(KeyPayTerm.KEYPAYGOODCODE, StringPool.BLANK);
}
epaymentProfileJSON.put(KeyPayTerm.KEYPAYMERCHANTCODE, epaymentConfigJSON.get("paymentMerchantCode"));
epaymentProfileJSON.put(KeyPayTerm.BANK, String.valueOf(true));
epaymentProfileJSON.put(KeyPayTerm.PAYGATE, String.valueOf(true));
epaymentProfileJSON.put(KeyPayTerm.SERVICEAMOUNT, serviceAmount);
epaymentProfileJSON.put(KeyPayTerm.PAYMENTNOTE, paymentNote);
epaymentProfileJSON.put(KeyPayTerm.PAYMENTFEE, paymentFee);
paymentFileLocalService.updateEProfile(dossier.getDossierId(), paymentFile.getReferenceUid(), epaymentProfileJSON.toJSONString(),
context);
} catch (IOException e) {
_log.error(e);
}
} else {
paymentFileLocalService.updateEProfile(dossier.getDossierId(), paymentFile.getReferenceUid(), epaymentProfileJSON.toJSONString(),
context);
}
_log.debug("==========VTPayTerm.VTP_CONFIG========"+epaymentConfigJSON);
if (epaymentConfigJSON.has(VTPayTerm.VTP_CONFIG)) {
try {
JSONObject schema = epaymentConfigJSON.getJSONObject(VTPayTerm.VTP_CONFIG);
JSONObject data = JSONFactoryUtil.createJSONObject();
data.put(schema.getJSONObject(VTPayTerm.PRIORITY).getString(VTPayTerm.KEY),
schema.getJSONObject(VTPayTerm.PRIORITY).getString(VTPayTerm.VALUE));
data.put(schema.getJSONObject(VTPayTerm.VERSION).getString(VTPayTerm.KEY),
schema.getJSONObject(VTPayTerm.VERSION).getString(VTPayTerm.VALUE));
data.put(schema.getJSONObject(VTPayTerm.TYPE).getString(VTPayTerm.KEY),
schema.getJSONObject(VTPayTerm.TYPE).getString(VTPayTerm.VALUE));
data.put(schema.getJSONObject(VTPayTerm.BILLCODE).getString(VTPayTerm.KEY), VTPayTerm.createBillCode(dossier.getGovAgencyCode(), paymentFile.getInvoiceNo()));
data.put(schema.getJSONObject(VTPayTerm.ORDER_ID).getString(VTPayTerm.KEY), VTPayTerm.createOrderId(dossier.getDossierId(), dossier.getDossierNo()));
data.put(schema.getJSONObject(VTPayTerm.AMOUNT).getString(VTPayTerm.KEY), paymentFile.getPaymentAmount());
data.put(schema.getJSONObject(VTPayTerm.MERCHANT_CODE).getString(VTPayTerm.KEY),
schema.getJSONObject(VTPayTerm.MERCHANT_CODE).getString(VTPayTerm.VALUE));
epaymentProfileJSON.put(VTPayTerm.VTPAY_GENQR, data);
paymentFileLocalService.updateEProfile(dossier.getDossierId(), paymentFile.getReferenceUid(), epaymentProfileJSON.toJSONString(),
context);
} catch (Exception e) {
_log.error(e);
}
}
}
return oldPaymentFile;
}
private void createNotificationSMS(long userId, long groupId, Dossier dossier, JSONArray assignedUsers, DossierAction dossierAction, ServiceContext context) {
// DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId());
User u = UserLocalServiceUtil.fetchUser(userId);
JSONObject payloadObj = JSONFactoryUtil.createJSONObject();
try {
payloadObj.put(
KeyPayTerm.DOSSIER, JSONFactoryUtil.createJSONObject(
JSONFactoryUtil.looseSerialize(dossier)));
if (dossierAction != null) {
payloadObj.put(DossierActionTerm.ACTION_CODE, dossierAction.getActionCode());
payloadObj.put(DossierActionTerm.ACTION_USER, dossierAction.getActionUser());
payloadObj.put(DossierActionTerm.ACTION_NAME, dossierAction.getActionName());
payloadObj.put(DossierActionTerm.ACTION_NOTE, dossierAction.getActionNote());
}
}
catch (Exception e) {
_log.error(e);
}
Notificationtemplate emplTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, NotificationTemplateTerm.EMPL_03);
Date now = new Date();
Calendar calEmpl = Calendar.getInstance();
calEmpl.setTime(now);
if (emplTemplate != null) {
if (KeyPayTerm.MINUTELY.equals(emplTemplate.getInterval())) {
calEmpl.add(Calendar.MINUTE, emplTemplate.getExpireDuration());
}
else if (KeyPayTerm.HOURLY.equals(emplTemplate.getInterval())) {
calEmpl.add(Calendar.HOUR, emplTemplate.getExpireDuration());
}
else {
calEmpl.add(Calendar.MINUTE, emplTemplate.getExpireDuration());
}
Date expired = calEmpl.getTime();
if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA
|| dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) {
try {
String stepCode = dossierAction.getStepCode();
StringBuilder buildX = new StringBuilder(stepCode);
if (stepCode.length() > 0) {
buildX.setCharAt(stepCode.length() - 1, 'x');
}
String stepCodeX = buildX.toString();
StepConfig stepConfig = StepConfigLocalServiceUtil.getByCode(groupId, dossierAction.getStepCode());
StepConfig stepConfigX = StepConfigLocalServiceUtil.getByCode(groupId, stepCodeX);
if ((stepConfig != null && stepConfig.getStepType() == StepConfigTerm.STEP_TYPE_DISPLAY_MENU_BY_PROCESSED)
|| (stepConfigX != null && stepConfigX.getStepType() == StepConfigTerm.STEP_TYPE_DISPLAY_MENU_BY_PROCESSED)) {
for (int n = 0; n < assignedUsers.length(); n++) {
JSONObject subUser = assignedUsers.getJSONObject(n);
if (subUser != null && subUser.has(DossierActionUserTerm.ASSIGNED)
&& subUser.getInt(DossierActionUserTerm.ASSIGNED) == DossierActionUserTerm.ASSIGNED_TH) {
long userIdAssigned = subUser.getLong(Field.USER_ID);
Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userIdAssigned);
if (employee != null) {
String telNo = employee != null ? employee.getTelNo() : StringPool.BLANK;
String fullName = employee != null ? employee.getFullName() : StringPool.BLANK;
NotificationQueueLocalServiceUtil.addNotificationQueue(
userId, groupId,
NotificationTemplateTerm.EMPL_03,
Dossier.class.getName(),
String.valueOf(dossier.getDossierId()),
payloadObj.toJSONString(),
u.getFullName(),
fullName,
userIdAssigned,
employee.getEmail(),
telNo,
now,
expired,
context);
}
}
}
}
} catch (NoSuchUserException e) {
_log.error(e);
//_log.error(e);
// e.printStackTrace();
}
}
}
}
private void createSubcription(long userId, long groupId, Dossier dossier, ActionConfig actionConfig, DossierAction dossierAction, ServiceContext context) {
if (actionConfig != null && Validator.isNotNull(actionConfig.getNotificationType())) {
// DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId());
// User u = UserLocalServiceUtil.fetchUser(userId);
Notificationtemplate notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, actionConfig.getNotificationType());
if (notiTemplate != null) {
if (actionConfig.getDocumentType().startsWith(KeyPayTerm.APLC)) {
if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA
|| dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) {
}
}
else if (actionConfig.getDocumentType().startsWith("EMPL")) {
if ((dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA
|| dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG)
&& dossierAction != null) {
StepConfig stepConfig = stepConfigLocalService.getByCode(groupId, dossierAction.getStepCode());
List<DossierActionUser> lstDaus = dossierActionUserLocalService.getByDID_DAI_SC_AS(dossier.getDossierId(), dossierAction.getDossierActionId(), dossierAction.getStepCode(), new int[] { 1, 2 });
if (NotificationTemplateTerm.EMPL_01.equals(actionConfig.getDocumentType()) && stepConfig != null
&& String.valueOf(1).equals(Validator.isNotNull(stepConfig.getStepType())
? String.valueOf(stepConfig.getStepType())
: StringPool.BLANK)) {
for (DossierActionUser dau : lstDaus) {
try {
SubscriptionLocalServiceUtil.addSubscription(dau.getUserId(), groupId, NotificationTemplateTerm.EMPL_01, 0);
} catch (PortalException e) {
_log.debug(e);
}
}
}
}
}
else if (actionConfig.getDocumentType().startsWith("USER")) {
}
}
}
}
private List<String> _putPaymentMessage(String pattern) {
List<String> lsDesc = new ArrayList<String>();
lsDesc.add(0, StringPool.BLANK);
lsDesc.add(1, StringPool.BLANK);
lsDesc.add(2, StringPool.BLANK);
lsDesc.add(3, StringPool.BLANK);
lsDesc.add(4, StringPool.BLANK);
List<String> lsMsg = DossierPaymentUtils.getMessagePayment(pattern);
for (int i = 0; i < lsMsg.size(); i++) {
lsDesc.set(1, lsMsg.get(i));
}
return lsDesc;
}
private long _genetatorTransactionId() {
long transactionId = 0;
try {
transactionId = counterLocalService.increment(PaymentFile.class.getName() + ".genetatorTransactionId");
} catch (SystemException e) {
_log.error(e);
}
return transactionId;
}
private String generatorPayURL(long groupId, long paymentFileId, String pattern,
Dossier dossier) throws IOException {
String result = StringPool.BLANK;
try {
PaymentFile paymentFile = paymentFileLocalService.getPaymentFile(paymentFileId);
PaymentConfig paymentConfig = paymentConfigLocalService.getPaymentConfigByGovAgencyCode(groupId,
dossier.getGovAgencyCode());
if (Validator.isNotNull(paymentConfig)) {
List<String> lsMessages = _putPaymentMessage(pattern);
long merchant_trans_id = _genetatorTransactionId();
JSONObject epaymentConfigJSON = JSONFactoryUtil.createJSONObject(paymentConfig.getEpaymentConfig());
String merchant_code = epaymentConfigJSON.getString("paymentMerchantCode");
String good_code = generatorGoodCode(10);
String net_cost = String.valueOf(paymentFile.getPaymentAmount());
String ship_fee = String.valueOf(0);
String tax = String.valueOf(0);
String bank_code = StringPool.BLANK;
String service_code = epaymentConfigJSON.getString("paymentServiceCode");
String version = epaymentConfigJSON.getString("paymentVersion");
String command = epaymentConfigJSON.getString("paymentCommand");
String currency_code = epaymentConfigJSON.getString("paymentCurrencyCode");
String desc_1 = StringPool.BLANK;
String desc_2 = StringPool.BLANK;
String desc_3 = StringPool.BLANK;
String desc_4 = StringPool.BLANK;
String desc_5 = StringPool.BLANK;
if (lsMessages.size() > 0) {
desc_1 = lsMessages.get(0);
desc_2 = lsMessages.get(1);
desc_3 = lsMessages.get(2);
desc_4 = lsMessages.get(3);
desc_5 = lsMessages.get(4);
if (desc_1.length() >= 20) {
desc_1 = desc_1.substring(0, 19);
}
if (desc_2.length() >= 30) {
desc_2 = desc_2.substring(0, 29);
}
if (desc_3.length() >= 40) {
desc_3 = desc_3.substring(0, 39);
}
if (desc_4.length() >= 100) {
desc_4 = desc_4.substring(0, 89);
}
if (desc_5.length() > 15) {
desc_5 = desc_5.substring(0, 15);
if (!Validator.isDigit(desc_5)) {
desc_5 = StringPool.BLANK;
}
}
}
String xml_description = StringPool.BLANK;
String current_locale = epaymentConfigJSON.getString("paymentCurrentLocale");
String country_code = epaymentConfigJSON.getString("paymentCountryCode");
String internal_bank = epaymentConfigJSON.getString("paymentInternalBank");
String merchant_secure_key = epaymentConfigJSON.getString("paymentMerchantSecureKey");
String algorithm = KeyPayTerm.VALUE_MD5;
if (epaymentConfigJSON.has("paymentHashAlgorithm")) {
algorithm = epaymentConfigJSON.getString("paymentHashAlgorithm");
}
// dossier = _getDossier(dossierId);
// TODO : update returnURL keyPay
String return_url;
_log.info("SONDT GENURL paymentReturnUrl ====================== "+ JSONFactoryUtil.looseSerialize(epaymentConfigJSON));
// return_url = epaymentConfigJSON.getString("paymentReturnUrl")+ "/" + dossier.getReferenceUid() + "/" + paymentFile.getReferenceUid();
return_url = epaymentConfigJSON.getString("paymentReturnUrl")+ "&dossierId=" + dossier.getDossierId() + "&goodCode=" + good_code + "&transId=" + merchant_trans_id + "&referenceUid=" + dossier.getReferenceUid();
_log.info("SONDT GENURL paymentReturnUrl ====================== "+ return_url);
// http://119.17.200.66:2681/web/bo-van-hoa/dich-vu-cong/#/thanh-toan-thanh-cong?paymentPortal=KEYPAY&dossierId=77603&goodCode=123&transId=555
KeyPay keypay = new KeyPay(String.valueOf(merchant_trans_id), merchant_code, good_code, net_cost,
ship_fee, tax, bank_code, service_code, version, command, currency_code, desc_1, desc_2, desc_3,
desc_4, desc_5, xml_description, current_locale, country_code, return_url, internal_bank,
merchant_secure_key, algorithm);
// keypay.setKeypay_url(paymentConfig.getKeypayDomain());
StringBuffer param = new StringBuffer();
param.append(KeyPayTerm.MERCHANT_CODE_EQ).append(URLEncoder.encode(keypay.getMerchant_code(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
// param.append(KeyPayTerm.MERCHANT_SECURE_KEY_EQ).append(URLEncoder.encode(keypay.getMerchant_secure_key(), StandardCharsets.UTF_8.name()))
// .append(StringPool.AMPERSAND);
param.append(KeyPayTerm.BANK_CODE_EQ).append(URLEncoder.encode(keypay.getBank_code(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.INTERNAL_BANK_EQ).append(URLEncoder.encode(keypay.getInternal_bank(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.MERCHANT_TRANS_ID_EQ).append(URLEncoder.encode(keypay.getMerchant_trans_id(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.GOOD_CODE_EQ).append(URLEncoder.encode(keypay.getGood_code(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.NET_COST_EQ).append(URLEncoder.encode(keypay.getNet_cost(), StandardCharsets.UTF_8.name()) )
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.SHIP_FEE_EQ).append(URLEncoder.encode(keypay.getShip_fee(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.TAX_EQ).append(URLEncoder.encode(keypay.getTax(), StandardCharsets.UTF_8.name())).append(StringPool.AMPERSAND);
param.append(KeyPayTerm.RETURN_URL_EQ).append(URLEncoder.encode(keypay.getReturn_url(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.VERSION_EQ).append(URLEncoder.encode(keypay.getVersion(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.COMMAND_EQ).append(URLEncoder.encode(keypay.getCommand(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.CURRENT_LOCALE_EQ).append(URLEncoder.encode(keypay.getCurrent_locale(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.CURRENCY_CODE_EQ).append(URLEncoder.encode(keypay.getCurrency_code(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.SERVICE_CODE_EQ).append(URLEncoder.encode(keypay.getService_code(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.COUNTRY_CODE_EQ).append(URLEncoder.encode(keypay.getCountry_code(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.DESC_1_EQ).append(URLEncoder.encode(keypay.getDesc_1(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.DESC_2_EQ).append(URLEncoder.encode(keypay.getDesc_2(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.DESC_3_EQ).append(URLEncoder.encode(keypay.getDesc_3(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.DESC_4_EQ).append(URLEncoder.encode(keypay.getDesc_4(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.DESC_5_EQ).append(URLEncoder.encode(keypay.getDesc_5(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.XML_DESCRIPTION_EQ).append(URLEncoder.encode(keypay.getXml_description(), StandardCharsets.UTF_8.name()))
.append(StringPool.AMPERSAND);
param.append(KeyPayTerm.SECURE_HASH_EQ).append(keypay.getSecure_hash());
result = epaymentConfigJSON.getString(KeyPayTerm.PAYMENTKEYPAYDOMAIN) + StringPool.QUESTION + param.toString();
}
} catch (NoSuchPaymentFileException e) {
_log.debug(e);
} catch (Exception e) {
_log.debug(e);
}
return result;
}
private Map<String, Object> createParamsInvoice(PaymentFile oldPaymentFile, Dossier dossier, int intpaymentMethod) {
Map<String, Object> params = new HashMap<>();
StringBuilder address = new StringBuilder();
address.append(dossier.getAddress());address.append(", ");
address.append(dossier.getWardName());address.append(", ");
address.append(dossier.getDistrictName());address.append(", ");
address.append(dossier.getCityName());
SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
String dateformatted = sdf.format(new Date());
_log.info("SONDT CINVOICE DATEFORMATED ============= " + dateformatted);
params.put(Field.USER_NAME, StringPool.BLANK);
params.put(CInvoiceTerm.secret, String.valueOf(1));
params.put(CInvoiceTerm.soid, String.valueOf(0));
params.put(CInvoiceTerm.maHoadon, StringPool.BLANK);
params.put(CInvoiceTerm.ngayHd, dateformatted); //"01/08/2018"
params.put(CInvoiceTerm.seri, String.valueOf(12314));
params.put(CInvoiceTerm.maNthue, "01");
params.put(CInvoiceTerm.kieuSo, "G");
params.put(CInvoiceTerm.maKhackHang, Long.toString(dossier.getUserId()));
params.put(CInvoiceTerm.ten, dossier.getApplicantName());
params.put(CInvoiceTerm.phone, dossier.getContactTelNo());
if(dossier.getApplicantIdType().contentEquals("business")) {
params.put(CInvoiceTerm.tax, dossier.getApplicantIdNo());
} else {
params.put(CInvoiceTerm.tax, StringPool.BLANK);
}
params.put(CInvoiceTerm.dchi, address);
params.put(CInvoiceTerm.maTk, StringPool.BLANK);
params.put(CInvoiceTerm.tenNh, StringPool.BLANK);
params.put(CInvoiceTerm.mailH, GetterUtil.getString(dossier.getContactEmail()));
params.put(CInvoiceTerm.phoneH, GetterUtil.getString(dossier.getContactTelNo()));
params.put(CInvoiceTerm.tenM, GetterUtil.getString(dossier.getDelegateName()));
params.put(CInvoiceTerm.maKhL, "K");
params.put(CInvoiceTerm.maNt, "VND");
params.put(CInvoiceTerm.tg, String.valueOf(1));
if(intpaymentMethod == 3) {
params.put(CInvoiceTerm.hthuc, CInvoiceTerm.hthuc_M);
}else {
params.put(CInvoiceTerm.hthuc, CInvoiceTerm.hthuc_C);
}
params.put(CInvoiceTerm.han, StringPool.BLANK);
params.put(CInvoiceTerm.tlGgia, String.valueOf(0));
params.put(CInvoiceTerm.ggia, String.valueOf(0));
params.put(CInvoiceTerm.phi, String.valueOf(0));
params.put(CInvoiceTerm.noidung, dossier.getDossierNo());
params.put(CInvoiceTerm.tien, Long.toString(oldPaymentFile.getPaymentAmount()));
params.put(CInvoiceTerm.ttoan, Long.toString(oldPaymentFile.getPaymentAmount()));
params.put(CInvoiceTerm.maVtDetail, dossier.getDossierNo());
params.put(CInvoiceTerm.tenDetail, GetterUtil.getString(dossier.getServiceName()));
params.put(CInvoiceTerm.dvtDetail, "bo");
params.put(CInvoiceTerm.luongDetail, String.valueOf(1));
params.put(CInvoiceTerm.giaDetail, Long.toString(oldPaymentFile.getPaymentAmount()));
params.put(CInvoiceTerm.tienDetail, Long.toString(oldPaymentFile.getPaymentAmount()));
params.put(CInvoiceTerm.tsDetail, String.valueOf(0));
params.put(CInvoiceTerm.thueDetail, String.valueOf(0));
params.put(CInvoiceTerm.ttoanDetail, Long.toString(oldPaymentFile.getPaymentAmount()));
return params;
}
private int checkPaymentMethodinPrecondition(String preCondition) {
int paymentMethod = 0;
String[] preConditions = StringUtil.split(preCondition);
for(String pre : preConditions) {
pre = pre.trim();
if (pre.toLowerCase().contains(KeyPayTerm.PAYMENTMETHOD_EQ)) {
String[] splitPaymentMethod = pre.split(StringPool.EQUAL);
if (splitPaymentMethod.length == 2) {
paymentMethod = Integer.parseInt(splitPaymentMethod[1]);
}
break;
}
}
return paymentMethod;
}
private String checkPaymentMethod(int mt) {
String pmMethod = StringPool.BLANK;
if (mt == 1) {
pmMethod = KeyPayTerm.PM_METHOD_1; //KeyPay
} else if (mt == 2) {
pmMethod = KeyPayTerm.PM_METHOD_2;
} else if (mt == 3) {
pmMethod = KeyPayTerm.PM_METHOD_3;
}
return pmMethod;
}
private JSONObject getStatusText(long groupId, String collectionCode, String curStatus, String curSubStatus) {
JSONObject jsonData = null;
DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(collectionCode, groupId);
if (Validator.isNotNull(dc) && Validator.isNotNull(curStatus)) {
jsonData = JSONFactoryUtil.createJSONObject();
DictItem it = DictItemLocalServiceUtil.fetchByF_dictItemCode(curStatus, dc.getPrimaryKey(), groupId);
if (Validator.isNotNull(it)) {
jsonData.put(curStatus, it.getItemName());
if (Validator.isNotNull(curSubStatus)) {
DictItem dItem = DictItemLocalServiceUtil.fetchByF_dictItemCode(curSubStatus, dc.getPrimaryKey(),
groupId);
if (Validator.isNotNull(dItem)) {
jsonData.put(curSubStatus, dItem.getItemName());
}
}
}
}
return jsonData;
}
private int getActionDueDate(long groupId, long dossierId, String refId, long processActionId) {
return 0;
}
protected String getDictItemName(long groupId, String collectionCode, String itemCode) {
DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(collectionCode, groupId);
if (Validator.isNotNull(dc)) {
DictItem it = DictItemLocalServiceUtil.fetchByF_dictItemCode(itemCode, dc.getPrimaryKey(), groupId);
if(Validator.isNotNull(it)){
return it.getItemName();
}else{
return StringPool.BLANK;
}
} else {
return StringPool.BLANK;
}
}
private void updateStatus(Dossier dossier, String status, String statusText, String subStatus,
String subStatusText, String lockState, String stepInstruction, ServiceContext context)
throws PortalException {
Date now = new Date();
dossier.setModifiedDate(now);
dossier.setDossierStatus(status);
dossier.setDossierStatusText(statusText);
dossier.setDossierSubStatus(subStatus);
dossier.setDossierSubStatusText(subStatusText);
if (dossier != null && !DossierTerm.PAUSE_OVERDUE_LOCK_STATE.equals(dossier.getLockState())) {
dossier.setLockState(lockState);
}
dossier.setDossierNote(stepInstruction);
// if (status.equalsIgnoreCase(DossierStatusConstants.RELEASING)) {
// dossier.setReleaseDate(now);
// }
//
// if (status.equalsIgnoreCase(DossierStatusConstants.DONE)) {
// dossier.setFinishDate(now);
// }
}
private Map<String, Boolean> updateProcessingDate(DossierAction dossierAction, DossierAction prevAction, ProcessStep processStep, Dossier dossier, String curStatus, String curSubStatus, String prevStatus,
int dateOption,
ProcessOption option,
ServiceProcess serviceProcess,
ServiceContext context) {
Date now = new Date();
Map<String, Boolean> bResult = new HashMap<>();
LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();
params.put(DossierTerm.GOV_AGENCY_CODE, dossier.getGovAgencyCode());
params.put(DossierTerm.SERVICE_CODE, dossier.getServiceCode());
params.put(DossierTerm.DOSSIER_TEMPLATE_NO, dossier.getDossierTemplateNo());
params.put(DossierTerm.DOSSIER_STATUS, StringPool.BLANK);
// ServiceProcess serviceProcess = null;
//
// long serviceProcessId = (option != null ? option.getServiceProcessId() : prevAction.getServiceProcessId());
// serviceProcess = ServiceProcessLocalServiceUtil.fetchServiceProcess(serviceProcessId);
// if ((Validator.isNull(prevStatus) && DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus)
// && (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA))
if ((DossierTerm.DOSSIER_STATUS_RECEIVING.equals(curStatus) || DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus))
&& dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) {
try {
if (Validator.isNotNull(option) && Validator.isNull(dossier.getDossierNo())
&& dossier.getOriginDossierId() > 0) {
String dossierRef = DossierNumberGenerator.generateDossierNumber(dossier.getGroupId(), dossier.getCompanyId(),
dossier.getDossierId(), option.getProcessOptionId(), serviceProcess.getDossierNoPattern(), params);
dossier.setDossierNo(dossierRef.trim());
// DossierLocalServiceUtil.updateDossier(dossier);
bResult.put(DossierTerm.DOSSIER_NO, true);
}
} catch (PortalException e) {
_log.debug(e);
//_log.error(e);
// e.printStackTrace();
}
}
if ((DossierTerm.DOSSIER_STATUS_NEW.equals(prevStatus)
&& DossierTerm.DOSSIER_STATUS_RECEIVING.equals(curStatus)) ||
(dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA && DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus))) {
// try {
// DossierLocalServiceUtil.updateSubmittingDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context);
if (Validator.isNull(dossier.getSubmitDate())) {
dossier.setSubmitDate(now);
bResult.put(DossierTerm.SUBMIT_DATE, true);
}
// } catch (PortalException e) {
// _log.error(e);
// e.printStackTrace();
// }
}
if (dossier.getOriginality() != DossierTerm.ORIGINALITY_DVCTT &&
((DossierTerm.DOSSIER_STATUS_PROCESSING.equals(curStatus) && dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG)
|| (DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus) && dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA)
|| (DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus) && dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG)
|| (dateOption == DossierTerm.DATE_OPTION_TWO))
&& dossier.getReceiveDate() == null) {
// try {
// DossierLocalServiceUtil.updateReceivingDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context);
dossier.setReceiveDate(now);
bResult.put(DossierTerm.RECEIVE_DATE, true);
Double durationCount = serviceProcess.getDurationCount();
int durationUnit = serviceProcess.getDurationUnit();
Date dueDate = null;
if (Validator.isNotNull(durationCount) && durationCount > 0
&& !areEqualDouble(durationCount, 0.00d, 3)) {
// dueDate = HolidayUtils.getDueDate(now, durationCount, durationUnit, dossier.getGroupId());
DueDateUtils dueDateUtils = new DueDateUtils(now, durationCount, durationUnit, dossier.getGroupId());
dueDate = dueDateUtils.getDueDate();
}
if (Validator.isNotNull(dueDate)) {
dossier.setDueDate(dueDate);
// DossierLocalServiceUtil.updateDueDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), dueDate, context);
bResult.put(DossierTerm.DUE_DATE, true);
}
dossier.setDurationCount(durationCount);
dossier.setDurationUnit(durationUnit);
if (dossier.getCounter() == 0 && Validator.isNotNull(dossier.getRegisterBookCode())) {
long counterCode = DossierNumberGenerator.countByRegiterBookCode(dossier.getGroupId(),
dossier.getRegisterBookCode());
dossier.setCounter(counterCode);
}
if (Validator.isNull(dossier.getDossierNo())) {
try {
String dossierRef = DossierNumberGenerator.generateDossierNumber(dossier.getGroupId(), dossier.getCompanyId(),
dossier.getDossierId(), option.getProcessOptionId(), serviceProcess.getDossierNoPattern(), params);
dossier.setDossierNo(dossierRef.trim());
} catch (Exception e) {
_log.debug(e);
}
}
if (Validator.isNull(dossier.getDossierCounter()) && Validator.isNotNull(serviceProcess.getCounterCode())) {
ConfigCounter counterConfig = ConfigCounterLocalServiceUtil.fetchByCountrCode(dossier.getGroupId(),
serviceProcess.getCounterCode());
if (counterConfig != null) {
if (Validator.isNotNull(counterConfig.getStartCounter()) && counterConfig.getStartCounter() > 0) {
String patternCode = counterConfig.getPatternCode();
try {
_log.info("dossierId: " + dossier.getDossierId() + "| option.getProcessOptionId(): "
+ option.getProcessOptionId() + "| serviceProcess.getCounterCode(): "
+ serviceProcess.getCounterCode() + "| getStartCounter(): "
+ counterConfig.getStartCounter());
String dossierCounter = ConfigCounterNumberGenerator.generateCounterNumber(dossier.getGroupId(),
dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(),
patternCode, counterConfig, params);
dossier.setDossierCounter(dossierCounter.trim());
_log.info("dossierCounter: " + dossierCounter);
} catch (Exception e) {
_log.debug(e);
}
} else {
String patternCode = counterConfig.getPatternCode();
try {
_log.info("dossierId: " + dossier.getDossierId() + "| option.getProcessOptionId(): "
+ option.getProcessOptionId() + "| serviceProcess.getCounterCode(): "
+ serviceProcess.getCounterCode());
String dossierCounter = ConfigCounterNumberGenerator.generateCounterNumber(dossier.getGroupId(),
dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(),
patternCode, counterConfig, params);
dossier.setDossierCounter(dossierCounter.trim());
_log.info("dossierCounter: " + dossierCounter);
} catch (Exception e) {
_log.debug(e);
}
}
}
}
}
//Update counter and dossierNo
if (dateOption == DossierTerm.DATE_OPTION_TWO || dateOption == DossierTerm.DATE_OPTION_TEN) {
if (dossier.getCounter() == 0 && Validator.isNotNull(dossier.getRegisterBookCode())) {
long counterCode = DossierNumberGenerator.countByRegiterBookCode(dossier.getGroupId(),
dossier.getRegisterBookCode());
dossier.setCounter(counterCode);
}
if (Validator.isNull(dossier.getDossierNo())) {
try {
String dossierRef = DossierNumberGenerator.generateDossierNumber(dossier.getGroupId(), dossier.getCompanyId(),
dossier.getDossierId(), option.getProcessOptionId(), serviceProcess.getDossierNoPattern(),
params);
dossier.setDossierNo(dossierRef.trim());
} catch (Exception e) {
_log.debug(e);
}
}
if (Validator.isNull(dossier.getDossierCounter()) && Validator.isNotNull(serviceProcess.getCounterCode())) {
ConfigCounter counterConfig = ConfigCounterLocalServiceUtil.fetchByCountrCode(dossier.getGroupId(),
serviceProcess.getCounterCode());
if (counterConfig != null) {
if (Validator.isNotNull(counterConfig.getStartCounter()) && counterConfig.getStartCounter() > 0) {
String patternCode = counterConfig.getPatternCode();
try {
_log.info("dossierId: " + dossier.getDossierId() + "| option.getProcessOptionId(): "
+ option.getProcessOptionId() + "| serviceProcess.getCounterCode(): "
+ serviceProcess.getCounterCode() + "| getStartCounter(): "
+ counterConfig.getStartCounter());
String dossierCounter = ConfigCounterNumberGenerator.generateCounterNumber(dossier.getGroupId(),
dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(),
patternCode, counterConfig, params);
dossier.setDossierCounter(dossierCounter.trim());
_log.info("dossierCounter: " + dossierCounter);
} catch (Exception e) {
_log.debug(e);
}
} else {
String patternCode = counterConfig.getPatternCode();
try {
_log.info("dossierId: " + dossier.getDossierId() + "| option.getProcessOptionId(): "
+ option.getProcessOptionId() + "| serviceProcess.getCounterCode(): "
+ serviceProcess.getCounterCode());
String dossierCounter = ConfigCounterNumberGenerator.generateCounterNumber(dossier.getGroupId(),
dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(),
patternCode, counterConfig, params);
dossier.setDossierCounter(dossierCounter.trim());
_log.info("dossierCounter: " + dossierCounter);
} catch (Exception e) {
_log.debug(e);
}
}
}
}
}
if (DossierTerm.DOSSIER_STATUS_RECEIVING.equals(prevStatus) && DossierTerm.DOSSIER_STATUS_PROCESSING.equals(curStatus)) {
// try {
// DossierLocalServiceUtil.updateProcessDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context);
dossier.setProcessDate(now);
bResult.put(DossierTerm.PROCESS_DATE, true);
// } catch (PortalException e) {
// _log.error(e);
// e.printStackTrace();
// }
}
// if (DossierTerm.DOSSIER_STATUS_RELEASING.equals(curStatus)
// || DossierTerm.DOSSIER_STATUS_DENIED.equals(curStatus)
// || DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus)
// || DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus)
// || DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)) {
if (DossierTerm.DOSSIER_STATUS_RELEASING.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus)
|| (dateOption == 4)
) {
if (Validator.isNull(dossier.getReleaseDate())) {
// try {
// DossierLocalServiceUtil.updateReleaseDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context);
dossier.setReleaseDate(now);
if (OpenCPSConfigUtil.isAutoBetimes()) {
int valueCompareRelease = BetimeUtils.getValueCompareRelease(dossier.getGroupId(), now, dossier.getDueDate());
if (3 == valueCompareRelease) {
dossier.setExtendDate(now);
}
}
bResult.put(DossierTerm.RELEASE_DATE, true);
// } catch (PortalException e) {
// _log.error(e);
// e.printStackTrace();
// }
}
}
// _log.info("========STEP DUE CUR STATUS: " + curStatus);
if (DossierTerm.DOSSIER_STATUS_DENIED.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)) {
// _log.info("========STEP DUE CUR STATUS UPDATING STATE DONE");
// dossierAction.setState(DossierActionTerm.STATE_ALREADY_PROCESSED);
// dossierAction.setModifiedDate(new Date());
dossierAction = dossierActionLocalService.updateState(dossierAction.getDossierActionId(), DossierActionTerm.STATE_ALREADY_PROCESSED);
}
//Check verification
if (DossierTerm.DOSSIER_STATUS_DONE.contentEquals(curStatus)) {
Applicant checkApplicant = ApplicantLocalServiceUtil.fetchByMappingID(dossier.getUserId());
if (checkApplicant != null && dossier.getOriginality() == DossierTerm.ORIGINALITY_DVCTT) {
if (checkApplicant.getVerification() == ApplicantTerm.LOCKED || checkApplicant.getVerification() == ApplicantTerm.LOCKED_DOSSIER) {
checkApplicant.setVerification(ApplicantTerm.UNLOCKED);
ApplicantLocalServiceUtil.updateApplicant(checkApplicant);
}
}
}
// if (DossierTerm.DOSSIER_STATUS_DENIED.equals(curStatus)
// || DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus)
// || DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus)
// || DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)) {
if (DossierTerm.DOSSIER_STATUS_DENIED.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus)
|| (dateOption == 5)) {
if (Validator.isNull(dossier.getFinishDate())) {
// try {
// DossierLocalServiceUtil.updateFinishDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context);
dossier.setFinishDate(now);
bResult.put(DossierTerm.FINISH_DATE, true);
// dossierAction.setState(DossierActionTerm.STATE_ALREADY_PROCESSED);
// dossierAction.setModifiedDate(new Date());
dossierAction = dossierActionLocalService.updateState(dossierAction.getDossierActionId(), DossierActionTerm.STATE_ALREADY_PROCESSED);
// } catch (PortalException e) {
// _log.error(e);
// e.printStackTrace();
// }
}
if (Validator.isNull(dossier.getReleaseDate())) {
// try {
// DossierLocalServiceUtil.updateReleaseDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context);
dossier.setReleaseDate(now);
if (OpenCPSConfigUtil.isAutoBetimes()) {
int valueCompareRelease = BetimeUtils.getValueCompareRelease(dossier.getGroupId(), now, dossier.getDueDate());
if (3 == valueCompareRelease) {
dossier.setExtendDate(now);
}
}
bResult.put(DossierTerm.RELEASE_DATE, true);
// } catch (PortalException e) {
// _log.error(e);
// e.printStackTrace();
// }
}
}
if (DossierTerm.DOSSIER_STATUS_PROCESSING.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_INTEROPERATING.equals(curStatus)
|| DossierTerm.DOSSIER_STATUS_WAITING.equals(curStatus)) {
if (Validator.isNotNull(dossier.getFinishDate())) {
dossier.setFinishDate(null);
bResult.put(DossierTerm.FINISH_DATE, true);
}
if (Validator.isNotNull(dossier.getReleaseDate())) {
dossier.setReleaseDate(null);
bResult.put(DossierTerm.RELEASE_DATE, true);
}
}
if (DossierTerm.DOSSIER_STATUS_RECEIVING.equals(prevStatus)) {
bResult.put(DossierTerm.DOSSIER_NO, true);
bResult.put(DossierTerm.RECEIVE_DATE, true);
bResult.put(DossierTerm.PROCESS_DATE, true);
bResult.put(DossierTerm.RELEASE_DATE, true);
bResult.put(DossierTerm.FINISH_DATE, true);
}
if (DossierTerm.DOSSIER_STATUS_NEW.equals(prevStatus) && dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG
&& Validator.isNotNull(dossier.getReceiveDate())) {
bResult.put(DossierTerm.RECEIVE_DATE, true);
}
if (DossierTerm.DOSSIER_STATUS_RECEIVING.contentEquals(dossier.getDossierStatus()) && dossier.getOriginality() == DossierTerm.ORIGINALITY_DVCTT) {
Applicant checkApplicant = ApplicantLocalServiceUtil.fetchByMappingID(dossier.getUserId());
if (checkApplicant != null) {
int countDossier = DossierLocalServiceUtil.countByG_UID_DS(dossier.getGroupId(), dossier.getUserId(), DossierTerm.DOSSIER_STATUS_RECEIVING);
_log.debug("APPLICANT NUMBER OF CREATE DOSSIER: " + countDossier);
if (countDossier >= DossierTerm.MAX_DOSSIER_WITHOUT_VERIFICATION) {
if (checkApplicant.getVerification() != ApplicantTerm.UNLOCKED) {
checkApplicant.setVerification(ApplicantTerm.LOCKED_DOSSIER);
ApplicantLocalServiceUtil.updateApplicant(checkApplicant);
}
}
}
}
//int dateOption = actionConfig.getDateOption();
_log.debug("dateOption: "+dateOption);
if (dateOption == DossierTerm.DATE_OPTION_CAL_WAITING) {
DossierAction dActEnd = dossierActionLocalService
.fetchDossierAction(dossierAction.getDossierActionId());
// DossierAction dActEnd = dossierAction;
if (dActEnd != null && dossier.getDurationCount() > 0) {
_log.debug("dActEnd.getPreviousActionId(): "+dActEnd.getPreviousActionId());
DossierAction dActPrevious = dossierActionLocalService
.fetchDossierAction(dActEnd.getPreviousActionId());
// DossierAction dActStart = prevAction;
if (dActPrevious != null) {
ActionConfig actPrevious = ActionConfigLocalServiceUtil.getByCode(dActPrevious.getGroupId(),
dActPrevious.getActionCode());
_log.debug("actPrevious: "+actPrevious.getDateOption());
long createEnd = dActEnd.getCreateDate().getTime();
long createStart = 0;
if (actPrevious != null && actPrevious.getDateOption() != 1) {
createStart = dActPrevious.getCreateDate().getTime();
} else {
List<DossierAction> dActionList = DossierActionLocalServiceUtil
.findByG_DID(dActEnd.getGroupId(), dActEnd.getDossierId());
if (dActionList != null && dActionList.size() > 1) {
int lengthAction = dActionList.size();
for (int i = lengthAction - 2; i >= 0; i--) {
DossierAction dAction = dActionList.get(i);
_log.debug("dAction: "+i+": "+dAction);
ActionConfig actDetail = ActionConfigLocalServiceUtil.getByCode(dAction.getGroupId(),
dAction.getActionCode());
_log.debug("actDetail: "+i+": "+actDetail.getDateOption());
if (actDetail.getDateOption() == 1) {
createStart = dAction.getCreateDate().getTime();
} else {
break;
}
}
}
}
_log.debug("createStart: "+createStart);
_log.debug("createEnd: "+createEnd);
if (createEnd > createStart) {
DueDateUtils dueDateUtils = new DueDateUtils(new Date(createStart), new Date(createEnd), 1, dActEnd.getGroupId());
//long extendDateTimeStamp = ExtendDueDateUtils.getTimeWaitingByHoliday(createStart, createEnd, dossier.getGroupId());
long extendDateTimeStamp = dueDateUtils.getOverDue();
_log.debug("extendDateTimeStamp: "+extendDateTimeStamp);
if (extendDateTimeStamp > 0) {
double hoursCount = extendDateTimeStamp * 1.0 / (1000 * 60 * 60);
_log.debug("hoursCount: "+hoursCount);
//_log.info("dossier.getExtendDate(): "+dossier.getExtendDate());
// List<Holiday> holidayList = HolidayLocalServiceUtil
// .getHolidayByGroupIdAndType(dossier.getGroupId(), 0);
// List<Holiday> extendWorkDayList = HolidayLocalServiceUtil
// .getHolidayByGroupIdAndType(dossier.getGroupId(), 1);
//Date dueDateExtend = HolidayUtils.getEndDate(dossier.getGroupId(),
// dossier.getDueDate(), hoursCount, holidayList,
// extendWorkDayList);
//
DueDateUtils dateUtils = new DueDateUtils(dossier.getDueDate(),
hoursCount, 1, dossier.getGroupId());
Date dueDateExtend = dateUtils.getDueDate();
_log.debug("dueDateExtend: "+dueDateExtend);
if (dueDateExtend != null) {
dossier.setDueDate(dueDateExtend);
//dossier.setCorrecttingDate(null);
bResult.put(DossierTerm.DUE_DATE, true);
}
}
}
}
} else if (dossier.getDurationCount() <= 0) {
dossier.setDueDate(null);
}
} else if (dateOption == DossierTerm.DATE_OPTION_CHANGE_DUE_DATE) {
if (dossier.getDueDate() != null) {
//dossier.setCorrecttingDate(dossier.getDueDate());
//dossier.setDueDate(null);
dossier.setLockState(DossierTerm.PAUSE_STATE);
}
}
else if (dateOption == DossierTerm.DATE_OPTION_RESET_DUE_DATE) {
if (dossier != null && !DossierTerm.PAUSE_OVERDUE_LOCK_STATE.equals(dossier.getLockState())) {
dossier.setLockState(StringPool.BLANK);
}
if (dossier.getDueDate() != null) {
if (serviceProcess != null) {
// Date newDueDate = HolidayUtils.getDueDate(new Date(),
// serviceProcess.getDurationCount(),
// serviceProcess.getDurationUnit(), dossier.getGroupId());
DueDateUtils dueDateUtils = new DueDateUtils(new Date(),
serviceProcess.getDurationCount(),
serviceProcess.getDurationUnit(), dossier.getGroupId());
Date newDueDate = dueDateUtils.getDueDate();
if (newDueDate != null) {
//dossier.setReceiveDate(new Date());
dossier.setDueDate(newDueDate);
bResult.put(DossierTerm.DUE_DATE, true);
}
}
}
}
else if (dateOption == DossierTerm.DATE_OPTION_PAUSE_OVERDUE) {
if (dossier.getDueDate() != null) {
dossier.setLockState(DossierTerm.PAUSE_OVERDUE_LOCK_STATE);
}
} else if ((dateOption == DossierTerm.DATE_OPTION_DUEDATE_PHASE_1
|| dateOption == DossierTerm.DATE_OPTION_DUEDATE_PHASE_2
|| dateOption == DossierTerm.DATE_OPTION_DUEDATE_PHASE_3)
&& serviceProcess != null) {
DueDatePhaseUtil dueDatePharse = new DueDatePhaseUtil(dossier.getGroupId(), new Date(), dateOption, serviceProcess.getDueDatePattern());
dossier.setDueDate(dueDatePharse.getDueDate());
bResult.put(DossierTerm.DUE_DATE, true);
dossier = setDossierNoNDueDate(dossier, serviceProcess, option, true, false, null, params);
} else //Update counter and dossierNo
if (dateOption == DossierTerm.DATE_OPTION_TWO || dateOption == DossierTerm.DATE_OPTION_TEN) {
/**
* THANHNV create common init DueDate DossierNo DossierCounter
if (dossier.getCounter() == 0 && Validator.isNotNull(dossier.getRegisterBookCode())) {
long counterCode = DossierNumberGenerator.countByRegiterBookCode(dossier.getGroupId(),
dossier.getRegisterBookCode());
dossier.setCounter(counterCode);
}
if (Validator.isNull(dossier.getDossierNo())) {
try {
String dossierRef = DossierNumberGenerator.generateDossierNumber(dossier.getGroupId(), dossier.getCompanyId(),
dossier.getDossierId(), option.getProcessOptionId(), serviceProcess.getDossierNoPattern(),
params);
dossier.setDossierNo(dossierRef.trim());
} catch (Exception e) {
_log.debug(e);
}
}
if (Validator.isNull(dossier.getDossierCounter()) && Validator.isNotNull(serviceProcess.getCounterCode())) {
ConfigCounter counterConfig = ConfigCounterLocalServiceUtil.fetchByCountrCode(dossier.getGroupId(),
serviceProcess.getCounterCode());
if (counterConfig != null) {
if (Validator.isNotNull(counterConfig.getStartCounter()) && counterConfig.getStartCounter() > 0) {
String patternCode = counterConfig.getPatternCode();
try {
_log.info("dossierId: " + dossier.getDossierId() + "| option.getProcessOptionId(): "
+ option.getProcessOptionId() + "| serviceProcess.getCounterCode(): "
+ serviceProcess.getCounterCode() + "| getStartCounter(): "
+ counterConfig.getStartCounter());
String dossierCounter = ConfigCounterNumberGenerator.generateCounterNumber(dossier.getGroupId(),
dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(),
patternCode, counterConfig, params);
dossier.setDossierCounter(dossierCounter.trim());
_log.info("dossierCounter: " + dossierCounter);
} catch (Exception e) {
_log.debug(e);
}
} else {
String patternCode = counterConfig.getPatternCode();
try {
_log.info("dossierId: " + dossier.getDossierId() + "| option.getProcessOptionId(): "
+ option.getProcessOptionId() + "| serviceProcess.getCounterCode(): "
+ serviceProcess.getCounterCode());
String dossierCounter = ConfigCounterNumberGenerator.generateCounterNumber(dossier.getGroupId(),
dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(),
patternCode, counterConfig, params);
dossier.setDossierCounter(dossierCounter.trim());
_log.info("dossierCounter: " + dossierCounter);
} catch (Exception e) {
_log.debug(e);
}
}
}
}
THANHNV: end
*/
dossier = setDossierNoNDueDate(dossier, serviceProcess, option, true, false, null, params);
}
//Check if dossier is done
if (DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)) {
List<DossierFile> lstFiles = dossierFileLocalService.getAllDossierFile(dossier.getDossierId());
int countTemplateNo = 0;
for (DossierFile df : lstFiles) {
//GS. Ta Tuan Anh
if (!df.getRemoved()) {
df.setOriginal(true);
}
dossierFileLocalService.updateDossierFile(df);
//GS. DuanTV ApplicantData
if (Validator.isNotNull(df.getFileTemplateNo())) {
countTemplateNo++;
}
}
String[] fileTemplateNos = new String[countTemplateNo];
DossierFile[] files = new DossierFile[countTemplateNo];
int count = 0;
for (DossierFile df : lstFiles) {
if (Validator.isNotNull(df.getFileTemplateNo())) {
files[count] = df;
fileTemplateNos[count++] = df.getFileTemplateNo();
}
}
List<FileItem> lstFileItems = FileItemLocalServiceUtil.findByG_FTNS(dossier.getGroupId(), fileTemplateNos);
for (int i = 0; i < lstFileItems.size(); i++) {
FileItem item = lstFileItems.get(i);
try {
ApplicantDataLocalServiceUtil.updateApplicantData(context, dossier.getGroupId(),
item.getFileTemplateNo(),
files[i].getDisplayName(),
files[i].getFileEntryId(),
StringPool.BLANK,
ApplicantDataTerm.STATUS_ACTIVE,
dossier.getApplicantIdNo(),
1,
dossier.getDossierNo(),
StringPool.BLANK);
} catch (SystemException e) {
_log.debug(e);
} catch (PortalException e) {
_log.debug(e);
}
}
}
//Calculate step due date
// DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId());
// _log.info("dossierAction: "+dossierAction);
dossierAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId());
Date rootDate = now;
Date dueDate = null;
// if (prevAction != null) {
// if (prevAction.getDueDate() != null) {
// if (rootDate.getTime() < prevAction.getDueDate().getTime()) {
// rootDate = prevAction.getDueDate();
// }
// }
// }
Double durationCount = processStep.getDurationCount();
// _log.info("durationCountStep: "+durationCount);
int durationUnit = serviceProcess.getDurationUnit();
// _log.info("Calculate do action duration count: " + durationCount);
if (Validator.isNotNull(durationCount) && durationCount > 0
&& !areEqualDouble(durationCount, 0.00d, 3)) {
// _log.info("========STEP DUE DATE CACULATE DUE DATE");
DueDateUtils dueDateUtils = new DueDateUtils(rootDate, durationCount, durationUnit, dossier.getGroupId());
// dueDate = HolidayUtils.getDueDate(rootDate, durationCount, durationUnit, dossier.getGroupId());
dueDate = dueDateUtils.getDueDate();
// _log.info("dueDateAction: "+dueDate);
}
// _log.info("========STEP DUE DATE:" + dueDate);
// DossierLocalServiceUtil.updateDossier(dossier);
// _log.info("dossierAction: " + dossierAction);
if (dossierAction != null) {
// _log.info("========STEP DUE DATE ACTION:" + dueDate);
if (dueDate != null) {
long dateNowTimeStamp = now.getTime();
Long dueDateTimeStamp = dueDate.getTime();
int overdue = 0;
// _log.info("dueDateTEST: "+dueDate);
// _log.info("Due date timestamp: " + dueDateTimeStamp);
if (dueDateTimeStamp != null && dueDateTimeStamp > 0) {
long subTimeStamp = dueDateTimeStamp - dateNowTimeStamp;
if (subTimeStamp > 0) {
overdue = calculatorOverDue(durationUnit, subTimeStamp);
// overdue = calculatorOverDue(durationUnit, subTimeStamp, dateNowTimeStamp, dueDateTimeStamp,
// dossierAction.getGroupId(), true);
} else {
overdue = -calculatorOverDue(durationUnit, subTimeStamp);
//// calculatorOverDue(int durationUnit, long subTimeStamp, long releaseDateTimeStamp,
//// long dueDateTimeStamp, long groupId, true);
// overdue = -calculatorOverDue(durationUnit, subTimeStamp, dateNowTimeStamp, dueDateTimeStamp,
// dossierAction.getGroupId(), true);
}
} else {
}
// _log.info("dueDateTEST111: "+dueDate);
dossierAction.setActionOverdue(overdue);
dossierAction.setDueDate(dueDate);
// _log.info("========STEP DUE DATE SET DUE DATE: " + dossierAction.getStepCode());
// DossierAction dActTest = DossierActionLocalServiceUtil.updateDossierAction(dossierAction);
dossierActionLocalService.updateDossierAction(dossierAction);
// _log.info("dActTest: "+dActTest);
}
else {
dossierActionLocalService.updateDossierAction(dossierAction);
}
}
return bResult;
}
public static boolean areEqualDouble(double a, double b, int precision) {
return Math.abs(a - b) <= Math.pow(10, -precision);
}
private static int calculatorOverDue(int durationUnit, long subTimeStamp) {
if (subTimeStamp < 0) {
subTimeStamp = Math.abs(subTimeStamp);
}
double dueCount;
double overDue;
int retval = Double.compare(durationUnit, 1.0);
if (retval < 0) {
dueCount = (double) subTimeStamp / VALUE_CONVERT_DATE_TIMESTAMP;
double subDueCount = (double) Math.round(dueCount * 100) / 100;
overDue = (double) Math.ceil(subDueCount * 4) / 4;
return (int)overDue;
} else {
dueCount = (double) subTimeStamp / VALUE_CONVERT_HOUR_TIMESTAMP;
overDue = (double) Math.round(dueCount);
}
return (int)overDue;
}
private JSONObject processMergeDossierFormData(Dossier dossier, JSONObject jsonData) {
jsonData.put(DossierTerm.GOV_AGENCY_CODE, dossier.getGovAgencyCode());
jsonData.put(DossierTerm.GOV_AGENCY_NAME, dossier.getGovAgencyName());
jsonData.put(DossierTerm.APPLICANT_ID_NO, dossier.getApplicantIdNo());
jsonData.put(DossierTerm.APPLICANT_ID_TYPE, dossier.getApplicantIdType());
jsonData.put(DossierTerm.APPLICANT_ID_DATE,
APIDateTimeUtils.convertDateToString(dossier.getApplicantIdDate(), APIDateTimeUtils._NORMAL_PARTTERN));
jsonData.put(DossierTerm.CITY_CODE, dossier.getCityCode());
jsonData.put(DossierTerm.CITY_NAME, dossier.getCityName());
jsonData.put(DossierTerm.DISTRICT_CODE, dossier.getDistrictCode());
jsonData.put(DossierTerm.DISTRICT_NAME, dossier.getDistrictName());
jsonData.put(DossierTerm.WARD_CODE, dossier.getWardCode());
jsonData.put(DossierTerm.WARD_NAME, dossier.getWardName());
jsonData.put(DossierTerm.DOSSIER_NO, dossier.getDossierNo());
jsonData.put(DossierTerm.APPLICANT_NAME, dossier.getApplicantName());
jsonData.put(DossierTerm.ADDRESS, dossier.getAddress());
jsonData.put(DossierTerm.CONTACT_TEL_NO, dossier.getContactTelNo());
jsonData.put(DossierTerm.CONTACT_EMAIL, dossier.getContactEmail());
jsonData.put(DossierTerm.CONTACT_NAME, dossier.getContactName());
jsonData.put(DossierTerm.DELEGATE_ADDRESS, dossier.getDelegateAddress());
jsonData.put(DossierTerm.SERVICE_CODE, dossier.getServiceCode());
jsonData.put(DossierTerm.SERVICE_NAME, dossier.getServiceName());
jsonData.put(DossierTerm.SAMPLE_COUNT, dossier.getSampleCount());
jsonData.put(DossierTerm.DURATION_UNIT, dossier.getDurationUnit());
jsonData.put(DossierTerm.DURATION_COUNT, dossier.getDurationCount());
jsonData.put(DossierTerm.SECRET_KEY, dossier.getPassword());
jsonData.put(DossierTerm.RECEIVE_DATE,
APIDateTimeUtils.convertDateToString(dossier.getReceiveDate(), APIDateTimeUtils._NORMAL_PARTTERN));
jsonData.put(DossierTerm.DELEGATE_NAME, dossier.getDelegateName());
jsonData.put(DossierTerm.DELEGATE_EMAIL, dossier.getDelegateEmail());
jsonData.put(DossierTerm.DELEGATE_TELNO, dossier.getDelegateTelNo());
jsonData.put(DossierTerm.DOSSIER_NAME, dossier.getDossierName());
jsonData.put(DossierTerm.VIA_POSTAL, dossier.getViaPostal());
jsonData.put(DossierTerm.POSTAL_ADDRESS, dossier.getPostalAddress());
jsonData.put(DossierTerm.APPLICANT_NOTE, dossier.getApplicantNote());
jsonData.put(DossierTerm.DOSSIER_COUNTER, dossier.getDossierCounter());
// MetaData
String metaData = dossier.getMetaData();
if (Validator.isNotNull(metaData)) {
try {
JSONObject jsonMetaData = JSONFactoryUtil.createJSONObject(metaData);
//
Iterator<String> keys = jsonMetaData.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = jsonMetaData.getString(key);
if (Validator.isNotNull(value)) {
try {
JSONArray valueObject = JSONFactoryUtil.createJSONArray(value);
jsonData.put(key, valueObject);
} catch (JSONException e) {
_log.debug(e);
try {
JSONObject valueObject = JSONFactoryUtil.createJSONObject(value);
jsonData.put(key, valueObject);
} catch (JSONException e1) {
_log.debug(e1);
jsonData.put(key, value);
}
}
}
}
} catch (JSONException e) {
_log.debug(e);
}
}
try {
ServiceInfo service = ServiceInfoLocalServiceUtil.getByCode(dossier.getGroupId(), dossier.getServiceCode());
jsonData.put(ServiceInfoTerm.FEE_TEXT, service != null ? service.getFeeText() : StringPool.BLANK);
jsonData.put(ServiceInfoTerm.DURATION_TEXT, service != null ? service.getDurationText() : StringPool.BLANK);
} catch (PortalException e1) {
_log.debug(e1);
jsonData.put(ServiceInfoTerm.FEE_TEXT, StringPool.BLANK);
jsonData.put(ServiceInfoTerm.DURATION_TEXT, StringPool.BLANK);
}
//
Date dueDate = dossier.getDueDate();
if (dueDate != null) {
ServiceProcess process = ServiceProcessLocalServiceUtil.getByG_PNO(dossier.getGroupId(),
dossier.getProcessNo());
if (process != null) {
String dueDatePattern = process.getDueDatePattern();
//_log.info("dueDatePattern: " + dueDatePattern);
// _log.info("START DUEDATE TEST");
if (Validator.isNotNull(dueDatePattern)) {
//_log.info("START DUEDATE TEST");
// _log.info("dueDatePattern: "+dueDatePattern);
try {
JSONObject jsonDueDate = JSONFactoryUtil.createJSONObject(dueDatePattern);
//_log.info("jsonDueDate: " + jsonDueDate);
if (jsonDueDate != null) {
JSONObject hours = jsonDueDate.getJSONObject(KeyPayTerm.HOUR);
JSONObject processHours = jsonDueDate.getJSONObject(KeyPayTerm.PROCESSHOUR);
//_log.info("hours: " + hours);
if (hours != null && hours.has(KeyPayTerm.AM) && hours.has(KeyPayTerm.PM)) {
//_log.info("AM-PM: ");
Calendar receiveCalendar = Calendar.getInstance();
receiveCalendar.setTime(dossier.getReceiveDate());
Calendar dueCalendar = Calendar.getInstance();
//_log.info("hours: " + receiveCalendar.get(Calendar.HOUR_OF_DAY));
if (receiveCalendar.get(Calendar.HOUR_OF_DAY) < 12) {
dueCalendar.setTime(dossier.getDueDate());
String hoursAfterNoon = hours.getString(KeyPayTerm.AM);
//_log.info("hoursAfterNoon: " + hoursAfterNoon);
if (Validator.isNotNull(hoursAfterNoon)) {
String[] splitAfter = StringUtil.split(hoursAfterNoon, StringPool.COLON);
if (splitAfter != null) {
dueCalendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(splitAfter[0]));
dueCalendar.set(Calendar.MINUTE, Integer.valueOf(splitAfter[1]));
}
}
} else {
dueCalendar.setTime(dossier.getDueDate());
String hoursAfterNoon = hours.getString(KeyPayTerm.PM);
if (Validator.isNotNull(hoursAfterNoon)) {
String[] splitAfter = StringUtil.split(hoursAfterNoon, StringPool.COLON);
if (splitAfter != null) {
if (Integer.valueOf(splitAfter[0]) < 12) {
dueCalendar.add(Calendar.DAY_OF_MONTH, 1);
dueCalendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(splitAfter[0]));
dueCalendar.set(Calendar.MINUTE, Integer.valueOf(splitAfter[1]));
} else {
//dueCalendar.add(Calendar.DAY_OF_MONTH, 1);
dueCalendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(splitAfter[0]));
dueCalendar.set(Calendar.MINUTE, Integer.valueOf(splitAfter[1]));
}
}
}
}
jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils
.convertDateToString(dueCalendar.getTime(), APIDateTimeUtils._NORMAL_PARTTERN));
} else if (processHours != null && processHours.has(KeyPayTerm.STARTHOUR) && processHours.has(KeyPayTerm.DUEHOUR)) {
//_log.info("STRART check new: ");
Calendar receiveCalendar = Calendar.getInstance();
receiveCalendar.setTime(dossier.getReceiveDate());
//
String receiveHour = processHours.getString(KeyPayTerm.STARTHOUR);
//_log.info("receiveHour: " + receiveHour);
if (Validator.isNotNull(receiveHour)) {
String[] splitHour = StringUtil.split(receiveHour, StringPool.COLON);
if (splitHour != null) {
int hourStart = GetterUtil.getInteger(splitHour[0]);
if (receiveCalendar.get(Calendar.HOUR_OF_DAY) < hourStart) {
String[] splitdueHour = StringUtil.split(processHours.getString(KeyPayTerm.DUEHOUR),
StringPool.COLON);
Calendar dueCalendar = Calendar.getInstance();
if (splitdueHour != null) {
dueCalendar.set(Calendar.HOUR_OF_DAY,
GetterUtil.getInteger(splitdueHour[0]));
dueCalendar.set(Calendar.MINUTE,
GetterUtil.getInteger(splitdueHour[1]));
} else {
jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString(
dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN));
}
jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString(
dueCalendar.getTime(), APIDateTimeUtils._NORMAL_PARTTERN));
} else {
jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString(
dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN));
}
}
}
} else {
jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils
.convertDateToString(dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN));
}
} else {
jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils
.convertDateToString(dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN));
}
} catch (JSONException e) {
_log.error(e);
jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString(dossier.getDueDate(),
APIDateTimeUtils._NORMAL_PARTTERN));
}
} else {
jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString(dossier.getDueDate(),
APIDateTimeUtils._NORMAL_PARTTERN));
}
} else {
jsonData.put(DossierTerm.DUE_DATE,
APIDateTimeUtils.convertDateToString(dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN));
}
} else {
jsonData.put(DossierTerm.DUE_DATE, StringPool.BLANK);
}
//
jsonData.put(DossierTerm.POSTAL_ADDRESS, dossier.getPostalAddress());
jsonData.put(DossierTerm.COUNTER, dossier.getCounter());
jsonData.put(DossierTerm.REGISTER_BOOK_CODE, dossier.getRegisterBookCode());
jsonData.put(DossierTerm.SECRET, dossier.getPassword());
jsonData.put(DossierTerm.BRIEF_NOTE, dossier.getBriefNote());
jsonData.put(DossierTerm.DOSSIER_ID, dossier.getDossierId());
//
long groupId = dossier.getGroupId();
JSONArray dossierMarkArr = JSONFactoryUtil.createJSONArray();
long dossierId = dossier.getDossierId();
String templateNo = dossier.getDossierTemplateNo();
List<DossierMark> dossierMarkList = DossierMarkLocalServiceUtil.getDossierMarksByFileMark(groupId, dossierId, 0);
if (dossierMarkList != null && dossierMarkList.size() > 0) {
JSONObject jsonMark = null;
String partNo;
for (DossierMark dossierMark : dossierMarkList) {
jsonMark = JSONFactoryUtil.createJSONObject();
partNo = dossierMark.getDossierPartNo();
if (Validator.isNotNull(partNo)) {
DossierPart part = DossierPartLocalServiceUtil.getByTempAndPartNo(groupId, templateNo, partNo);
if (part != null) {
jsonMark.put(DossierPartTerm.DOSSIERPART_ID, part.getDossierPartId());
jsonMark.put(DossierPartTerm.PART_NAME, part.getPartName());
jsonMark.put(DossierPartTerm.PART_TIP, part.getPartTip());
jsonMark.put(DossierPartTerm.PART_TYPE, part.getPartType());
}
}
jsonMark.put(DossierPartTerm.PART_NO, partNo);
jsonMark.put(DossierPartTerm.FILE_MARK, dossierMark.getFileMark());
jsonMark.put(DossierPartTerm.FILE_CHECK, dossierMark.getFileCheck());
jsonMark.put(DossierPartTerm.FILE_COMMENT, dossierMark.getFileComment());
jsonMark.put(DossierPartTerm.RECORD_COUNT, dossierMark.getRecordCount());
// String strDossierMark = JSONFactoryUtil.looseSerialize(dossierMark);
dossierMarkArr.put(jsonMark);
}
}
//Hot fix TP99
DossierMark dossierMark = DossierMarkLocalServiceUtil.getDossierMarkbyDossierId(groupId, dossierId, KeyPayTerm.TP99);
if (dossierMark != null) {
JSONObject jsonMark = null;
String partNo = dossierMark.getDossierPartNo();
if (Validator.isNotNull(partNo)) {
List<DossierFile> fileList = DossierFileLocalServiceUtil.getDossierFileByDID_DPNO(dossierId, partNo, false);
DossierPart part = DossierPartLocalServiceUtil.getByTempAndPartNo(groupId, templateNo, partNo);
if (fileList != null && part != null) {
for (DossierFile dossierFile : fileList) {
jsonMark = JSONFactoryUtil.createJSONObject();
jsonMark.put(DossierPartTerm.PART_NAME, dossierFile.getDisplayName());
jsonMark.put(DossierPartTerm.DOSSIERPART_ID, part.getDossierPartId());
jsonMark.put(DossierPartTerm.PART_TIP, part.getPartTip());
jsonMark.put(DossierPartTerm.PART_TYPE, part.getPartType());
jsonMark.put(DossierPartTerm.PART_NO, partNo);
jsonMark.put(DossierPartTerm.FILE_MARK, dossierMark.getFileMark());
jsonMark.put(DossierPartTerm.FILE_CHECK, dossierMark.getFileCheck());
jsonMark.put(DossierPartTerm.FILE_COMMENT, dossierMark.getFileComment());
jsonMark.put(DossierPartTerm.RECORD_COUNT, dossierMark.getRecordCount());
// String strDossierMark = JSONFactoryUtil.looseSerialize(dossierMark);
dossierMarkArr.put(jsonMark);
}
}
}
}
jsonData.put(DossierTerm.DOSSIER_MARKS, dossierMarkArr);
PaymentFile payment = PaymentFileLocalServiceUtil.getByDossierId(groupId, dossierId);
if (payment != null) {
jsonData.put(PaymentFileTerm.ADVANCE_AMOUNT, payment.getAdvanceAmount());
jsonData.put(PaymentFileTerm.PAYMENT_AMOUNT, payment.getPaymentAmount());
jsonData.put(PaymentFileTerm.PAYMENT_FEE, payment.getPaymentFee());
jsonData.put(PaymentFileTerm.SERVICE_AMOUNT, payment.getServiceAmount());
jsonData.put(PaymentFileTerm.SHIP_AMOUNT, payment.getShipAmount());
}
if (dossier.getOriginality() == DossierTerm.ORIGINALITY_HOSONHOM) {
JSONArray groupDossierArr = JSONFactoryUtil.createJSONArray();
List<Dossier> lstDossiers = DossierLocalServiceUtil.findByG_GDID(groupId, dossier.getDossierId());
for (Dossier d : lstDossiers) {
JSONObject dObject = JSONFactoryUtil.createJSONObject();
dObject.put(DossierTerm.DOSSIER_NO, d.getDossierNo());
dObject.put(DossierTerm.APPLICANT_NAME, d.getApplicantName());
dObject.put(DossierTerm.ADDRESS, d.getAddress());
dObject.put(DossierTerm.CONTACT_TEL_NO, d.getContactTelNo());
dObject.put(DossierTerm.CONTACT_EMAIL, d.getContactEmail());
dObject.put(DossierTerm.CONTACT_NAME, d.getContactName());
dObject.put(DossierTerm.DELEGATE_ADDRESS, d.getDelegateAddress());
dObject.put(DossierTerm.SERVICE_CODE, d.getServiceCode());
dObject.put(DossierTerm.SERVICE_NAME, d.getServiceName());
dObject.put(DossierTerm.SAMPLE_COUNT, d.getSampleCount());
dObject.put(DossierTerm.DURATION_UNIT, d.getDurationUnit());
dObject.put(DossierTerm.DURATION_COUNT, d.getDurationCount());
dObject.put(DossierTerm.SECRET_KEY, d.getPassword());
dObject.put(DossierTerm.RECEIVE_DATE,
APIDateTimeUtils.convertDateToString(d.getReceiveDate(), APIDateTimeUtils._NORMAL_PARTTERN));
dObject.put(DossierTerm.DELEGATE_NAME, d.getDelegateName());
dObject.put(DossierTerm.DELEGATE_EMAIL, d.getDelegateEmail());
dObject.put(DossierTerm.DELEGATE_TELNO, d.getDelegateTelNo());
dObject.put(DossierTerm.DOSSIER_NAME, d.getDossierName());
dObject.put(DossierTerm.VIA_POSTAL, d.getViaPostal());
dObject.put(DossierTerm.POSTAL_ADDRESS, d.getPostalAddress());
groupDossierArr.put(dObject);
}
jsonData.put(DossierTerm.GROUP_DOSSIERS, groupDossierArr);
}
DictCollection govCollection = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(GOVERNMENT_AGENCY, dossier.getGroupId());
if (govCollection != null) {
DictItem govAgenItem = DictItemLocalServiceUtil.fetchByF_dictItemCode(dossier.getGovAgencyCode(), govCollection.getDictCollectionId(), dossier.getGroupId());
String metaDataItem = govAgenItem.getMetaData();
try {
JSONObject metaObj = JSONFactoryUtil.createJSONObject(metaDataItem);
if (govAgenItem != null) {
if (metaObj.has(BN_TELEPHONE)) {
jsonData.put(BN_TELEPHONE, metaObj.getString(BN_TELEPHONE));
}
if (metaObj.has(BN_EMAIL)) {
jsonData.put(BN_EMAIL, metaObj.getString(BN_EMAIL));
}
if (metaObj.has(BN_ADDRESS)) {
jsonData.put(BN_ADDRESS, metaObj.getString(BN_ADDRESS));
}
}
}
catch (Exception e) {
_log.debug(e);
}
}
if (jsonData.has(DossierTerm.EXTEND_DATE) && Validator.isNotNull(jsonData.get(DossierTerm.EXTEND_DATE))
&& GetterUtil.getLong(jsonData.get(DossierTerm.EXTEND_DATE)) > 0) {
Date extendDate = new Date(GetterUtil.getLong(jsonData.get(DossierTerm.EXTEND_DATE)));
jsonData.put(DossierTerm.EXTEND_DATE, APIDateTimeUtils.convertDateToString(extendDate, APIDateTimeUtils._NORMAL_DATE_TIME));
}
//Notarization
ServiceInfo si;
try {
si = ServiceInfoLocalServiceUtil.getByCode(dossier.getGroupId(), dossier.getServiceCode());
if (si != null) {
jsonData.put(ServiceInfoTerm.IS_NOTARIZATION, si.isIsNotarization());
}
else {
jsonData.put(ServiceInfoTerm.IS_NOTARIZATION, false);
}
} catch (PortalException e) {
_log.debug(e);
}
List<Notarization> lstNotarizations = NotarizationLocalServiceUtil.findByG_DID(groupId, dossierId);
JSONArray notarizationArr = JSONFactoryUtil.createJSONArray();
for (Notarization nt : lstNotarizations) {
JSONObject notObj = JSONFactoryUtil.createJSONObject();
notObj.put(NotarizationTerm.NOTARIZATION_ID, nt.getNotarizationId());
notObj.put(NotarizationTerm.DOSSIER_ID, nt.getDossierId());
notObj.put(NotarizationTerm.GROUP_ID, nt.getGroupId());
notObj.put(NotarizationTerm.FILE_NAME, nt.getFileName());
notObj.put(NotarizationTerm.NOTARIZATION_DATE, nt.getNotarizationDate() != null ? APIDateTimeUtils.convertDateToString(nt.getNotarizationDate(), APIDateTimeUtils._NORMAL_PARTTERN) : StringPool.BLANK);
notObj.put(NotarizationTerm.NOTARIZATION_NO, nt.getNotarizationNo());
notObj.put(NotarizationTerm.NOTARIZATION_YEAR, nt.getNotarizationYear());
notObj.put(NotarizationTerm.SIGNER_NAME, nt.getSignerName());
notObj.put(NotarizationTerm.SIGNER_POSITION, nt.getSignerPosition());
notObj.put(NotarizationTerm.STATUS_CODE, nt.getStatusCode());
notObj.put(NotarizationTerm.TOTAL_COPY, nt.getTotalCopy());
notObj.put(NotarizationTerm.TOTAL_FEE, nt.getTotalFee());
notObj.put(NotarizationTerm.TOTAL_PAGE, nt.getTotalPage());
notObj.put(NotarizationTerm.TOTAL_RECORD, nt.getTotalRecord());
notarizationArr.put(notObj);
}
jsonData.put(DossierTerm.NOTARIZATIONS, notarizationArr);
return jsonData;
}
//LamTV_ Mapping process dossier and formData
private JSONObject processMergeDossierProcessRole(Dossier dossier, int length, JSONObject jsonData,
DossierAction dAction) {
//
long groupId = dossier.getGroupId();
if (dAction != null) {
long serviceProcessId = dAction.getServiceProcessId();
jsonData.put(DossierTerm.GOV_AGENCY_NAME, dossier.getGovAgencyName());
jsonData.put(DossierTerm.TOTAL, length);
jsonData.put(DossierTerm.ACTION_USER, dAction.getActionUser());
String sequenceNo = dAction.getSequenceNo();
if (Validator.isNotNull(sequenceNo)) {
ProcessSequence sequence = ProcessSequenceLocalServiceUtil.findBySID_SNO(groupId, serviceProcessId,
sequenceNo);
if (sequence != null) {
jsonData.put(DossierTerm.SEQUENCE_ROLE, sequence.getSequenceRole());
} else {
jsonData.put(DossierTerm.SEQUENCE_ROLE, StringPool.BLANK);
}
} else {
jsonData.put(DossierTerm.SEQUENCE_ROLE, StringPool.BLANK);
}
// Process get Next sequence Role
//List<ProcessSequence> sequenceList = ProcessSequenceLocalServiceUtil.getByServiceProcess(groupId,
// serviceProcessId);
//TODO: Using cache
// List<ProcessSequence> sequenceList = null;
// Serializable data = CacheLocalServiceUtil.getFromCache("ProcessSequence", groupId +"_"+serviceProcessId);
// if (data != null) {
// sequenceList = (List<ProcessSequence>) data;
// } else {
// sequenceList = ProcessSequenceLocalServiceUtil.getByServiceProcess(groupId,
// serviceProcessId);
// if (sequenceList != null) {
// //_log.info("START_ Serlist null");
// CacheLocalServiceUtil.addToCache("ProcessSequence",
// groupId +"_"+serviceProcessId, (Serializable) sequenceList,
// (int) Time.MINUTE * 30);
// }
// }
List<ProcessSequence> sequenceList = ProcessSequenceLocalServiceUtil.getByServiceProcess(groupId,
serviceProcessId);
String[] sequenceArr = null;
if (sequenceList != null && !sequenceList.isEmpty()) {
int lengthSeq = sequenceList.size();
sequenceArr = new String[lengthSeq];
for (int i = 0; i < lengthSeq; i++) {
ProcessSequence processSequence = sequenceList.get(i);
if (processSequence != null) {
sequenceArr[i] = processSequence.getSequenceNo();
}
}
}
if (sequenceArr != null && sequenceArr.length > 0) {
Arrays.sort(sequenceArr);
for (int i = 0; i < sequenceArr.length - 1; i++) {
String seq = sequenceArr[i];
if (sequenceNo.equals(seq)) {
String nextSequenceNo = sequenceArr[i + 1];
if (Validator.isNotNull(nextSequenceNo)) {
ProcessSequence sequence = ProcessSequenceLocalServiceUtil.findBySID_SNO(groupId,
serviceProcessId, nextSequenceNo);
if (sequence != null) {
jsonData.put(DossierTerm.NEXT_SEQUENCE_ROLE, sequence.getSequenceRole());
} else {
jsonData.put(DossierTerm.NEXT_SEQUENCE_ROLE, StringPool.BLANK);
}
} else {
jsonData.put(DossierTerm.NEXT_SEQUENCE_ROLE, StringPool.BLANK);
}
}
}
} else {
jsonData.put(DossierTerm.NEXT_SEQUENCE_ROLE, StringPool.BLANK);
}
//Process array sequence
JSONArray jsonSequenceArr = getProcessSequencesJSON(sequenceArr, sequenceList);
if (jsonSequenceArr != null) {
jsonData.put(KeyPayTerm.processSequenceArr, jsonSequenceArr);
}
}
return jsonData;
}
private static JSONArray getProcessSequencesJSON(String[] sequenceArr, List<ProcessSequence> sequenceList) {
JSONArray jsonSequenceArr = JSONFactoryUtil.createJSONArray();
if (sequenceArr != null && sequenceArr.length > 0) {
for (int i = 0; i < sequenceArr.length - 1; i++) {
String sequenceNo = sequenceArr[i];
JSONObject sequenceObj = JSONFactoryUtil.createJSONObject();
for (ProcessSequence proSeq : sequenceList) {
if (sequenceNo.equals(proSeq.getSequenceNo())) {
sequenceObj.put(DossierTerm.SEQUENCE_NO, proSeq.getSequenceNo());
sequenceObj.put(DossierTerm.SEQUENCE_NAME, proSeq.getSequenceName());
sequenceObj.put(DossierTerm.SEQUENCE_ROLE, proSeq.getSequenceRole());
sequenceObj.put(DossierTerm.DURATION_COUNT, proSeq.getDurationCount());
sequenceObj.put(Field.CREATE_DATE, proSeq.getCreateDate());
}
}
String nextSequenceNo = sequenceArr[i + 1];
for (ProcessSequence proSeq : sequenceList) {
if (nextSequenceNo.equals(proSeq.getSequenceNo())) {
sequenceObj.put(DossierTerm.NEXT_SEQUENCE_NO, proSeq.getSequenceNo());
sequenceObj.put(DossierTerm.NEXT_SEQUENCE_NAME, proSeq.getSequenceName());
sequenceObj.put(DossierTerm.NEXT_SEQUENCE_ROLE, proSeq.getSequenceRole());
sequenceObj.put(DossierTerm.NEXT_CREATE_DATE, proSeq.getCreateDate());
}
}
jsonSequenceArr.put(sequenceObj);
}
}
return jsonSequenceArr;
}
private void vnpostEvent(Dossier dossier, long dossierActionId) {
Message message = new Message();
JSONObject msgData = JSONFactoryUtil.createJSONObject();
message.put(ConstantUtils.MSG_ENG, msgData);
message.put(DossierTerm.CONSTANT_DOSSIER, DossierMgtUtils.convertDossierToJSON(dossier, dossierActionId));
MessageBusUtil.sendMessage(DossierTerm.VNPOST_DOSSIER_DESTINATION, message);
}
private void collectVnpostEvent(Dossier dossier, long dossierActionId) {
Message message = new Message();
JSONObject msgData = JSONFactoryUtil.createJSONObject();
message.put(ConstantUtils.MSG_ENG, msgData);
message.put(DossierTerm.CONSTANT_DOSSIER, DossierMgtUtils.convertDossierToJSON(dossier, dossierActionId));
_log.info("=============create collectVnpostEvent============");
MessageBusUtil.sendMessage(DossierTerm.COLLECTION_VNPOST_DOSSIER_DESTINATION, message);
}
private void publishEvent(Dossier dossier, ServiceContext context, long dossierActionId) {
if (dossier.getOriginDossierId() != 0 || Validator.isNotNull(dossier.getOriginDossierNo())) {
return;
}
Message message = new Message();
JSONObject msgData = JSONFactoryUtil.createJSONObject();
message.put(ConstantUtils.MSG_ENG, msgData);
message.put(DossierTerm.CONSTANT_DOSSIER, DossierMgtUtils.convertDossierToJSON(dossier, dossierActionId));
// MessageBusUtil.sendMessage(DossierTerm.PUBLISH_DOSSIER_DESTINATION, message);
Message lgspMessage = new Message();
JSONObject lgspMsgData = msgData;
lgspMessage.put(ConstantUtils.MSG_ENG, lgspMsgData);
lgspMessage.put(DossierTerm.CONSTANT_DOSSIER, DossierMgtUtils.convertDossierToJSON(dossier, dossierActionId));
// MessageBusUtil.sendMessage(DossierTerm.LGSP_DOSSIER_DESTINATION, lgspMessage);
//Add publish queue
List<ServerConfig> lstScs = ServerConfigLocalServiceUtil.getByProtocol(dossier.getGroupId(), ServerConfigTerm.PUBLISH_PROTOCOL);
for (ServerConfig sc : lstScs) {
try {
List<PublishQueue> lstQueues = PublishQueueLocalServiceUtil.getByG_DID_SN_ST(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo(), new int[] { PublishQueueTerm.STATE_WAITING_SYNC, PublishQueueTerm.STATE_ALREADY_SENT });
if (lstQueues == null || lstQueues.isEmpty()) {
publishQueueLocalService.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
}
// PublishQueue pq = PublishQueueLocalServiceUtil.getByG_DID_SN(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo());
// if (pq == null) {
// PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
// }
// else {
// if (pq.getStatus() == PublishQueueTerm.STATE_ACK_ERROR) {
// PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), pq.getPublishQueueId(), dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
// }
// }
} catch (PortalException e) {
_log.debug(e);
}
}
lstScs = ServerConfigLocalServiceUtil.getByProtocol(dossier.getGroupId(), ServerConfigTerm.LGSP_PROTOCOL);
for (ServerConfig sc : lstScs) {
try {
List<PublishQueue> lstQueues = publishQueueLocalService.getByG_DID_SN_ST(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo(), new int[] { PublishQueueTerm.STATE_WAITING_SYNC, PublishQueueTerm.STATE_ALREADY_SENT });
if (lstQueues == null || lstQueues.isEmpty()) {
publishQueueLocalService.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
}
// PublishQueue pq = PublishQueueLocalServiceUtil.getByG_DID_SN(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo());
// if (pq == null) {
// PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
// }
// else {
// if (pq.getStatus() == PublishQueueTerm.STATE_ACK_ERROR) {
// PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), pq.getPublishQueueId(), dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
// }
// }
} catch (PortalException e) {
_log.debug(e);
}
}
//add by TrungNT
DVCQGIntegrationActionImpl actionImpl = new DVCQGIntegrationActionImpl();
String mappingDossierStatus = actionImpl.getMappingStatus(dossier.getGroupId(), dossier);
if(Validator.isNotNull(mappingDossierStatus)) {
lstScs = ServerConfigLocalServiceUtil.getByProtocol(dossier.getGroupId(), ServerConfigTerm.DVCQG_INTEGRATION);
for (ServerConfig sc : lstScs) {
try {
List<PublishQueue> lstQueues = publishQueueLocalService.getByG_DID_SN_ST(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo(), new int[] { PublishQueueTerm.STATE_WAITING_SYNC, PublishQueueTerm.STATE_ALREADY_SENT });
if (lstQueues == null || lstQueues.isEmpty()) {
publishQueueLocalService.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
}
// PublishQueue pq = PublishQueueLocalServiceUtil.getByG_DID_SN(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo());
// if (pq == null) {
// PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
// }
// else {
// if (pq.getStatus() == PublishQueueTerm.STATE_ACK_ERROR) {
// PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), pq.getPublishQueueId(), dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context);
// }
// }
} catch (PortalException e) {
_log.debug(e);
}
}
}
}
private ProcessOption getProcessOption(String serviceInfoCode, String govAgencyCode, String dossierTemplateNo,
long groupId) throws PortalException {
ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, serviceInfoCode, govAgencyCode);
return processOptionLocalService.getByDTPLNoAndServiceCF(groupId, dossierTemplateNo,
config.getServiceConfigId());
}
protected ProcessAction getProcessAction(long groupId, long dossierId, String refId, String actionCode,
long serviceProcessId) throws PortalException {
ProcessAction action = null;
try {
List<ProcessAction> actions = processActionLocalService.getByActionCode(groupId, actionCode,
serviceProcessId);
Dossier dossier = getDossier(groupId, dossierId, refId);
String dossierStatus = dossier.getDossierStatus();
String dossierSubStatus = Validator.isNull(dossier.getDossierSubStatus()) ? StringPool.BLANK
: dossier.getDossierSubStatus();
String curStepCode = StringPool.BLANK;
if (dossier.getDossierActionId() > 0) {
DossierAction curAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId());
if (curAction != null) {
curStepCode = curAction.getStepCode();
}
}
for (ProcessAction act : actions) {
String preStepCode = act.getPreStepCode();
if (Validator.isNotNull(curStepCode) && !preStepCode.contentEquals(curStepCode)) continue;
ProcessStep step = processStepLocalService.fetchBySC_GID(preStepCode, groupId, serviceProcessId);
String subStepStatus = StringPool.BLANK;
if (Validator.isNotNull(step)) {
subStepStatus = Validator.isNull(step.getDossierSubStatus()) ? StringPool.BLANK
: step.getDossierSubStatus();
}
if (Validator.isNull(step)) {
action = act;
break;
} else {
if (step.getDossierStatus().contentEquals(dossierStatus)
&& subStepStatus.contentEquals(dossierSubStatus)) {
action = act;
break;
}
}
}
} catch (Exception e) {
_log.debug(e);
//_log.error(e);
throw new NotFoundException("ProcessActionNotFoundException with actionCode= " + actionCode
+ "|serviceProcessId= " + serviceProcessId + "|referenceUid= " + refId + "|groupId= " + groupId);
}
return action;
}
protected Dossier getDossier(long groupId, long dossierId, String refId) throws PortalException {
Dossier dossier = null;
if (dossierId != 0) {
dossier = dossierLocalService.fetchDossier(dossierId);
} else {
dossier = dossierLocalService.getByRef(groupId, refId);
}
return dossier;
}
private String generatorGoodCode(int length) {
String tempGoodCode = _generatorUniqueString(length);
String goodCode;
while (_checkContainsGoodCode(tempGoodCode)) {
tempGoodCode = _generatorUniqueString(length);
}
/*
* while(_testCheck(tempGoodCode)) { tempGoodCode =
* _generatorUniqueString(length); }
*/
goodCode = tempGoodCode;
return goodCode;
}
private boolean _checkContainsGoodCode(String keypayGoodCode) {
boolean isContains = false;
try {
PaymentFile paymentFile = null;//PaymentFileLocalServiceUtil.getByGoodCode(keypayGoodCode);
if (Validator.isNotNull(paymentFile)) {
isContains = true;
}
} catch (Exception e) {
_log.error(e);
isContains = true;
}
return isContains;
}
private DossierAction doActionOutsideProcess(long groupId, long userId, Dossier dossier, ActionConfig actionConfig, ProcessOption option, ProcessAction proAction,
String actionCode, String actionUser, String actionNote, String payload, String assignUsers,
String payment,
int syncType,
ServiceContext context) throws PortalException, SystemException, Exception {
context.setUserId(userId);
DossierAction dossierAction = null;
String dossierStatus = dossier.getDossierStatus().toLowerCase();
if (Validator.isNotNull(dossierStatus) && !"new".equals(dossierStatus)) {
dossier = dossierLocalService.updateDossier(dossier);
}
// ServiceProcess serviceProcess = null;
// if (option != null) {
// long serviceProcessId = option.getServiceProcessId();
// serviceProcess = serviceProcessLocalService.fetchServiceProcess(serviceProcessId);
// }
dossierAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId());
// ActionConfig ac = actionConfigLocalService.getByCode(groupId, actionCode);
ActionConfig ac = actionConfig;
JSONObject payloadObject = JSONFactoryUtil.createJSONObject(payload);
if (Validator.isNotNull(payload)) {
if (DossierActionTerm.OUTSIDE_ACTION_9100.equals(actionCode)) {
dossier = dossierLocalService.updateDossierSpecial(dossier.getDossierId(), payloadObject);
}
else {
dossier = dossierLocalService.updateDossier(dossier.getDossierId(), payloadObject);
}
}
if (DossierActionTerm.OUTSIDE_ACTION_ROLLBACK.equals(actionCode)) {
Dossier hslt = dossierLocalService.getByOrigin(dossier.getGroupId(), dossier.getDossierId());
// chi nguoi thuc hien buoc truoc moi duoc phep quay lai buoc
User user=UserLocalServiceUtil.getUser(userId);
List<Role> userRoles = user.getRoles();
boolean isAdmin = false;
for (Role r : userRoles) {
if (r.getName().startsWith("Administrator")) {
isAdmin = true;
break;
}
}
if (dossierAction != null && !dossierAction.getPending() &&
(dossierAction.isRollbackable() || hslt.getOriginality() < 0)
&& (isAdmin || dossierAction.getUserId() == userId)) {
dossierActionLocalService.updateState(dossierAction.getDossierActionId(), DossierActionTerm.STATE_ROLLBACK);
DossierAction previousAction = dossierActionLocalService.fetchDossierAction(dossierAction.getPreviousActionId());
if (previousAction != null) {
dossierActionLocalService.updateState(previousAction.getDossierActionId(), DossierActionTerm.STATE_WAITING_PROCESSING);
dossierActionLocalService.updateNextActionId(previousAction.getDossierActionId(), 0);
dossierLocalService.rollback(dossier, previousAction);
}
else {
dossierActionLocalService.removeAction(dossierAction.getDossierActionId());
dossier.setDossierActionId(0);
dossier.setOriginality(-dossier.getOriginality());
dossierLocalService.updateDossier(dossier);
}
}
}
//Create DossierSync
String dossierRefUid = dossier.getReferenceUid();
String syncRefUid = UUID.randomUUID().toString();
if (syncType > 0) {
int state = DossierActionUtils.getSyncState(syncType, dossier);
//Update payload
if (Validator.isNotNull(dossier.getServerNo())
&& dossier.getServerNo().split(StringPool.BLANK).length > 1) {
String serverNo = dossier.getServerNo().split(StringPool.COMMA)[0].split(StringPool.AT)[0];
dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid,
dossierAction.getPrimaryKey(), actionCode, ac.getActionName(), actionUser, actionNote,
syncType, ac.getInfoType(), payloadObject.toJSONString(), serverNo, state);
}
else {
dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid,
dossierAction.getPrimaryKey(), actionCode, ac.getActionName(), actionUser, actionNote,
syncType, ac.getInfoType(), payloadObject.toJSONString(), dossier.getServerNo(), state);
}
}
if (ac != null && dossierAction != null) {
//Only create dossier document if 2 && 3
if (dossier.getOriginality() != DossierTerm.ORIGINALITY_DVCTT) {
if (Validator.isNotNull(ac.getDocumentType()) && !ac.getActionCode().startsWith(StringPool.AT)) {
//Generate document
DocumentType dt = documentTypeLocalService.getByTypeCode(groupId, ac.getDocumentType());
if (dt != null) {
String documentCode = DocumentTypeNumberGenerator.generateDocumentTypeNumber(groupId, ac.getCompanyId(), dt.getDocumentTypeId());
DossierDocument dossierDocument = dossierDocumentLocalService.addDossierDoc(groupId, dossier.getDossierId(), UUID.randomUUID().toString(), dossierAction.getDossierActionId(), dt.getTypeCode(), dt.getDocumentName(), documentCode, 0L, dt.getDocSync(), context);
//Generate PDF
String formData = payload;
JSONObject formDataObj = processMergeDossierFormData(dossier, JSONFactoryUtil.createJSONObject(formData));
// _log.info("Dossier document form data action outside: " + formDataObj.toJSONString());
Message message = new Message();
// _log.info("Document script: " + dt.getDocumentScript());
JSONObject msgData = JSONFactoryUtil.createJSONObject();
msgData.put(ConstantUtils.CLASS_NAME, DossierDocument.class.getName());
msgData.put(Field.CLASS_PK, dossierDocument.getDossierDocumentId());
msgData.put(ConstantUtils.JRXML_TEMPLATE, dt.getDocumentScript());
msgData.put(ConstantUtils.FORM_DATA, formDataObj.toJSONString());
msgData.put(Field.USER_ID, userId);
message.put(ConstantUtils.MSG_ENG, msgData);
MessageBusUtil.sendMessage(ConstantUtils.JASPER_DESTINATION, message);
}
}
}
}
if (ac != null && ac.getEventType() == ActionConfigTerm.EVENT_TYPE_SENT && OpenCPSConfigUtil.isPublishEventEnable()) {
publishEvent(dossier, context, dossierAction.getDossierActionId());
}
//Add by TrungNT - Fix tam theo y/k cua a TrungDK va Duantv
if (dossier.isOnline() && proAction != null && "listener".equals(proAction.getAutoEvent().toString()) && OpenCPSConfigUtil.isPublishEventEnable()) {
publishEvent(dossier, context, dossierAction.getDossierActionId());
}
if (OpenCPSConfigUtil.isNotificationEnable()) {
createNotificationQueueOutsideProcess(userId, groupId, dossier, proAction, actionConfig, context);
}
if (DossierActionTerm.OUTSIDE_ACTION_ROLLBACK.equals(actionCode)) {
if (dossier.getOriginDossierId() != 0) {
Dossier hslt = dossierLocalService.fetchDossier(dossier.getOriginDossierId());
ProcessOption optionHslt = getProcessOption(hslt.getServiceCode(), hslt.getGovAgencyCode(),
hslt.getDossierTemplateNo(), groupId);
String actionUserHslt = actionUser;
if (dossier.getOriginDossierId() != 0) {
Dossier originDossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId());
if (originDossier != null) {
DossierAction lastAction = dossierActionLocalService.fetchDossierAction(originDossier.getDossierActionId());
ActionConfig mappingAction = actionConfigLocalService.getByCode(groupId, lastAction.getActionCode());
if (Validator.isNotNull(mappingAction.getMappingAction())) {
DossierAction previousOriginAction = dossierActionLocalService.fetchDossierAction(lastAction.getPreviousActionId());
dossierActionLocalService.updateState(previousOriginAction.getDossierActionId(), DossierActionTerm.STATE_WAITING_PROCESSING);
dossierActionLocalService.updateNextActionId(previousOriginAction.getDossierActionId(), 0);
dossierLocalService.rollback(originDossier, previousOriginAction);
}
}
}
if (DossierTerm.DOSSIER_STATUS_NEW.equals(hslt.getDossierStatus())) {
Date now = new Date();
hslt.setSubmitDate(now);
hslt = dossierLocalService.updateDossier(hslt);
try {
JSONObject payloadObj = JSONFactoryUtil.createJSONObject(payload);
payloadObj.put(DossierTerm.SUBMIT_DATE, now.getTime());
payload = payloadObj.toJSONString();
}
catch (JSONException e) {
_log.debug(e);
}
}
DossierAction lastAction = dossierActionLocalService.fetchDossierAction(hslt.getDossierActionId());
ActionConfig mappingAction = actionConfigLocalService.getByCode(groupId, lastAction.getActionCode());
if (Validator.isNotNull(mappingAction.getMappingAction())) {
doAction(groupId, userId, hslt, optionHslt, null, DossierActionTerm.OUTSIDE_ACTION_ROLLBACK, actionUserHslt, actionNote, payload, assignUsers, payment, 0, context);
}
}
}
return dossierAction;
}
private boolean isSmsNotify(Dossier dossier) {
String metaData = dossier.getMetaData();
if (Validator.isNotNull(metaData)) {
try {
JSONObject jsonMetaData = JSONFactoryUtil.createJSONObject(metaData);
//
Iterator<String> keys = jsonMetaData.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = jsonMetaData.getString(key);
if (Validator.isNotNull(value) && value.contentEquals(DossierTerm.SMS_NOTIFY)) {
try {
Boolean isSmsNotify = Boolean.parseBoolean(value);
return isSmsNotify;
} catch (Exception e) {
_log.debug(e);
}
}
}
} catch (JSONException e) {
_log.debug(e);
}
}
return true;
}
private boolean isEmailNotify(Dossier dossier) {
String metaData = dossier.getMetaData();
if (Validator.isNotNull(metaData)) {
try {
JSONObject jsonMetaData = JSONFactoryUtil.createJSONObject(metaData);
//
Iterator<String> keys = jsonMetaData.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = jsonMetaData.getString(key);
if (Validator.isNotNull(value) && value.contentEquals(DossierTerm.EMAIL_NOTIFY)) {
try {
Boolean isEmailNotify = Boolean.parseBoolean(value);
return isEmailNotify;
} catch (Exception e) {
_log.debug(e);
}
}
}
} catch (JSONException e) {
_log.debug(e);
}
}
return true;
}
private void createNotificationQueueOutsideProcess(long userId, long groupId, Dossier dossier, ProcessAction proAction, ActionConfig actionConfig, ServiceContext context) {
DossierAction dossierAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId());
User u = UserLocalServiceUtil.fetchUser(userId);
JSONObject payloadObj = JSONFactoryUtil.createJSONObject();
payloadObj = buildNotificationPayload(dossier, payloadObj);
try {
JSONObject dossierObj = JSONFactoryUtil.createJSONObject(
JSONFactoryUtil.looseSerialize(dossier));
dossierObj = buildNotificationPayload(dossier, dossierObj);
payloadObj.put(
KeyPayTerm.DOSSIER, dossierObj);
if (dossierAction != null) {
payloadObj.put(DossierActionTerm.ACTION_CODE, dossierAction.getActionCode());
payloadObj.put(DossierActionTerm.ACTION_USER, dossierAction.getActionUser());
payloadObj.put(DossierActionTerm.ACTION_NAME, dossierAction.getActionName());
payloadObj.put(DossierActionTerm.ACTION_NOTE, dossierAction.getActionNote());
}
}
catch (Exception e) {
_log.error(e);
}
String notificationType = StringPool.BLANK;
String preCondition = StringPool.BLANK;
if (actionConfig != null && Validator.isNotNull(actionConfig.getNotificationType())) {
if (actionConfig.getNotificationType().contains(StringPool.AT)) {
String[] split = StringUtil.split(actionConfig.getNotificationType(), StringPool.AT);
if (split.length == 2) {
notificationType = split[0];
preCondition = split[1];
}
}
else {
notificationType = actionConfig.getNotificationType();
}
boolean isSendSMS = NotificationUtil.isSendSMS(preCondition);
boolean isSendEmail = NotificationUtil.isSendEmail(preCondition);
boolean isSendNotiSMS = true;
boolean isSendNotiEmail = true;
if (Validator.isNotNull(preCondition)) {
if (!DossierMgtUtils.checkPreCondition(new String[] { preCondition } , dossier, null)) {
if (isSendSMS) {
isSendNotiSMS = false;
isSendNotiEmail = true;
}
else {
isSendNotiSMS = false;
isSendNotiEmail = false;
}
}
else {
isSendNotiSMS = isSendSMS;
isSendNotiEmail = isSendEmail;
}
}
Notificationtemplate notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, notificationType);
Date now = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(now);
if (notiTemplate != null) {
if (KeyPayTerm.MINUTELY.equals(notiTemplate.getInterval())) {
cal.add(Calendar.MINUTE, notiTemplate.getExpireDuration());
}
else if (KeyPayTerm.HOURLY.equals(notiTemplate.getInterval())) {
cal.add(Calendar.HOUR, notiTemplate.getExpireDuration());
}
else {
cal.add(Calendar.MINUTE, notiTemplate.getExpireDuration());
}
Date expired = cal.getTime();
if (notificationType.startsWith(KeyPayTerm.APLC)) {
if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA
|| dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) {
try {
Applicant applicant = ApplicantLocalServiceUtil.fetchByAppId(dossier.getApplicantIdNo());
long toUserId = (applicant != null ? applicant.getMappingUserId() : 0l);
String contactEmail = (isEmailNotify(dossier)) ? dossier.getContactEmail() : StringPool.BLANK;
String telNo = (isSmsNotify(dossier)) ? dossier.getContactTelNo() : StringPool.BLANK;
String fromFullName = u.getFullName();
if (Validator.isNotNull(OpenCPSConfigUtil.getMailToApplicantFrom())) {
fromFullName = OpenCPSConfigUtil.getMailToApplicantFrom();
}
JSONObject filesAttach = getFileAttachMailForApplicant(dossier, proAction);
payloadObj.put("filesAttach", filesAttach);
NotificationQueueLocalServiceUtil.addNotificationQueue(
userId, groupId,
notificationType,
Dossier.class.getName(),
String.valueOf(dossier.getDossierId()),
payloadObj.toJSONString(),
fromFullName,
dossier.getApplicantName(),
toUserId,
isSendNotiEmail ? contactEmail : StringPool.BLANK,
isSendNotiSMS ? telNo : StringPool.BLANK,
now,
expired,
context);
} catch (NoSuchUserException e) {
_log.error(e);
}
}
}
else if (notificationType.startsWith(KeyPayTerm.USER)) {
}
}
}
}
/**
* @param pattern
* @param lenght
* @return
*/
private String _generatorUniqueString(int lenght) {
char[] chars = KeyPayTerm.ZERO_TO_NINE.toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < lenght; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
return sb.toString();
}
private void assignDossierActionUser(Dossier dossier, int allowAssignUser, DossierAction dossierAction, long userId, long groupId, long assignUserId, JSONArray assignedUsers)
throws PortalException {
int moderator = 1;
List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId());
HashMap<Long, DossierUser> mapDus = new HashMap<>();
for (DossierUser du : lstDus) {
mapDus.put(du.getUserId(), du);
}
List<org.opencps.dossiermgt.model.DossierActionUser> lstDaus = dossierActionUserLocalService.getByDossierId(dossier.getDossierId());
HashMap<Long, Map<Long, org.opencps.dossiermgt.model.DossierActionUser>> mapDaus = new HashMap<>();
for (org.opencps.dossiermgt.model.DossierActionUser dau : lstDaus) {
if (mapDaus.get(dau.getDossierActionId()) != null) {
Map<Long, org.opencps.dossiermgt.model.DossierActionUser> temp = mapDaus.get(dau.getDossierActionId());
temp.put(dau.getUserId(), dau);
}
else {
Map<Long, org.opencps.dossiermgt.model.DossierActionUser> temp = new HashMap<>();
temp.put(dau.getUserId(), dau);
mapDaus.put(dau.getDossierActionId(), temp);
}
}
for (int n = 0; n < assignedUsers.length(); n++) {
JSONObject subUser = assignedUsers.getJSONObject(n);
if (subUser != null && subUser.has(DossierActionUserTerm.ASSIGNED)
&& subUser.getInt(DossierActionUserTerm.ASSIGNED) == DossierActionUserTerm.ASSIGNED_TH) {
DossierActionUserPK pk = new DossierActionUserPK();
long userIdAssigned = subUser.getLong(Field.USER_ID);
int assigned = subUser.has(DossierActionUserTerm.ASSIGNED) ? subUser.getInt(DossierActionUserTerm.ASSIGNED) : 0;
pk.setDossierActionId(dossierAction.getDossierActionId());
pk.setUserId(subUser.getLong(Field.USER_ID));
DossierUser dossierUser = null;
dossierUser = mapDus.get(subUser.getLong(Field.USER_ID));
if (dossierUser != null) {
//Update dossier user if assigned
if (allowAssignUser != ProcessActionTerm.NOT_ASSIGNED) {
dossierUser.setModerator(1);
dossierUserLocalService.updateDossierUser(dossierUser.getDossierId(), dossierUser.getUserId(),
dossierUser.getModerator(), dossierUser.getVisited());
// model.setModerator(dossierUser.getModerator());
moderator = dossierUser.getModerator();
}
}
else {
if (allowAssignUser != ProcessActionTerm.NOT_ASSIGNED) {
dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userIdAssigned, 1, true);
}
}
// org.opencps.dossiermgt.model.DossierActionUser dau = DossierActionUserLocalServiceUtil.fetchDossierActionUser(pk);
org.opencps.dossiermgt.model.DossierActionUser dau = null;
// dau = mapDaus.get(userIdAssigned);
if (mapDaus.get(dossierAction.getDossierActionId()) != null) {
dau = mapDaus.get(dossierAction.getDossierActionId()).get(userIdAssigned);
}
if (dau == null) {
// DossierAction dAction = DossierActionLocalServiceUtil.fetchDossierAction(dossierAction.getDossierActionId());
DossierAction dAction = dossierAction;
if (dAction != null) {
addDossierActionUserByAssigned(groupId, allowAssignUser, userIdAssigned, dossierAction.getDossierActionId(), moderator, false,
dAction.getStepCode(), dossier.getDossierId(), assigned, 0);
}
// else {
// addDossierActionUserByAssigned(allowAssignUser, userIdAssigned, dossierAction.getDossierActionId(), moderator, false,
// StringPool.BLANK, dossier.getDossierId(), assigned);
// }
}
else {
dau.setModerator(1);
dau.setAssigned(assigned);
dossierActionUserLocalService.updateDossierActionUser(dau);
}
}
else if (subUser != null && subUser.has(DossierActionUserTerm.ASSIGNED)
&& subUser.getInt(DossierActionUserTerm.ASSIGNED) == DossierActionUserTerm.NOT_ASSIGNED) {
// model = new org.opencps.dossiermgt.model.impl.DossierActionUserImpl();
DossierActionUserPK pk = new DossierActionUserPK();
pk.setDossierActionId(dossierAction.getDossierActionId());
pk.setUserId(subUser.getLong(Field.USER_ID));
org.opencps.dossiermgt.model.DossierActionUser dau = dossierActionUserLocalService.fetchDossierActionUser(pk);
if (Validator.isNull(dau)) {
}
else {
dau.setModerator(0);
dossierActionUserLocalService.updateDossierActionUser(dau);
}
}
}
}
private void addDossierActionUserByAssigned(long groupId, int allowAssignUser, long userId, long dossierActionId,
int moderator, boolean visited, String stepCode, long dossierId, int assigned, int delegacy) {
org.opencps.dossiermgt.model.DossierActionUser model = new org.opencps.dossiermgt.model.impl.DossierActionUserImpl();
// int assigned = DossierActionUserTerm.NOT_ASSIGNED;
model.setVisited(visited);
model.setDossierId(dossierId);
model.setStepCode(stepCode);
model.setAssigned(assigned);
model.setDelegacy(delegacy);
//Check employee is exits and wokingStatus
Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId);
_log.debug("Employee : " + employee);
_log.debug("ADD DOSSIER ACTION USER ASSIGNED : " + stepCode);
if (employee != null && employee.getWorkingStatus() == 1) {
DossierActionUserPK pk = new DossierActionUserPK(dossierActionId, userId);
org.opencps.dossiermgt.model.DossierActionUser dau = dossierActionUserLocalService.fetchDossierActionUser(pk);
model.setUserId(userId);
model.setDossierActionId(dossierActionId);
model.setModerator(moderator);
// if (allowAssignUser == ProcessActionTerm.NOT_ASSIGNED) {
// model.setUserId(userId);
// model.setDossierActionId(dossierActionId);
// model.setModerator(moderator);
// if (moderator == 1) {
// model.setAssigned(1);
// } else {
// model.setAssigned(assigned);
// }
// if (dau == null) {
// dossierActionUserLocalService.addDossierActionUser(model);
// }
// else {
// if (dau.getModerator() != DossierActionUserTerm.ASSIGNED_TH
// && model.getModerator() == DossierActionUserTerm.ASSIGNED_TH) {
// dossierActionUserLocalService.updateDossierActionUser(model);
// }
// }
// }
// else if (allowAssignUser == ProcessActionTerm.ASSIGNED_TH) {
// _log.debug("Assign dau: " + userId);
// model.setUserId(userId);
// model.setDossierActionId(dossierActionId);
// model.setModerator(moderator);
// assigned = DossierActionUserTerm.ASSIGNED_TH;
// model.setAssigned(assigned);
// if (dau == null) {
// _log.debug("Assign add dau: " + userId);
// dossierActionUserLocalService.addDossierActionUser(model);
// }
// else {
// if (dau.getModerator() != DossierActionUserTerm.ASSIGNED_TH
// && model.getModerator() == DossierActionUserTerm.ASSIGNED_TH) {
// _log.debug("Assign update dau: " + userId);
// dossierActionUserLocalService.updateDossierActionUser(model);
// }
// }
// }
// else if (allowAssignUser == ProcessActionTerm.ASSIGNED_TH_PH) {
// model.setUserId(userId);
// model.setDossierActionId(dossierActionId);
// model.setModerator(moderator);
// assigned = DossierActionUserTerm.ASSIGNED_TH;
// model.setAssigned(assigned);
// dossierActionUserLocalService.addDossierActionUser(model);
//
// model.setUserId(userId);
// model.setDossierActionId(dossierActionId);
// model.setModerator(moderator);
// model.setVisited(true);
// assigned = DossierActionUserTerm.ASSIGNED_PH;
// model.setAssigned(assigned);
// if (dau == null) {
// dossierActionUserLocalService.addDossierActionUser(model);
// }
// else {
// if (dau.getModerator() != DossierActionUserTerm.ASSIGNED_TH
// && model.getModerator() == DossierActionUserTerm.ASSIGNED_TH) {
// dossierActionUserLocalService.updateDossierActionUser(model);
// }
// }
// }
// else if (allowAssignUser == ProcessActionTerm.ASSIGNED_TH_PH_TD) {
// model.setUserId(userId);
// model.setDossierActionId(dossierActionId);
// model.setModerator(moderator);
// assigned = DossierActionUserTerm.ASSIGNED_TH;
// model.setAssigned(assigned);
// dossierActionUserLocalService.addDossierActionUser(model);
//
// model.setUserId(userId);
// model.setDossierActionId(dossierActionId);
// model.setModerator(moderator);
// assigned = DossierActionUserTerm.ASSIGNED_PH;
// model.setAssigned(assigned);
// dossierActionUserLocalService.addDossierActionUser(model);
//
// model.setUserId(userId);
// model.setDossierActionId(dossierActionId);
// model.setModerator(moderator);
// assigned = DossierActionUserTerm.ASSIGNED_TD;
// model.setAssigned(assigned);
// if (dau == null) {
// dossierActionUserLocalService.addDossierActionUser(model);
// }
// else {
// if (dau.getModerator() != DossierActionUserTerm.ASSIGNED_TH
// && model.getModerator() == DossierActionUserTerm.ASSIGNED_TH) {
// dossierActionUserLocalService.updateDossierActionUser(model);
// }
// }
// }
_log.debug("DOSSIER ACTION ASSIGNED USER: " + dau);
if (dau == null) {
dossierActionUserLocalService.addDossierActionUser(model);
}
else {
dossierActionUserLocalService.updateDossierActionUser(model);
}
}
}
public void initDossierActionUser(ProcessAction processAction, Dossier dossier, int allowAssignUser, DossierAction dossierAction, long userId, long groupId, long assignUserId)
throws PortalException {
// Delete record in dossierActionUser
List<org.opencps.dossiermgt.model.DossierActionUser> dossierActionUser = dossierActionUserLocalService
.getListUser(dossierAction.getDossierActionId());
if (dossierActionUser != null && dossierActionUser.size() > 0) {
dossierActionUserLocalService.deleteByDossierAction(dossierAction.getDossierActionId());
}
long serviceProcessId = dossierAction.getServiceProcessId();
String stepCode = processAction.getPostStepCode();
// Get ProcessStep
ProcessStep processStep = processStepLocalService.fetchBySC_GID(stepCode, groupId, serviceProcessId);
long processStepId = processStep.getProcessStepId();
int assigned;
// Get List ProcessStepRole
List<ProcessStepRole> listProcessStepRole = processStepRoleLocalService.findByP_S_ID(processStepId);
ProcessStepRole processStepRole = null;
List<DossierAction> lstStepActions = dossierActionLocalService.getByDID_FSC_NOT_DAI(dossier.getDossierId(), stepCode, dossierAction.getDossierActionId());
if (listProcessStepRole.size() != 0) {
for (int i = 0; i < listProcessStepRole.size(); i++) {
processStepRole = listProcessStepRole.get(i);
long roleId = processStepRole.getRoleId();
boolean moderator = processStepRole.getModerator();
int mod = 0;
if (moderator) {
mod = 1;
}
// Get list user
List<User> users = UserLocalServiceUtil.getRoleUsers(roleId);
for (User user : users) {
Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(dossier.getGroupId(), user.getUserId());
//_log.debug("Employee : " + employee);
if (employee != null && employee.getWorkingStatus() == 1
&& (Validator.isNull(employee.getScope()) || (Validator.isNotNull(employee.getScope()) && dossier.getGovAgencyCode().contentEquals(employee.getScope())))) {
List<DossierAction> lstDoneActions = dossierActionLocalService
.getByDID_U_FSC(dossier.getDossierId(), user.getUserId(), stepCode);
if (!lstStepActions.isEmpty()) {
if (!lstDoneActions.isEmpty())
mod = 1;
else
mod = 0;
}
if (moderator) {
assigned = DossierActionUserTerm.ASSIGNED_TH;
}
else {
assigned = DossierActionUserTerm.NOT_ASSIGNED;
}
updateDossierUser(dossier, processStepRole, user);
List<DossierActionUser> lstDau = dossierActionUserLocalService.getByDossierUserAndStepCode(dossier.getDossierId(), user.getUserId(), stepCode);
DossierActionUser lastDau = (lstDau.size() > 0 ? lstDau.get(0) : null);
for (DossierActionUser dau : lstDau) {
if (dau.getDossierActionId() > lastDau.getDossierActionId()) {
lastDau = dau;
}
}
if (lastDau != null) {
addDossierActionUserByAssigned(groupId, processAction.getAllowAssignUser(), user.getUserId(),
dossierAction.getDossierActionId(), lastDau.getModerator(), false, stepCode, dossier.getDossierId(), lastDau.getAssigned(), lastDau.getDelegacy());
}
else {
addDossierActionUserByAssigned(groupId, processAction.getAllowAssignUser(), user.getUserId(),
dossierAction.getDossierActionId(), mod, false, stepCode, dossier.getDossierId(), assigned, 0);
}
}
}
}
}
else {
//Get role from service process
initDossierActionUserByServiceProcessRole(dossier, allowAssignUser, dossierAction, userId, groupId, assignUserId);
}
}
private void updateDossierUser(Dossier dossier, ProcessStepRole processStepRole, User user) {
DossierUserPK pk = new DossierUserPK();
pk.setDossierId(dossier.getDossierId());
pk.setUserId(user.getUserId());
DossierUser du = dossierUserLocalService.fetchDossierUser(pk);
if (du == null) {
dossierUserLocalService.addDossierUser(dossier.getGroupId(), dossier.getDossierId(), user.getUserId(), processStepRole.getModerator() ? 1 : 0, true);
}
else {
try {
if ((processStepRole.getModerator() && du.getModerator() != DossierActionUserTerm.ASSIGNED_PH)
|| (!processStepRole.getModerator() && du.getModerator() != DossierActionUserTerm.ASSIGNED_PH)) {
dossierUserLocalService.updateDossierUser(dossier.getDossierId(), user.getUserId(), du.getModerator() == 0 ? (processStepRole.getModerator() ? 1 : 0) : 1, true);
}
} catch (NoSuchDossierUserException e) {
_log.error(e);
}
}
}
private boolean checkGovDossierEmployee(Dossier dossier, Employee e) {
if (e != null && (Validator.isNull(e.getScope()) || (dossier.getGovAgencyCode().contentEquals(e.getScope())))) {
return true;
}
return false;
}
private void initDossierActionUserByServiceProcessRole(Dossier dossier, int allowAssignUser, DossierAction dossierAction, long userId, long groupId, long assignUserId) {
try {
Map<Long, Employee> mapEmps = new HashMap<Long, Employee>();
List<Employee> lstEmps = EmployeeLocalServiceUtil.findByG(dossier.getGroupId());
for (Employee e : lstEmps) {
mapEmps.put(e.getMappingUserId(), e);
}
ServiceProcess serviceProcess = serviceProcessLocalService.getServiceByCode(groupId, dossier.getServiceCode(), dossier.getGovAgencyCode(), dossier.getDossierTemplateNo());
List<ServiceProcessRole> listSprs = serviceProcessRoleLocalService.findByS_P_ID(serviceProcess.getServiceProcessId());
DossierAction da = dossierAction;
for (ServiceProcessRole spr : listSprs) {
int mod = 0;
boolean moderator = spr.getModerator();
if (moderator) {
mod = 1;
}
List<User> users = UserLocalServiceUtil.getRoleUsers(spr.getRoleId());
for (User user : users) {
if (mapEmps.containsKey(user.getUserId())) {
Employee e = mapEmps.get(user.getUserId());
if (checkGovDossierEmployee(dossier, e)) {
int assigned = user.getUserId() == assignUserId ? DossierActionUserTerm.ASSIGNED_TH : (moderator ? DossierActionUserTerm.ASSIGNED_TH : DossierActionUserTerm.NOT_ASSIGNED);
org.opencps.dossiermgt.model.DossierActionUser dau = dossierActionUserLocalService.getByDossierAndUser(dossierAction.getDossierActionId(), user.getUserId());
if (dau != null) {
dau.setModerator(mod);
dau.setAssigned(assigned);
dossierActionUserLocalService.updateDossierActionUser(dau);
} else {
addDossierActionUserByAssigned(groupId, allowAssignUser, user.getUserId(), dossierAction.getDossierActionId(), mod, false, da.getStepCode(), dossier.getDossierId(), assigned, 0);
}
}
}
}
}
} catch (PortalException e) {
_log.error(e);
}
}
private void copyRoleAsStep(ProcessStep curStep, Dossier dossier) {
if (Validator.isNull(curStep.getRoleAsStep()))
return;
String[] stepCodeArr = StringUtil.split(curStep.getRoleAsStep());
Map<Long, Employee> mapEmps = new HashMap<Long, Employee>();
List<Employee> lstEmps = EmployeeLocalServiceUtil.findByG(dossier.getGroupId());
for (Employee e : lstEmps) {
mapEmps.put(e.getMappingUserId(), e);
}
if (stepCodeArr.length > 0) {
for (String stepCode : stepCodeArr) {
if (stepCode.startsWith(StringPool.EXCLAMATION)) {
int index = stepCode.indexOf(StringPool.EXCLAMATION);
String stepCodePunc = stepCode.substring(index + 1);
List<org.opencps.dossiermgt.model.DossierActionUser> lstDaus = dossierActionUserLocalService.getByDossierAndStepCode(dossier.getDossierId(), stepCodePunc);
List<DossierAction> lstDossierActions = dossierActionLocalService.findDossierActionByDID_STEP(dossier.getDossierId(), stepCodePunc);
try {
for (org.opencps.dossiermgt.model.DossierActionUser dau : lstDaus) {
boolean flagDA = false;
for (DossierAction da : lstDossierActions) {
if (da.getUserId() == dau.getUserId()) {
flagDA = true;
break;
}
}
if (flagDA) {
DossierUserPK duPk = new DossierUserPK();
duPk.setDossierId(dossier.getDossierId());
duPk.setUserId(dau.getUserId());
int moderator = dau.getModerator();
DossierUser duModel = dossierUserLocalService.fetchDossierUser(duPk);
if (duModel == null) {
dossierUserLocalService.addDossierUser(dossier.getGroupId(), dossier.getDossierId(),
dau.getUserId(), moderator, true);
}
else {
try {
if (duModel.getModerator() == 0 && moderator == 1) {
dossierUserLocalService.updateDossierUser(dossier.getDossierId(), dau.getUserId(),
moderator, true);
}
} catch (NoSuchDossierUserException e) {
// e.printStackTrace();
_log.error(e);
}
}
DossierActionUserPK dauPk = new DossierActionUserPK();
dauPk.setDossierActionId(dossier.getDossierActionId());
dauPk.setUserId(dau.getUserId());
int assigned = moderator == 1 ? 1 : 0;
dossierActionUserLocalService.addOrUpdateDossierActionUser(dau.getUserId(), dossier.getGroupId(), dossier.getDossierActionId(), dossier.getDossierId(), curStep.getStepCode(), moderator, assigned, true);
}
}
}
catch (Exception e) {
_log.error(e);
}
}
else {
ServiceProcess serviceProcess = null;
try {
serviceProcess = serviceProcessLocalService.getServiceByCode(dossier.getGroupId(), dossier.getServiceCode(), dossier.getGovAgencyCode(), dossier.getDossierTemplateNo());
if (serviceProcess != null) {
ProcessStep processStep = processStepLocalService.fetchBySC_GID(stepCode, dossier.getGroupId(), serviceProcess.getServiceProcessId());
if (processStep == null) continue;
List<ProcessStepRole> lstRoles = processStepRoleLocalService.findByP_S_ID(processStep.getProcessStepId());
for (ProcessStepRole psr : lstRoles) {
List<User> users = UserLocalServiceUtil.getRoleUsers(psr.getRoleId());
for (User u : users) {
if (mapEmps.containsKey(u.getUserId())) {
Employee emp = mapEmps.get(u.getUserId());
if (checkGovDossierEmployee(dossier, emp)) {
DossierUserPK duPk = new DossierUserPK();
duPk.setDossierId(dossier.getDossierId());
duPk.setUserId(u.getUserId());
int moderator = (psr.getModerator() ? 1 : 0);
DossierUser duModel = dossierUserLocalService.fetchDossierUser(duPk);
if (duModel == null) {
dossierUserLocalService.addDossierUser(dossier.getGroupId(), dossier.getDossierId(),
u.getUserId(), moderator, true);
}
else {
try {
if (duModel.getModerator() == 0 && moderator == 1) {
dossierUserLocalService.updateDossierUser(dossier.getDossierId(), u.getUserId(),
moderator, true);
}
} catch (NoSuchDossierUserException e) {
_log.error(e);
}
}
DossierActionUserPK dauPk = new DossierActionUserPK();
dauPk.setDossierActionId(dossier.getDossierActionId());
dauPk.setUserId(u.getUserId());
int assigned = moderator == 1 ? 1 : 0;
dossierActionUserLocalService.addOrUpdateDossierActionUser(u.getUserId(), dossier.getGroupId(), dossier.getDossierActionId(), dossier.getDossierId(), curStep.getStepCode(), moderator, assigned, true);
}
}
}
}
}
} catch (PortalException e) {
_log.error(e);
}
}
}
}
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public Dossier addDossier(long groupId, Company company, User user, ServiceContext serviceContext,
DossierInputModel input) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
DossierPermission dossierPermission = new DossierPermission();
long start = System.currentTimeMillis();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
ProcessOption option = getProcessOption(input.getServiceCode(), input.getGovAgencyCode(),
input.getDossierTemplateNo(), groupId);
long serviceProcessId = 0;
if (option != null) {
serviceProcessId = option.getServiceProcessId();
}
boolean flag = false;
long userId = serviceContext.getUserId();
Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId);
if (employee != null) {
long employeeId = employee.getEmployeeId();
if (employeeId > 0) {
List<EmployeeJobPos> empJobList = EmployeeJobPosLocalServiceUtil.findByF_EmployeeId(employeeId);
if (empJobList != null && empJobList.size() > 0) {
for (EmployeeJobPos employeeJobPos : empJobList) {
long jobPosId = employeeJobPos.getJobPostId();
if (jobPosId > 0) {
JobPos job = JobPosLocalServiceUtil.fetchJobPos(jobPosId);
if (job != null) {
ServiceProcessRolePK pk = new ServiceProcessRolePK(serviceProcessId,
job.getMappingRoleId());
ServiceProcessRole role = serviceProcessRoleLocalService
.fetchServiceProcessRole(pk);
if (role != null && role.getModerator()) {
flag = true;
break;
}
}
}
}
}
}
} else {
flag = true;
}
if (!flag) {
throw new UnauthenticationException("No permission create dossier");
}
_log.debug("CREATE DOSSIER 1: " + (System.currentTimeMillis() - start) + " ms");
_log.debug("CREATE DOSSIER 1.X: " + input.getServiceCode() + ", " + input.getGovAgencyCode() + ", " + input.getDossierTemplateNo());
dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(),
input.getGovAgencyCode(), input.getDossierTemplateNo());
//int counter = DossierNumberGenerator.counterDossier(user.getUserId(), groupId);
String referenceUid = input.getReferenceUid();
int counter = 0;
// Create dossierNote
ServiceProcess process = null;
boolean online = GetterUtil.getBoolean(input.getOnline());
int originality = GetterUtil.getInteger(input.getOriginality());
Integer viaPostal = input.getViaPostal();
ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, input.getServiceCode(),
input.getGovAgencyCode());
if (config != null && Validator.isNotNull(viaPostal)) {
viaPostal = config.getPostService() ? (viaPostal == 0 ? 1 : viaPostal) : 0;
}
else if (config != null) {
viaPostal = config.getPostService() ? 1 : 0;
}
if (option != null) {
process = serviceProcessLocalService.getServiceProcess(serviceProcessId);
}
if (process == null) {
throw new NotFoundException("Cant find process");
}
if (Validator.isNull(referenceUid) || referenceUid.trim().length() == 0)
referenceUid = DossierNumberGenerator.generateReferenceUID(groupId);
//Dossier checkDossier = dossierLocalService.getByRef(groupId, referenceUid);
//if (checkDossier != null) {
// return checkDossier;
//}
ServiceInfo service = serviceInfoLocalService.getByCode(groupId, input.getServiceCode());
String serviceName = StringPool.BLANK;
if (service != null) {
serviceName = service.getServiceName();
}
String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, input.getGovAgencyCode());
DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(ADMINISTRATIVE_REGION, groupId);
String cityName = getDictItemName(groupId, dc, input.getCityCode());
String districtName = getDictItemName(groupId, dc, input.getDistrictCode());
String wardName = getDictItemName(groupId, dc, input.getWardCode());
// _log.info("Service code: " + input.getServiceCode());
_log.debug("===ADD DOSSIER CITY NAME:" + cityName);
String password = StringPool.BLANK;
if (Validator.isNotNull(input.getPassword())) {
password = input.getPassword();
} else if (Validator.isNotNull(process.getGeneratePassword()) && process.getGeneratePassword()) {
_log.debug("DOSSIER SECRET LENGTH: " + OpenCPSConfigUtil.getDefaultDossierSecretLength());
if (OpenCPSConfigUtil.getDefaultDossierSecretLength() > DossierTerm.PIN_LENGTH) {
password = PwdGenerator.getPassword(OpenCPSConfigUtil.getDefaultDossierSecretLength(), PwdGenerator.KEY1);
}
else {
password = PwdGenerator.getPinNumber();
}
}
String postalCityName = StringPool.BLANK;
if (Validator.isNotNull(input.getPostalCityCode())) {
postalCityName = getDictItemName(groupId, VNPOST_CITY_CODE, input.getPostalCityCode());
}
Long sampleCount = (option != null ? option.getSampleCount() : 1l);
String registerBookCode = (option != null ? (Validator.isNotNull(option.getRegisterBookCode()) ? option.getRegisterBookCode() : StringPool.BLANK) : StringPool.BLANK);
//String registerBookName = (Validator.isNotNull(registerBookCode) ? getDictItemName(groupId, REGISTER_BOOK, registerBookCode) : StringPool.BLANK);
String registerBookName = StringPool.BLANK;
if (Validator.isNotNull(registerBookCode)) {
DynamicReport report = DynamicReportLocalServiceUtil.fetchByG_CODE(groupId, registerBookCode);
if (report != null) {
registerBookName = report.getReportName();
}
}
// Process group dossier
if (originality == 9) {
_log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date appIdDate = null;
try {
appIdDate = sdf.parse(input.getApplicantIdDate());
} catch (Exception e) {
_log.debug(e);
}
Dossier dossier = dossierLocalService.initDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName,
input.getGovAgencyCode(), govAgencyName, input.getApplicantName(), input.getApplicantIdType(),
input.getApplicantIdNo(), appIdDate, input.getAddress(), input.getCityCode(),
cityName, input.getDistrictCode(), districtName, input.getWardCode(), wardName,
input.getContactName(), input.getContactTelNo(), input.getContactEmail(),
input.getDossierTemplateNo(), password, viaPostal, input.getPostalAddress(), input.getPostalCityCode(), postalCityName,
input.getPostalTelNo(), online, process.getDirectNotification(), input.getApplicantNote(),
Integer.valueOf(input.getOriginality()),
service, process, option,
serviceContext);
if (Validator.isNotNull(input.getDossierName())) {
dossier.setDossierName(input.getDossierName());
} else {
dossier.setDossierName(serviceName);
}
dossier.setSampleCount(sampleCount);
dossier.setSystemId(input.getSystemId());
//Delegate dossier
dossier.setDelegateType(input.getDelegateType() != null ? input.getDelegateType() : 0);
if (Validator.isNotNull(input.getDocumentNo())) {
dossier.setDocumentNo(input.getDocumentNo());
}
if (input.getDocumentDate() != null && 0 != input.getDocumentDate()) {
dossier.setDocumentDate(new Date(input.getDocumentDate()));
}
if (Validator.isNotNull(input.getMetaData()))
dossier.setMetaData(input.getMetaData());
updateDelegateApplicant(dossier, input);
// Process update dossierNo
// LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();
// params.put(DossierTerm.GOV_AGENCY_CODE, dossier.getGovAgencyCode());
// params.put(DossierTerm.SERVICE_CODE, dossier.getServiceCode());
// params.put(DossierTerm.DOSSIER_TEMPLATE_NO, dossier.getDossierTemplateNo());
// params.put(DossierTerm.DOSSIER_STATUS, StringPool.BLANK);
if (option != null) {
//Process submition note
dossier.setSubmissionNote(option.getSubmissionNote());
// String dossierRef = DossierNumberGenerator.generateDossierNumber(groupId, dossier.getCompanyId(),
// dossier.getDossierId(), option.getProcessOptionId(), process.getDossierGroupPattern(), params);
// dossier.setDossierNo(dossierRef.trim());
}
dossier.setViaPostal(1);
_log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms");
if (Validator.isNull(dossier)) {
throw new NotFoundException("Can't add DOSSIER");
}
_log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms");
//Create DossierMark
_log.debug("originality: "+originality);
String templateNo = dossier.getDossierTemplateNo();
_log.debug("templateNo: "+templateNo);
if (Validator.isNotNull(input.getDossierMarkArr())) {
JSONArray markArr = JSONFactoryUtil.createJSONArray(input.getDossierMarkArr());
if (markArr != null && markArr.length() > 0) {
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId());
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
for (int i = 0; i < markArr.length(); i++) {
JSONObject jsonMark = markArr.getJSONObject(i);
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[markArr.length()];
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(jsonMark.getString("partNo"));
model.setFileCheck(0);
model.setFileMark(jsonMark.getInt("fileMark"));
model.setFileComment(StringPool.BLANK);
model.setRecordCount(StringPool.BLANK);
marks[i] = model;
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
}
}
} else if (Validator.isNotNull(templateNo)) {
List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo);
// _log.info("partList: "+partList);
if (partList != null && partList.size() > 0) {
_log.debug("partList.size(): "+partList.size());
_log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms");
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()];
int count = 0;
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId());
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
for (DossierPart dossierPart : partList) {
int fileMark = dossierPart.getFileMark();
String dossierPartNo = dossierPart.getPartNo();
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(dossierPartNo);
model.setFileCheck(0);
model.setFileMark(fileMark);
model.setFileComment(StringPool.BLANK);
model.setRecordCount(StringPool.BLANK);
marks[count++] = model;
}
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
_log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms");
}
}
//Create dossier user
List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId());
List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId());
if (lstDus.size() == 0) {
DossierUserActions duActions = new DossierUserActionsImpl();
duActions.initDossierUser(groupId, dossier, process, lstProcessRoles);
}
// if (originality == DossierTerm.ORIGINALITY_DVCTT) {
// dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true);
// }
_log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms");
//Add to dossier user based on service process role
createDossierUsers(groupId, dossier, process, lstProcessRoles);
if (Validator.isNotNull(input.getVnpostalStatus())) {
dossier.setVnpostalStatus(input.getVnpostalStatus());
}
if (Validator.isNotNull(input.getVnpostalProfile())) {
dossier.setVnpostalProfile(input.getVnpostalProfile());
}
if (Validator.isNotNull(input.getServerNo())) {
dossier.setServerNo(input.getServerNo());
}
_log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms");
return dossierLocalService.updateDossier(dossier);
} else {
List<Dossier> oldDossiers = dossierLocalService.getByU_G_GAC_SC_DTNO_DS_O(
userId, groupId, input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo(), StringPool.BLANK, Integer.valueOf(input.getOriginality()));
Dossier dossier = null;
Dossier oldRefDossier = Validator.isNotNull(input.getReferenceUid()) ? dossierLocalService.getByRef(groupId, input.getReferenceUid()) : null;
if (originality == DossierTerm.ORIGINALITY_DVCTT) {
online = true;
}
boolean flagOldDossier = false;
_log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms");
if (oldRefDossier != null) {
//Check old cross dossier rollback
if (oldRefDossier.getOriginality() < 0 && Validator.isNotNull(input.getOriginDossierNo())) {
oldRefDossier.setOriginality(-oldRefDossier.getOriginality());
}
dossier = oldRefDossier;
dossier.setSubmitDate(new Date());
dossier.setReceiveDate(new Date());
ServiceProcess serviceProcess = process;
double durationCount = 0;
int durationUnit = 0;
if (serviceProcess != null ) {
durationCount = serviceProcess.getDurationCount();
durationUnit = serviceProcess.getDurationUnit();
dossier.setDurationCount(durationCount);
dossier.setDurationUnit(durationUnit);
}
if (durationCount > 0) {
// Date dueDate = HolidayUtils.getDueDate(new Date(), durationCount, durationUnit, groupId);
DueDateUtils dueDateUtils = new DueDateUtils(new Date(), durationCount, durationUnit, groupId);
Date dueDate = dueDateUtils.getDueDate();
dossier.setDueDate(dueDate);
}
//Delegate
//Delegate dossier
dossier.setDelegateType(input.getDelegateType() != null ? input.getDelegateType() : 0);
if (Validator.isNotNull(input.getDocumentNo())) {
dossier.setDocumentNo(input.getDocumentNo());
}
if (input.getDocumentDate() != null && 0 != input.getDocumentDate()) {
dossier.setDocumentDate(new Date(input.getDocumentDate()));
}
}
else if (oldDossiers.size() > 0) {
flagOldDossier = true;
dossier = oldDossiers.get(0);
dossier.setApplicantName(input.getApplicantName());
dossier.setApplicantNote(input.getApplicantNote());
dossier.setApplicantIdNo(input.getApplicantIdNo());
dossier.setAddress(input.getAddress());
dossier.setContactEmail(input.getContactEmail());
dossier.setContactName(input.getContactName());
dossier.setContactTelNo(input.getContactTelNo());
dossier.setDelegateName(input.getDelegateName());
dossier.setDelegateEmail(input.getDelegateEmail());
dossier.setDelegateAddress(input.getDelegateAddress());
dossier.setPostalAddress(input.getPostalAddress());
dossier.setPostalCityCode(input.getPostalCityCode());
dossier.setPostalCityName(postalCityName);
dossier.setPostalTelNo(input.getPostalTelNo());
dossier.setPostalServiceCode(input.getPostalServiceCode());
dossier.setPostalServiceName(input.getPostalServiceName());
dossier.setPostalDistrictCode(input.getPostalDistrictCode());
dossier.setPostalDistrictName(input.getPostalDistrictName());
dossier.setPostalWardCode(input.getPostalWardCode());
dossier.setPostalWardName(input.getPostalWardName());
dossier.setPostalTelNo(input.getPostalTelNo());
dossier.setViaPostal(viaPostal);
dossier.setOriginDossierNo(input.getOriginDossierNo());
if (Validator.isNotNull(registerBookCode)) {
dossier.setRegisterBookCode(registerBookCode);
}
dossier.setRegisterBookName(registerBookName);
dossier.setSampleCount(sampleCount);
dossier.setServiceCode(input.getServiceCode());
dossier.setGovAgencyCode(input.getGovAgencyCode());
dossier.setDossierTemplateNo(input.getDossierTemplateNo());
updateDelegateApplicant(dossier, input);
// dossier.setDossierNo(input.getDossierNo());
dossier.setSubmitDate(new Date());
// ServiceProcess serviceProcess = ServiceProcessLocalServiceUtil.fetchServiceProcess(serviceProcessId);
ServiceProcess serviceProcess = process;
double durationCount = 0;
int durationUnit = 0;
if (serviceProcess != null ) {
durationCount = serviceProcess.getDurationCount();
durationUnit = serviceProcess.getDurationUnit();
dossier.setDurationCount(durationCount);
dossier.setDurationUnit(durationUnit);
}
if (durationCount > 0) {
// Date dueDate = HolidayUtils.getDueDate(new Date(), durationCount, durationUnit, groupId);
DueDateUtils dueDateUtils = new DueDateUtils(new Date(), durationCount, durationUnit, groupId);
Date dueDate = dueDateUtils.getDueDate();
dossier.setDueDate(dueDate);
}
dossier.setOnline(online);
if (Validator.isNotNull(input.getDossierName()))
dossier.setDossierName(input.getDossierName());
if (serviceProcess != null) {
dossier.setProcessNo(serviceProcess.getProcessNo());
}
//Delegate dossier
dossier.setDelegateType(input.getDelegateType() != null ? input.getDelegateType() : 0);
if (Validator.isNotNull(input.getDocumentNo())) {
dossier.setDocumentNo(input.getDocumentNo());
}
if (input.getDocumentDate() != null && 0 != input.getDocumentDate()) {
dossier.setDocumentDate(new Date(input.getDocumentDate()));
}
// dossier = DossierLocalServiceUtil.updateDossier(dossier);
}
else {
SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
Date appIdDate = null;
try {
appIdDate = sdf.parse(input.getApplicantIdDate());
} catch (Exception e) {
_log.debug(e);
}
dossier = dossierLocalService.initDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName,
input.getGovAgencyCode(), govAgencyName, input.getApplicantName(), input.getApplicantIdType(),
input.getApplicantIdNo(), appIdDate, input.getAddress(), input.getCityCode(),
cityName, input.getDistrictCode(), districtName, input.getWardCode(), wardName,
input.getContactName(), input.getContactTelNo(), input.getContactEmail(),
input.getDossierTemplateNo(), password, viaPostal, input.getPostalAddress(), input.getPostalCityCode(), postalCityName,
input.getPostalTelNo(), online, process.getDirectNotification(), input.getApplicantNote(),
Integer.valueOf(input.getOriginality()),
service, process, option,
serviceContext);
dossier.setDelegateName(input.getDelegateName());
dossier.setDelegateEmail(input.getDelegateEmail());
dossier.setDelegateAddress(input.getDelegateAddress());
if (Validator.isNotNull(input.getDossierName())) {
dossier.setDossierName(input.getDossierName());
} else {
dossier.setDossierName(serviceName);
}
dossier.setPostalCityName(postalCityName);
dossier.setPostalTelNo(input.getPostalTelNo());
dossier.setPostalServiceCode(input.getPostalServiceCode());
dossier.setPostalServiceName(input.getPostalServiceName());
dossier.setPostalDistrictCode(input.getPostalDistrictCode());
dossier.setPostalDistrictName(input.getPostalDistrictName());
dossier.setPostalWardCode(input.getPostalWardCode());
dossier.setPostalWardName(input.getPostalWardName());
dossier.setOriginDossierNo(input.getOriginDossierNo());
//dossier.setRegisterBookCode(registerBookCode);
//dossier.setRegisterBookName(registerBookName);
dossier.setSampleCount(sampleCount);
dossier.setSystemId(input.getSystemId());
if (Validator.isNotNull(input.getMetaData()))
dossier.setMetaData(input.getMetaData());
//Delegate dossier
if (Validator.isNotNull(input.getDelegateType())) {
dossier.setDelegateType(input.getDelegateType());
}
if (Validator.isNotNull(input.getDocumentNo())) {
dossier.setDocumentNo(input.getDocumentNo());
}
if (input.getDocumentDate() != null && 0 != input.getDocumentDate()) {
dossier.setDocumentDate(new Date(input.getDocumentDate()));
}
updateDelegateApplicant(dossier, input);
//if (process != null) {
// dossier.setProcessNo(process.getProcessNo());
//}
// dossier = DossierLocalServiceUtil.updateDossier(dossier);
}
_log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms");
if (originality != DossierTerm.ORIGINALITY_LIENTHONG) {
Applicant applicant = ApplicantLocalServiceUtil.fetchByMappingID(serviceContext.getUserId());
if (applicant != null) {
updateApplicantInfo(dossier,
applicant.getApplicantIdDate(),
applicant.getApplicantIdNo(),
applicant.getApplicantIdType(),
applicant.getApplicantName(),
applicant.getAddress(),
applicant.getCityCode(),
applicant.getCityName(),
applicant.getDistrictCode(),
applicant.getDistrictName(),
applicant.getWardCode(),
applicant.getWardName(),
applicant.getContactEmail(),
applicant.getContactTelNo()
);
}
}
if (Validator.isNull(dossier)) {
throw new NotFoundException("Cant add DOSSIER");
}
_log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms");
//Create DossierMark
_log.debug("flagOldDossier: "+flagOldDossier);
_log.debug("originality: "+originality);
if ((originality == DossierTerm.ORIGINALITY_MOTCUA || originality == DossierTerm.ORIGINALITY_LIENTHONG)
&& !flagOldDossier) {
String templateNo = dossier.getDossierTemplateNo();
_log.debug("templateNo: "+templateNo);
if (Validator.isNotNull(templateNo)) {
List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo);
// _log.info("partList: "+partList);
if (partList != null && partList.size() > 0) {
_log.debug("partList.size(): "+partList.size());
_log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms");
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()];
int count = 0;
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId());
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
for (DossierPart dossierPart : partList) {
int fileMark = dossierPart.getFileMark();
String dossierPartNo = dossierPart.getPartNo();
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(dossierPartNo);
model.setFileCheck(0);
model.setFileMark(fileMark);
model.setFileComment(StringPool.BLANK);
marks[count++] = model;
// DossierMarkLocalServiceUtil.addDossierMark(groupId, dossier.getDossierId(), dossierPartNo,
// fileMark, 0, StringPool.BLANK, serviceContext);
}
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
_log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms");
}
}
}
//Create dossier user
List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId());
List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId());
if (lstDus.size() == 0) {
DossierUserActions duActions = new DossierUserActionsImpl();
// duActions.initDossierUser(groupId, dossier);
duActions.initDossierUser(groupId, dossier, process, lstProcessRoles);
}
if (originality == DossierTerm.ORIGINALITY_DVCTT) {
dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true);
}
_log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms");
// DossierLocalServiceUtil.updateDossier(dossier);
if (dossier != null) {
//
//Check if have DOSSIER-01 template
Notificationtemplate dossierTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, NotificationType.DOSSIER_01);
if (dossierTemplate != null) {
long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName());
NotificationQueue queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId);
//Process add notification queue
Date now = new Date();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1);
queue.setCreateDate(now);
queue.setModifiedDate(now);
queue.setGroupId(groupId);
queue.setCompanyId(company.getCompanyId());
queue.setNotificationType(NotificationType.DOSSIER_01);
queue.setClassName(Dossier.class.getName());
queue.setClassPK(String.valueOf(dossier.getPrimaryKey()));
queue.setToUsername(dossier.getUserName());
queue.setToUserId(dossier.getUserId());
if (isEmailNotify(dossier)) {
queue.setToEmail(dossier.getContactEmail());
}
if (isSmsNotify(dossier)) {
queue.setToTelNo(dossier.getContactTelNo());
}
JSONObject payload = JSONFactoryUtil.createJSONObject();
try {
// _log.info("START PAYLOAD: ");
payload.put(
KeyPayTerm.DOSSIER, JSONFactoryUtil.createJSONObject(
JSONFactoryUtil.looseSerialize(dossier)));
}
catch (JSONException parse) {
_log.error(parse);
}
// _log.info("payloadTest: "+payload.toJSONString());
queue.setPayload(payload.toJSONString());
queue.setExpireDate(cal.getTime());
NotificationQueueLocalServiceUtil.addNotificationQueue(queue);
}
}
_log.debug("CREATE DOSSIER 6: " + (System.currentTimeMillis() - start) + " ms");
//Add to dossier user based on service process role
createDossierUsers(groupId, dossier, process, lstProcessRoles);
if (Validator.isNotNull(input.getVnpostalStatus())) {
dossier.setVnpostalStatus(input.getVnpostalStatus());
}
if (Validator.isNotNull(input.getVnpostalProfile())) {
dossier.setVnpostalProfile(input.getVnpostalProfile());
}
if (Validator.isNotNull(input.getServerNo())) {
dossier.setServerNo(input.getServerNo());
}
_log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms");
dossierLocalService.updateDossier(dossier);
_log.debug("CREATE DOSSIER 8: " + (System.currentTimeMillis() - start) + " ms");
//Check verification applicant
Applicant checkApplicant = ApplicantLocalServiceUtil.fetchByMappingID(user.getUserId());
if (checkApplicant != null) {
int countDossier = DossierLocalServiceUtil.countByG_UID_DS(groupId, user.getUserId(), DossierTerm.DOSSIER_STATUS_RECEIVING);
_log.debug("APPLICANT NUMBER OF CREATE DOSSIER: " + countDossier);
if (countDossier >= DossierTerm.MAX_DOSSIER_WITHOUT_VERIFICATION) {
if (checkApplicant.getVerification() != ApplicantTerm.UNLOCKED) {
checkApplicant.setVerification(ApplicantTerm.LOCKED_DOSSIER);
ApplicantLocalServiceUtil.updateApplicant(checkApplicant);
}
}
}
return dossier;
}
}
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { SystemException.class, PortalException.class,
Exception.class })
public Dossier addMultipleDossier(long groupId, Company company, User user, ServiceContext serviceContext,
DossierMultipleInputModel input) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
DossierPermission dossierPermission = new DossierPermission();
long start = System.currentTimeMillis();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
ProcessOption option = getProcessOption(input.getServiceCode(), input.getGovAgencyCode(),
input.getDossierTemplateNo(), groupId);
long serviceProcessId = 0;
if (option != null) {
serviceProcessId = option.getServiceProcessId();
}
boolean flag = false;
long userId = serviceContext.getUserId();
Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId);
if (employee != null) {
long employeeId = employee.getEmployeeId();
if (employeeId > 0) {
List<EmployeeJobPos> empJobList = EmployeeJobPosLocalServiceUtil.findByF_EmployeeId(employeeId);
if (empJobList != null && empJobList.size() > 0) {
for (EmployeeJobPos employeeJobPos : empJobList) {
long jobPosId = employeeJobPos.getJobPostId();
if (jobPosId > 0) {
JobPos job = JobPosLocalServiceUtil.fetchJobPos(jobPosId);
if (job != null) {
ServiceProcessRolePK pk = new ServiceProcessRolePK(serviceProcessId,
job.getMappingRoleId());
ServiceProcessRole role = serviceProcessRoleLocalService
.fetchServiceProcessRole(pk);
if (role != null && role.getModerator()) {
flag = true;
break;
}
}
}
}
}
}
} else {
flag = true;
}
if (!flag) {
throw new UnauthenticationException("No permission create dossier");
}
_log.debug("CREATE DOSSIER 1: " + (System.currentTimeMillis() - start) + " ms");
dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(),
input.getGovAgencyCode(), input.getDossierTemplateNo());
Dossier dossier = null;
if (Validator.isNotNull(input.getDossiers())) {
JSONObject jsonDossier = JSONFactoryUtil.createJSONObject(input.getDossiers());
//Get params input dossier
String referenceUid = jsonDossier.getString(DossierTerm.REFERENCE_UID);
if (Validator.isNull(referenceUid) || referenceUid.trim().length() == 0)
referenceUid = DossierNumberGenerator.generateReferenceUID(groupId);
int counter = 0;
//boolean online = GetterUtil.getBoolean(input.getOnline());
boolean online = false;
int originality = input.getOriginality();
int viaPostal = Validator.isNotNull(jsonDossier.getString(DossierTerm.VIA_POSTAL))
? GetterUtil.getInteger(jsonDossier.getString(DossierTerm.VIA_POSTAL)): 0;
ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, input.getServiceCode(),
input.getGovAgencyCode());
if (config != null && Validator.isNotNull(viaPostal)) {
viaPostal = config.getPostService() ? (viaPostal == 0 ? 1 : viaPostal) : 0;
} else if (config != null) {
viaPostal = config.getPostService() ? 1 : 0;
}
//Get service process
ServiceProcess process = null;
if (option != null) {
process = serviceProcessLocalService.getServiceProcess(serviceProcessId);
if (process == null) {
throw new NotFoundException("Cant find process");
}
}
ServiceInfo service = serviceInfoLocalService.getByCode(groupId, input.getServiceCode());
String serviceName = service != null ? service.getServiceName(): StringPool.BLANK;
String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, input.getGovAgencyCode());
//DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(ADMINISTRATIVE_REGION, groupId);
//String cityName = getDictItemName(groupId, dc, input.getCityCode());
//String districtName = getDictItemName(groupId, dc, input.getDistrictCode());
//String wardName = getDictItemName(groupId, dc, input.getWardCode());
// _log.info("Service code: " + input.getServiceCode());
//_log.debug("===ADD DOSSIER CITY NAME:" + cityName);
String password = StringPool.BLANK;
if (Validator.isNotNull(jsonDossier.getString("password"))) {
password = jsonDossier.getString("password");
} else if (Validator.isNotNull(process.getGeneratePassword()) && process.getGeneratePassword()) {
if (OpenCPSConfigUtil.getDefaultDossierSecretLength() > DossierTerm.PIN_LENGTH) {
password = PwdGenerator.getPassword(OpenCPSConfigUtil.getDefaultDossierSecretLength(), PwdGenerator.KEY1);
}
else {
password = PwdGenerator.getPinNumber();
}
}
String postalCityName = StringPool.BLANK;
if (Validator.isNotNull(jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE))) {
postalCityName = getDictItemName(groupId, VNPOST_CITY_CODE, jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE));
}
int sampleCount = (option != null ? (int) option.getSampleCount() : 1);
String registerBookCode = (option != null
? (Validator.isNotNull(option.getRegisterBookCode()) ? option.getRegisterBookCode()
: StringPool.BLANK) : StringPool.BLANK);
//String registerBookName = (Validator.isNotNull(registerBookCode)
// ? getDictItemName(groupId, REGISTER_BOOK, registerBookCode) : StringPool.BLANK);
String registerBookName = StringPool.BLANK;
if (Validator.isNotNull(registerBookCode)) {
DynamicReport report = DynamicReportLocalServiceUtil.fetchByG_CODE(groupId, registerBookCode);
if (report != null) {
registerBookName = report.getReportName();
}
}
_log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms");
Long appIdDateLong = jsonDossier.getLong(DossierTerm.APPLICANT_ID_DATE);
Date appIdDate = null;
if (appIdDateLong > 0) {
appIdDate = new Date(appIdDateLong);
}
// Params add dossier
String applicantName = jsonDossier.getString(DossierTerm.APPLICANT_NAME);
String applicantIdType = jsonDossier.getString(DossierTerm.APPLICANT_ID_TYPE);
String applicantIdNo = jsonDossier.getString(DossierTerm.APPLICANT_ID_NO);
String address = jsonDossier.getString(DossierTerm.ADDRESS);
String contactName = jsonDossier.getString(DossierTerm.CONTACT_NAME);
String contactTelNo = jsonDossier.getString(DossierTerm.CONTACT_TEL_NO);
String contactEmail = jsonDossier.getString(DossierTerm.CONTACT_EMAIL);
//
String postalServiceCode = jsonDossier.getString(DossierTerm.POSTAL_SERVICE_CODE);
String postalServiceName = jsonDossier.getString(DossierTerm.POSTAL_SERVICE_NAME);
String postalAddress = jsonDossier.getString(DossierTerm.POSTAL_ADDRESS);
String postalCityCode = jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE);
String postalDistrictCode = jsonDossier.getString(DossierTerm.POSTAL_DISTRICT_CODE);
String postalDistrictName = jsonDossier.getString(DossierTerm.POSTAL_DISTRICT_NAME);
String postalWardCode = jsonDossier.getString(DossierTerm.POSTAL_WARD_CODE);
String postalWardName = jsonDossier.getString(DossierTerm.POSTAL_WARD_NAME);
String postalTelNo = jsonDossier.getString(DossierTerm.POSTAL_TEL_NO);
String applicantNote = jsonDossier.getString(DossierTerm.APPLICANT_NOTE);
String delegateIdNo = jsonDossier.getString(DossierTerm.DELEGATE_ID_NO);
String delegateName = jsonDossier.getString(DossierTerm.DELEGATE_NAME);
String delegateTelNo = jsonDossier.getString(DossierTerm.DELEGATE_TELNO);
String delegateEmail = jsonDossier.getString(DossierTerm.DELEGATE_EMAIL);
String delegateAddress = jsonDossier.getString(DossierTerm.DELEGATE_ADDRESS);
//TODO
String delegateCityCode = jsonDossier.getString(DossierTerm.DELEGATE_CITYCODE);
String delegateCityName = StringPool.BLANK;
if (Validator.isNotNull(delegateCityCode)) {
delegateCityName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateCityCode);
}
String delegateDistrictCode = jsonDossier.getString(DossierTerm.DELEGATE_DISTRICTCODE);
String delegateDistrictName = StringPool.BLANK;
if (Validator.isNotNull(delegateDistrictCode)) {
delegateDistrictName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateDistrictCode);
}
String delegateWardCode = jsonDossier.getString(DossierTerm.DELEGATE_WARDCODE);
String delegateWardName = StringPool.BLANK;
if (Validator.isNotNull(delegateWardCode)) {
delegateWardName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateWardCode);
}
//
String dossierName = Validator.isNotNull(jsonDossier.getString(DossierTerm.DOSSIER_NAME)) ? jsonDossier.getString(DossierTerm.DOSSIER_NAME) : serviceName;
Long receiveDateTimeStamp = jsonDossier.getLong(DossierTerm.RECEIVE_DATE);
Date receiveDate = null;
if (receiveDateTimeStamp > 0) {
receiveDate = new Date(receiveDateTimeStamp);
}
Long dueDateTimeStamp = jsonDossier.getLong(DossierTerm.DUE_DATE);
Date dueDate = null;
if (dueDateTimeStamp > 0) {
dueDate = new Date(dueDateTimeStamp);
}
String metaData = jsonDossier.getString(DossierTerm.META_DATA);
dossier = dossierLocalService.initMultipleDossier(groupId, 0l, referenceUid, counter,
input.getServiceCode(), serviceName, input.getGovAgencyCode(), govAgencyName, applicantName,
applicantIdType, applicantIdNo, appIdDate, address, contactName, contactTelNo, contactEmail,
input.getDossierTemplateNo(), password, viaPostal, postalServiceCode, postalServiceName,
postalAddress, postalCityCode, postalCityName, postalDistrictCode, postalDistrictName,
postalWardCode, postalWardName, postalTelNo, online, process.getDirectNotification(), applicantNote,
input.getOriginality(), delegateIdNo, delegateName, delegateTelNo, delegateEmail, delegateAddress,
delegateCityCode, delegateCityName, delegateDistrictCode, delegateDistrictName, delegateWardCode,
delegateWardName, registerBookCode, registerBookName, sampleCount, dossierName, service, process,
option, serviceContext);
if (receiveDate != null)
dossier.setReceiveDate(receiveDate);
if (dueDate != null)
dossier.setDueDate(dueDate);
if (Validator.isNotNull(metaData))
dossier.setMetaData(metaData);
//
dossier.setSystemId(input.getSystemId());
//TODO: Process then
//updateDelegateApplicant(dossier, input);
_log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms");
if (originality != DossierTerm.ORIGINALITY_LIENTHONG) {
Applicant applicant = ApplicantLocalServiceUtil.fetchByMappingID(serviceContext.getUserId());
if (applicant != null) {
updateApplicantInfo(dossier,
applicant.getApplicantIdDate(),
applicant.getApplicantIdNo(),
applicant.getApplicantIdType(),
applicant.getApplicantName(),
applicant.getAddress(),
applicant.getCityCode(),
applicant.getCityName(),
applicant.getDistrictCode(),
applicant.getDistrictName(),
applicant.getWardCode(),
applicant.getWardName(),
applicant.getContactEmail(),
applicant.getContactTelNo()
);
}
}
if (Validator.isNull(dossier)) {
throw new NotFoundException("Cant add DOSSIER");
}
_log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms");
//TODO
/** Create DossierMark */
//_log.debug("flagOldDossier: "+flagOldDossier);
_log.debug("originality: "+originality);
String templateNo = dossier.getDossierTemplateNo();
_log.debug("templateNo: "+templateNo);
long dossierId = dossier.getDossierId();
if (originality == DossierTerm.ORIGINALITY_MOTCUA || originality == DossierTerm.ORIGINALITY_LIENTHONG) {
if (Validator.isNotNull(input.getDossierMarkArr())) {
JSONArray markArr = JSONFactoryUtil.createJSONArray(input.getDossierMarkArr());
if (markArr != null && markArr.length() > 0) {
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossierId);
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[markArr.length()];
for (int i = 0; i < markArr.length(); i++) {
JSONObject jsonMark = markArr.getJSONObject(i);
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(jsonMark.getString("partNo"));
model.setFileCheck(0);
model.setFileMark(jsonMark.getInt("fileMark"));
model.setFileComment(StringPool.BLANK);
model.setRecordCount(StringPool.BLANK);
marks[i] = model;
}
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
}
} else if (Validator.isNotNull(templateNo)) {
List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo);
// _log.info("partList: "+partList);
if (partList != null && partList.size() > 0) {
_log.debug("partList.size(): "+partList.size());
_log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms");
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()];
int count = 0;
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossierId);
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
for (DossierPart dossierPart : partList) {
int fileMark = dossierPart.getFileMark();
String dossierPartNo = dossierPart.getPartNo();
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(dossierPartNo);
model.setFileCheck(0);
model.setFileMark(fileMark);
model.setFileComment(StringPool.BLANK);
model.setRecordCount(StringPool.BLANK);
marks[count++] = model;
}
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
_log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms");
}
}
}
/**
* Add dossier file
*/
String strDossierFileId = input.getDossierFileArr();
if (Validator.isNotNull(strDossierFileId)) {
String[] splitDossierFileId = strDossierFileId.split(StringPool.COMMA);
if (splitDossierFileId != null && splitDossierFileId.length > 0) {
for (String strFileId : splitDossierFileId) {
processCloneDossierFile(Long.valueOf(strFileId), dossier.getDossierId(), userId);
}
}
}
/**Create dossier user */
List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId());
List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId());
if (lstDus.size() == 0) {
DossierUserActions duActions = new DossierUserActionsImpl();
duActions.initDossierUser(groupId, dossier, process, lstProcessRoles);
}
if (originality == DossierTerm.ORIGINALITY_DVCTT) {
dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true);
}
_log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms");
// if (dossier != null) {
// //
// long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName());
//
// NotificationQueue queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId);
// //Process add notification queue
// Date now = new Date();
//
// Calendar cal = Calendar.getInstance();
// cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1);
//
// queue.setCreateDate(now);
// queue.setModifiedDate(now);
// queue.setGroupId(groupId);
// queue.setCompanyId(company.getCompanyId());
//
// queue.setNotificationType(NotificationType.DOSSIER_01);
// queue.setClassName(Dossier.class.getName());
// queue.setClassPK(String.valueOf(dossier.getPrimaryKey()));
// queue.setToUsername(dossier.getUserName());
// queue.setToUserId(dossier.getUserId());
// queue.setToEmail(dossier.getContactEmail());
// queue.setToTelNo(dossier.getContactTelNo());
//
// JSONObject payload = JSONFactoryUtil.createJSONObject();
// try {
//// _log.info("START PAYLOAD: ");
// payload.put(
// "Dossier", JSONFactoryUtil.createJSONObject(
// JSONFactoryUtil.looseSerialize(dossier)));
// }
// catch (JSONException parse) {
// _log.error(parse);
// }
//// _log.info("payloadTest: "+payload.toJSONString());
// queue.setPayload(payload.toJSONString());
// queue.setExpireDate(cal.getTime());
//
// NotificationQueueLocalServiceUtil.addNotificationQueue(queue);
// }
_log.debug("CREATE DOSSIER 6: " + (System.currentTimeMillis() - start) + " ms");
//Add to dossier user based on service process role
createDossierUsers(groupId, dossier, process, lstProcessRoles);
_log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms");
dossierLocalService.updateDossier(dossier);
_log.debug("CREATE DOSSIER 8: " + (System.currentTimeMillis() - start) + " ms");
String payload = StringPool.BLANK;
String actionCode = "1100";
if (dossier.getReceiveDate() == null) {
JSONObject jsonDate = JSONFactoryUtil.createJSONObject();
jsonDate.put(DossierTerm.RECEIVE_DATE, (new Date()).getTime());
Double durationCount = process.getDurationCount();
if (Validator.isNotNull(String.valueOf(durationCount)) && durationCount > 0d) {
// Date dueDateCal = HolidayUtils.getDueDate(new Date(), process.getDurationCount(),
// process.getDurationUnit(), groupId);
DueDateUtils dueDateUtils = new DueDateUtils(new Date(), process.getDurationCount(),
process.getDurationUnit(), groupId);
Date dueDateCal = dueDateUtils.getDueDate();
jsonDate.put(DossierTerm.DUE_DATE, dueDateCal != null ? dueDateCal.getTime() : 0);
}
if (Validator.isNotNull(jsonDate)) {
payload = jsonDate.toJSONString();
}
}
//
ProcessAction proAction = getProcessAction(user.getUserId(), groupId, dossier, actionCode,
serviceProcessId);
doAction(groupId, userId, dossier, option, proAction, actionCode, StringPool.BLANK, StringPool.BLANK,
payload, StringPool.BLANK, input.getPayment(), 0, serviceContext);
}
return dossier;
}
private void processCloneDossierFile(Long dossierFileId, long dossierId, long userId) throws PortalException {
DossierFile dossierFileParent = dossierFileLocalService.fetchDossierFile(dossierFileId);
if (dossierFileParent != null) {
long dossierFileChildrenId = counterLocalService.increment(DossierFile.class.getName());
DossierFile object = dossierFilePersistence.create(dossierFileChildrenId);
_log.debug("****End uploadFile file at:" + new Date());
Date now = new Date();
User userAction = null;
if (userId != 0) {
userAction = userLocalService.getUser(userId);
}
// Add audit fields
object.setCompanyId(dossierFileParent.getCompanyId());
object.setGroupId(dossierFileParent.getGroupId());
object.setCreateDate(now);
object.setModifiedDate(now);
object.setUserId(userAction != null ? userAction.getUserId() : 0l);
object.setUserName(userAction != null ? userAction.getFullName() : StringPool.BLANK);
// Add other fields
object.setDossierId(dossierId);
object.setReferenceUid(PortalUUIDUtil.generate());
object.setDossierTemplateNo(dossierFileParent.getDossierTemplateNo());
object.setFileEntryId(dossierFileParent.getFileEntryId());
object.setDossierPartNo(dossierFileParent.getDossierPartNo());
object.setFileTemplateNo(dossierFileParent.getFileTemplateNo());
object.setDossierPartType(dossierFileParent.getDossierPartType());
_log.debug("****Start autofill file at:" + new Date());
object.setDisplayName(dossierFileParent.getDisplayName());
object.setOriginal(false);
object.setIsNew(true);
object.setFormData(dossierFileParent.getFormData());
object.setEForm(dossierFileParent.getEForm());
object.setRemoved(false);
object.setSignCheck(dossierFileParent.getSignCheck());
object.setFormScript(dossierFileParent.getFormScript());
object.setFormReport(dossierFileParent.getFormReport());
object.setFormSchema(dossierFileParent.getFormSchema());
dossierFilePersistence.update(object);
}
}
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { SystemException.class, PortalException.class,
Exception.class })
public Dossier addFullDossier(long groupId, Company company, User user, ServiceContext serviceContext,
DossierMultipleInputModel input) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
DossierPermission dossierPermission = new DossierPermission();
long start = System.currentTimeMillis();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
ProcessOption option = getProcessOption(input.getServiceCode(), input.getGovAgencyCode(),
input.getDossierTemplateNo(), groupId);
long serviceProcessId = 0;
if (option != null) {
serviceProcessId = option.getServiceProcessId();
}
boolean flag = false;
long userId = serviceContext.getUserId();
Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId);
if (employee != null) {
long employeeId = employee.getEmployeeId();
if (employeeId > 0) {
List<EmployeeJobPos> empJobList = EmployeeJobPosLocalServiceUtil.findByF_EmployeeId(employeeId);
if (empJobList != null && empJobList.size() > 0) {
for (EmployeeJobPos employeeJobPos : empJobList) {
long jobPosId = employeeJobPos.getJobPostId();
if (jobPosId > 0) {
JobPos job = JobPosLocalServiceUtil.fetchJobPos(jobPosId);
if (job != null) {
ServiceProcessRolePK pk = new ServiceProcessRolePK(serviceProcessId,
job.getMappingRoleId());
ServiceProcessRole role = serviceProcessRoleLocalService
.fetchServiceProcessRole(pk);
if (role != null && role.getModerator()) {
flag = true;
break;
}
}
}
}
}
}
} else {
flag = true;
}
if (!flag) {
throw new UnauthenticationException("No permission create dossier");
}
_log.debug("CREATE DOSSIER 1: " + (System.currentTimeMillis() - start) + " ms");
dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(),
input.getGovAgencyCode(), input.getDossierTemplateNo());
Dossier dossier = null;
if (Validator.isNotNull(input.getDossiers())) {
JSONObject jsonDossier = JSONFactoryUtil.createJSONObject(input.getDossiers());
//Get params input dossier
String referenceUid = jsonDossier.getString(DossierTerm.REFERENCE_UID);
if (Validator.isNull(referenceUid) || referenceUid.trim().length() == 0)
referenceUid = DossierNumberGenerator.generateReferenceUID(groupId);
int counter = 0;
//boolean online = GetterUtil.getBoolean(input.getOnline());
boolean online = false;
int originality = input.getOriginality();
int viaPostal = Validator.isNotNull(jsonDossier.getString(DossierTerm.VIA_POSTAL))
? GetterUtil.getInteger(jsonDossier.getString(DossierTerm.VIA_POSTAL)): 0;
ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, input.getServiceCode(),
input.getGovAgencyCode());
if (config != null && Validator.isNotNull(viaPostal)) {
viaPostal = config.getPostService() ? (viaPostal == 0 ? 1 : viaPostal) : 0;
} else if (config != null) {
viaPostal = config.getPostService() ? 1 : 0;
}
//Get service process
ServiceProcess process = null;
if (option != null) {
process = serviceProcessLocalService.getServiceProcess(serviceProcessId);
if (process == null) {
throw new NotFoundException("Cant find process");
}
}
ServiceInfo service = serviceInfoLocalService.getByCode(groupId, input.getServiceCode());
String serviceName = service != null ? service.getServiceName(): StringPool.BLANK;
String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, input.getGovAgencyCode());
//DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(ADMINISTRATIVE_REGION, groupId);
//String cityName = getDictItemName(groupId, dc, input.getCityCode());
//String districtName = getDictItemName(groupId, dc, input.getDistrictCode());
//String wardName = getDictItemName(groupId, dc, input.getWardCode());
// _log.info("Service code: " + input.getServiceCode());
//_log.debug("===ADD DOSSIER CITY NAME:" + cityName);
String password = StringPool.BLANK;
if (Validator.isNotNull(jsonDossier.getString("password"))) {
password = jsonDossier.getString("password");
} else if (Validator.isNotNull(process.getGeneratePassword()) && process.getGeneratePassword()) {
if (OpenCPSConfigUtil.getDefaultDossierSecretLength() > DossierTerm.PIN_LENGTH) {
password = PwdGenerator.getPassword(OpenCPSConfigUtil.getDefaultDossierSecretLength(), PwdGenerator.KEY1);
}
else {
password = PwdGenerator.getPinNumber();
}
}
String postalCityName = StringPool.BLANK;
if (Validator.isNotNull(jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE))) {
postalCityName = getDictItemName(groupId, VNPOST_CITY_CODE, jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE));
}
int sampleCount = (option != null ? (int) option.getSampleCount() : 1);
String registerBookCode = (option != null
? (Validator.isNotNull(option.getRegisterBookCode()) ? option.getRegisterBookCode()
: StringPool.BLANK) : StringPool.BLANK);
//String registerBookName = (Validator.isNotNull(registerBookCode)
// ? getDictItemName(groupId, REGISTER_BOOK, registerBookCode) : StringPool.BLANK);
String registerBookName = StringPool.BLANK;
if (Validator.isNotNull(registerBookCode)) {
DynamicReport report = DynamicReportLocalServiceUtil.fetchByG_CODE(groupId, registerBookCode);
if (report != null) {
registerBookName = report.getReportName();
}
}
_log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms");
Long appIdDateLong = jsonDossier.getLong(DossierTerm.APPLICANT_ID_DATE);
Date appIdDate = null;
if (appIdDateLong > 0) {
appIdDate = new Date(appIdDateLong);
}
// Params add dossier
String applicantName = jsonDossier.getString(DossierTerm.APPLICANT_NAME);
String applicantIdType = jsonDossier.getString(DossierTerm.APPLICANT_ID_TYPE);
String applicantIdNo = jsonDossier.getString(DossierTerm.APPLICANT_ID_NO);
String address = jsonDossier.getString(DossierTerm.ADDRESS);
String contactName = jsonDossier.getString(DossierTerm.CONTACT_NAME);
String contactTelNo = jsonDossier.getString(DossierTerm.CONTACT_TEL_NO);
String contactEmail = jsonDossier.getString(DossierTerm.CONTACT_EMAIL);
//
String postalServiceCode = jsonDossier.getString(DossierTerm.POSTAL_SERVICE_CODE);
String postalServiceName = jsonDossier.getString(DossierTerm.POSTAL_SERVICE_NAME);
String postalAddress = jsonDossier.getString(DossierTerm.POSTAL_ADDRESS);
String postalCityCode = jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE);
String postalDistrictCode = jsonDossier.getString(DossierTerm.POSTAL_DISTRICT_CODE);
String postalDistrictName = jsonDossier.getString(DossierTerm.POSTAL_DISTRICT_NAME);
String postalWardCode = jsonDossier.getString(DossierTerm.POSTAL_WARD_CODE);
String postalWardName = jsonDossier.getString(DossierTerm.POSTAL_WARD_NAME);
String postalTelNo = jsonDossier.getString(DossierTerm.POSTAL_TEL_NO);
String applicantNote = jsonDossier.getString(DossierTerm.APPLICANT_NOTE);
String delegateIdNo = jsonDossier.getString(DossierTerm.DELEGATE_ID_NO);
String delegateName = jsonDossier.getString(DossierTerm.DELEGATE_NAME);
String delegateTelNo = jsonDossier.getString(DossierTerm.DELEGATE_TELNO);
String delegateEmail = jsonDossier.getString(DossierTerm.DELEGATE_EMAIL);
String delegateAddress = jsonDossier.getString(DossierTerm.DELEGATE_ADDRESS);
//TODO
String cityCode = jsonDossier.getString(DossierTerm.CITY_CODE);
String cityName = StringPool.BLANK;
if (Validator.isNotNull(cityCode)) {
cityName = getDictItemName(groupId, ADMINISTRATIVE_REGION, cityCode);
}
String districtCode = jsonDossier.getString(DossierTerm.DISTRICT_CODE);
String districtName = StringPool.BLANK;
if (Validator.isNotNull(districtCode)) {
districtName = getDictItemName(groupId, ADMINISTRATIVE_REGION, districtCode);
}
String wardCode = jsonDossier.getString(DossierTerm.WARD_CODE);
String wardName = StringPool.BLANK;
if (Validator.isNotNull(wardCode)) {
wardName = getDictItemName(groupId, ADMINISTRATIVE_REGION, wardCode);
}
//
String delegateCityCode = jsonDossier.getString(DossierTerm.DELEGATE_CITYCODE);
String delegateCityName = StringPool.BLANK;
if (Validator.isNotNull(delegateCityCode)) {
delegateCityName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateCityCode);
}
String delegateDistrictCode = jsonDossier.getString(DossierTerm.DELEGATE_DISTRICTCODE);
String delegateDistrictName = StringPool.BLANK;
if (Validator.isNotNull(delegateDistrictCode)) {
delegateDistrictName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateDistrictCode);
}
String delegateWardCode = jsonDossier.getString(DossierTerm.DELEGATE_WARDCODE);
String delegateWardName = StringPool.BLANK;
if (Validator.isNotNull(delegateWardCode)) {
delegateWardName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateWardCode);
}
//
String dossierName = Validator.isNotNull(jsonDossier.getString(DossierTerm.DOSSIER_NAME)) ? jsonDossier.getString(DossierTerm.DOSSIER_NAME) : serviceName;
Long receiveDateTimeStamp = jsonDossier.getLong(DossierTerm.RECEIVE_DATE);
Date receiveDate = null;
if (receiveDateTimeStamp > 0) {
receiveDate = new Date(receiveDateTimeStamp);
}
Long dueDateTimeStamp = jsonDossier.getLong(DossierTerm.DUE_DATE);
Date dueDate = null;
if (dueDateTimeStamp > 0) {
dueDate = new Date(dueDateTimeStamp);
}
String metaData = jsonDossier.getString(DossierTerm.META_DATA);
dossier = dossierLocalService.initMultipleDossier(groupId, 0l, referenceUid, counter,
input.getServiceCode(), serviceName, input.getGovAgencyCode(), govAgencyName, applicantName,
applicantIdType, applicantIdNo, appIdDate, address, contactName, contactTelNo, contactEmail,
input.getDossierTemplateNo(), password, viaPostal, postalServiceCode, postalServiceName,
postalAddress, postalCityCode, postalCityName, postalDistrictCode, postalDistrictName,
postalWardCode, postalWardName, postalTelNo, online, process.getDirectNotification(), applicantNote,
input.getOriginality(), delegateIdNo, delegateName, delegateTelNo, delegateEmail, delegateAddress,
delegateCityCode, delegateCityName, delegateDistrictCode, delegateDistrictName, delegateWardCode,
delegateWardName, registerBookCode, registerBookName, sampleCount, dossierName, service, process,
option, serviceContext);
if (receiveDate != null)
dossier.setReceiveDate(receiveDate);
if (dueDate != null)
dossier.setDueDate(dueDate);
if (Validator.isNotNull(metaData))
dossier.setMetaData(metaData);
if (Validator.isNotNull(address))
dossier.setAddress(address);
if (Validator.isNotNull(cityCode))
dossier.setCityCode(cityCode);
if (Validator.isNotNull(cityName))
dossier.setCityName(cityName);
if (Validator.isNotNull(districtCode))
dossier.setDistrictCode(districtCode);
if (Validator.isNotNull(districtName))
dossier.setDistrictName(districtName);
if (Validator.isNotNull(wardCode))
dossier.setWardCode(wardCode);
if (Validator.isNotNull(wardName))
dossier.setWardName(wardName);
//
dossier.setSystemId(input.getSystemId());
//TODO: Process then
//updateDelegateApplicant(dossier, input);
_log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms");
if (originality != DossierTerm.ORIGINALITY_LIENTHONG) {
Applicant applicant = ApplicantLocalServiceUtil.fetchByMappingID(serviceContext.getUserId());
if (applicant != null) {
updateApplicantInfo(dossier,
applicant.getApplicantIdDate(),
applicant.getApplicantIdNo(),
applicant.getApplicantIdType(),
applicant.getApplicantName(),
applicant.getAddress(),
applicant.getCityCode(),
applicant.getCityName(),
applicant.getDistrictCode(),
applicant.getDistrictName(),
applicant.getWardCode(),
applicant.getWardName(),
applicant.getContactEmail(),
applicant.getContactTelNo()
);
}
}
if (Validator.isNull(dossier)) {
throw new NotFoundException("Cant add DOSSIER");
}
_log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms");
/** Create DossierMark */
//_log.debug("flagOldDossier: "+flagOldDossier);
_log.debug("originality: "+originality);
String templateNo = dossier.getDossierTemplateNo();
_log.debug("templateNo: "+templateNo);
long dossierId = dossier.getDossierId();
if (originality == DossierTerm.ORIGINALITY_MOTCUA || originality == DossierTerm.ORIGINALITY_LIENTHONG) {
if (Validator.isNotNull(input.getDossierMarkArr())) {
JSONArray markArr = JSONFactoryUtil.createJSONArray(input.getDossierMarkArr());
if (markArr != null && markArr.length() > 0) {
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossierId);
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[markArr.length()];
for (int i = 0; i < markArr.length(); i++) {
JSONObject jsonMark = markArr.getJSONObject(i);
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(jsonMark.getString("partNo"));
model.setFileCheck(0);
model.setFileMark(jsonMark.getInt("fileMark"));
model.setFileComment(StringPool.BLANK);
model.setRecordCount(StringPool.BLANK);
marks[i] = model;
}
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
}
} else if (Validator.isNotNull(templateNo)) {
List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo);
// _log.info("partList: "+partList);
if (partList != null && partList.size() > 0) {
_log.debug("partList.size(): "+partList.size());
_log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms");
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()];
int count = 0;
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossierId);
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
for (DossierPart dossierPart : partList) {
int fileMark = dossierPart.getFileMark();
String dossierPartNo = dossierPart.getPartNo();
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(dossierPartNo);
model.setFileCheck(0);
model.setFileMark(fileMark);
model.setFileComment(StringPool.BLANK);
model.setRecordCount(StringPool.BLANK);
marks[count++] = model;
}
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
_log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms");
}
}
}
/**
* Add dossier file
*/
if (Validator.isNotNull(input.getDossierFileArr())) {
JSONArray dossierFileArr = JSONFactoryUtil.createJSONArray(input.getDossierFileArr());
if (dossierFileArr != null && dossierFileArr.length() > 0) {
for (int j = 0; j < dossierFileArr.length(); j++) {
JSONObject jsonFile = dossierFileArr.getJSONObject(j);
boolean eform = Boolean.valueOf(jsonFile.getString("eform"));
if (eform) {
//EFORM
_log.info("In dossier file create by eform");
try {
// String referenceUidFile = UUID.randomUUID().toString();
String partNo = jsonFile.getString(DossierPartTerm.PART_NO);
String formData = jsonFile.getString(ConstantUtils.FORM_DATA);
DossierFile dossierFile = null;
// DossierFileActions action = new DossierFileActionsImpl();
DossierPart dossierPart = dossierPartLocalService.fetchByTemplatePartNo(groupId, templateNo, partNo);
//_log.info("__file:" + file);
//DataHandler dataHandler = (file != null) ? file.getDataHandler() : null;
dossierFile = DossierFileLocalServiceUtil.getByGID_DID_PART_EFORM(groupId, dossierId,
partNo, true, false);
if (dossierFile == null) {
_log.info("dossierFile NULL");
dossierFile = dossierFileLocalService.addDossierFileEForm(groupId, dossierId, referenceUid,
templateNo, partNo, dossierPart.getFileTemplateNo(), dossierPart.getPartName(), dossierPart.getPartName(), 0,
null, StringPool.BLANK, "true", serviceContext);
}
if(Validator.isNotNull(formData)) {
dossierFile.setFormData(formData);
}
if(Validator.isNotNull(eform)) {
dossierFile.setEForm(eform);
}
_log.info("__Start update dossier file at:" + new Date());
DossierFileLocalServiceUtil.updateDossierFile(dossierFile);
dossierFileLocalService.updateFormData(groupId, dossierId, dossierFile.getReferenceUid(), formData,
serviceContext);
_log.info("__End update dossier file at:" + new Date());
} catch (Exception e) {
_log.debug(e);
}
}
}
}
}
/**Create dossier user */
List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId());
List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId());
if (lstDus.size() == 0) {
DossierUserActions duActions = new DossierUserActionsImpl();
duActions.initDossierUser(groupId, dossier, process, lstProcessRoles);
}
if (originality == DossierTerm.ORIGINALITY_DVCTT) {
dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true);
}
_log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms");
// if (dossier != null) {
// //
// long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName());
//
// NotificationQueue queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId);
// //Process add notification queue
// Date now = new Date();
//
// Calendar cal = Calendar.getInstance();
// cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1);
//
// queue.setCreateDate(now);
// queue.setModifiedDate(now);
// queue.setGroupId(groupId);
// queue.setCompanyId(company.getCompanyId());
//
// queue.setNotificationType(NotificationType.DOSSIER_01);
// queue.setClassName(Dossier.class.getName());
// queue.setClassPK(String.valueOf(dossier.getPrimaryKey()));
// queue.setToUsername(dossier.getUserName());
// queue.setToUserId(dossier.getUserId());
// queue.setToEmail(dossier.getContactEmail());
// queue.setToTelNo(dossier.getContactTelNo());
//
// JSONObject payload = JSONFactoryUtil.createJSONObject();
// try {
//// _log.info("START PAYLOAD: ");
// payload.put(
// "Dossier", JSONFactoryUtil.createJSONObject(
// JSONFactoryUtil.looseSerialize(dossier)));
// }
// catch (JSONException parse) {
// _log.error(parse);
// }
//// _log.info("payloadTest: "+payload.toJSONString());
// queue.setPayload(payload.toJSONString());
// queue.setExpireDate(cal.getTime());
//
// NotificationQueueLocalServiceUtil.addNotificationQueue(queue);
// }
_log.debug("CREATE DOSSIER 6: " + (System.currentTimeMillis() - start) + " ms");
//Add to dossier user based on service process role
createDossierUsers(groupId, dossier, process, lstProcessRoles);
_log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms");
dossierLocalService.updateDossier(dossier);
_log.debug("CREATE DOSSIER 8: " + (System.currentTimeMillis() - start) + " ms");
String payload = StringPool.BLANK;
String actionCode = "1100";
if (dossier.getReceiveDate() == null) {
JSONObject jsonDate = JSONFactoryUtil.createJSONObject();
jsonDate.put(DossierTerm.RECEIVE_DATE, (new Date()).getTime());
Double durationCount = process.getDurationCount();
if (Validator.isNotNull(String.valueOf(durationCount)) && durationCount > 0d) {
// Date dueDateCal = HolidayUtils.getDueDate(new Date(), process.getDurationCount(),
// process.getDurationUnit(), groupId);
DueDateUtils dueDateUtils = new DueDateUtils(new Date(), process.getDurationCount(),
process.getDurationUnit(), groupId);
Date dueDateCal = dueDateUtils.getDueDate();
jsonDate.put(DossierTerm.DUE_DATE, dueDateCal != null ? dueDateCal.getTime() : 0);
}
if (Validator.isNotNull(jsonDate)) {
payload = jsonDate.toJSONString();
}
}
//
ProcessAction proAction = getProcessAction(user.getUserId(), groupId, dossier, actionCode,
serviceProcessId);
doAction(groupId, userId, dossier, option, proAction, actionCode, StringPool.BLANK, StringPool.BLANK,
payload, StringPool.BLANK, input.getPayment(), 0, serviceContext);
}
return dossier;
}
private void createDossierUsers(long groupId, Dossier dossier, ServiceProcess process, List<ServiceProcessRole> lstProcessRoles) {
List<DossierUser> lstDaus = dossierUserLocalService.findByDID(dossier.getDossierId());
int count = 0;
long[] roleIds = new long[lstProcessRoles.size()];
for (ServiceProcessRole spr : lstProcessRoles) {
long roleId = spr.getRoleId();
roleIds[count++] = roleId;
}
List<JobPos> lstJobPoses = JobPosLocalServiceUtil.findByF_mappingRoleIds(groupId, roleIds);
Map<Long, JobPos> mapJobPoses = new HashMap<>();
long[] jobPosIds = new long[lstJobPoses.size()];
count = 0;
for (JobPos jp : lstJobPoses) {
mapJobPoses.put(jp.getJobPosId(), jp);
jobPosIds[count++] = jp.getJobPosId();
}
List<EmployeeJobPos> lstTemp = EmployeeJobPosLocalServiceUtil.findByF_G_jobPostIds(groupId, jobPosIds);
Map<Long, List<EmployeeJobPos>> mapEJPS = new HashMap<>();
for (EmployeeJobPos ejp : lstTemp) {
if (mapEJPS.get(ejp.getJobPostId()) != null) {
mapEJPS.get(ejp.getJobPostId()).add(ejp);
}
else {
List<EmployeeJobPos> lstEJPs = new ArrayList<>();
lstEJPs.add(ejp);
mapEJPS.put(ejp.getJobPostId(), lstEJPs);
}
}
for (ServiceProcessRole spr : lstProcessRoles) {
long roleId = spr.getRoleId();
int moderator = spr.getModerator() ? 1 : 0;
// JobPos jp = JobPosLocalServiceUtil.fetchByF_mappingRoleId(groupId, roleId);
JobPos jp = mapJobPoses.get(roleId);
if (jp != null) {
// List<EmployeeJobPos> lstEJPs = EmployeeJobPosLocalServiceUtil.getByJobPostId(groupId, jp.getJobPosId());
List<EmployeeJobPos> lstEJPs = mapEJPS.get(jp.getJobPosId());
long[] employeeIds = new long[lstEJPs.size()];
int countEmp = 0;
for (EmployeeJobPos ejp : lstEJPs) {
employeeIds[countEmp++] = ejp.getEmployeeId();
}
List<Employee> lstEmpls = EmployeeLocalServiceUtil.findByG_EMPID(groupId, employeeIds);
HashMap<Long, Employee> mapEmpls = new HashMap<>();
for (Employee e : lstEmpls) {
mapEmpls.put(e.getEmployeeId(), e);
}
List<Employee> lstEmployees = new ArrayList<>();
// for (EmployeeJobPos ejp : lstEJPs) {
// Employee employee = EmployeeLocalServiceUtil.fetchEmployee(ejp.getEmployeeId());
// if (employee != null) {
// lstEmployees.add(employee);
// }
// }
for (EmployeeJobPos ejp : lstEJPs) {
if (mapEmpls.get(ejp.getEmployeeId()) != null) {
lstEmployees.add(mapEmpls.get(ejp.getEmployeeId()));
}
}
HashMap<Long, DossierUser> mapDaus = new HashMap<>();
for (DossierUser du : lstDaus) {
mapDaus.put(du.getUserId(), du);
}
for (Employee e : lstEmployees) {
// DossierUserPK pk = new DossierUserPK();
// pk.setDossierId(dossier.getDossierId());
// pk.setUserId(e.getMappingUserId());
// DossierUser ds = DossierUserLocalServiceUtil.fetchDossierUser(pk);
if (mapDaus.get(e.getMappingUserId()) == null) {
// if (ds == null) {
dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), e.getMappingUserId(), moderator, Boolean.FALSE);
}
else {
DossierUser ds = mapDaus.get(e.getMappingUserId());
if (moderator == 1 && ds.getModerator() == 0) {
ds.setModerator(1);
dossierUserLocalService.updateDossierUser(ds);
}
}
}
}
}
}
private void updateApplicantInfo(Dossier dossier, Date applicantIdDate,
String applicantIdNo,
String applicantIdType,
String applicantName,
String address,
String cityCode,
String cityName,
String districtCode,
String districtName,
String wardCode,
String wardName,
String contactEmail,
String contactTelNo) {
dossier.setApplicantIdDate(applicantIdDate);
dossier.setApplicantIdNo(applicantIdNo);
dossier.setApplicantIdType(applicantIdType);
dossier.setApplicantName(applicantName);
dossier.setAddress(address);
dossier.setCityCode(cityCode);
dossier.setCityName(cityName);
dossier.setDistrictCode(districtCode);
dossier.setDistrictName(districtName);
dossier.setWardCode(wardCode);
dossier.setWardName(wardName);
dossier.setContactEmail(contactEmail);
dossier.setContactTelNo(contactTelNo);
dossier.setDelegateAddress(address);
dossier.setDelegateCityCode(cityCode);
dossier.setDelegateCityName(cityName);
dossier.setDelegateDistrictCode(districtCode);
dossier.setDelegateDistrictName(districtName);
dossier.setDelegateEmail(contactEmail);
dossier.setDelegateIdNo(applicantIdNo);
dossier.setDelegateName(applicantName);
dossier.setDelegateTelNo(contactTelNo);
dossier.setDelegateWardCode(wardCode);
dossier.setDelegateWardName(wardName);
}
private void updateDelegateApplicant(Dossier dossier, DossierInputModel input) {
if (Validator.isNotNull(input.getDelegateName())) {
dossier.setDelegateName(input.getDelegateName());
}
if (Validator.isNotNull(input.getDelegateIdNo())) {
dossier.setDelegateIdNo(input.getDelegateIdNo());
}
if (Validator.isNotNull(input.getDelegateTelNo())) {
dossier.setDelegateTelNo(input.getDelegateTelNo());
}
if (Validator.isNotNull(input.getDelegateEmail())) {
dossier.setDelegateEmail(input.getDelegateEmail());
}
if (Validator.isNotNull(input.getDelegateAddress())) {
dossier.setDelegateAddress(input.getDelegateAddress());
}
if (Validator.isNotNull(input.getDelegateCityCode())) {
dossier.setDelegateCityCode(input.getDelegateCityCode());
}
if (Validator.isNotNull(input.getDelegateCityName())) {
dossier.setDelegateCityName(input.getDelegateCityName());
}
if (Validator.isNotNull(input.getDelegateDistrictCode())) {
dossier.setDelegateDistrictCode(input.getDelegateDistrictCode());
}
if (Validator.isNotNull(input.getDelegateDistrictName())) {
dossier.setDelegateDistrictName(input.getDelegateDistrictName());
}
if (Validator.isNotNull(input.getDelegateWardCode())) {
dossier.setDelegateWardCode(input.getDelegateWardCode());
}
if (Validator.isNotNull(input.getDelegateWardName())) {
dossier.setDelegateWardCode(input.getDelegateWardName());
}
}
private String getDictItemName(long groupId, DictCollection dc, String itemCode) {
if (Validator.isNotNull(dc)) {
DictItem it = DictItemLocalServiceUtil.fetchByF_dictItemCode(itemCode, dc.getPrimaryKey(), groupId);
if(Validator.isNotNull(it)){
return it.getItemName();
}else{
return StringPool.BLANK;
}
} else {
return StringPool.BLANK;
}
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public DossierFile addDossierFileByDossierId(long groupId, Company company, User user, ServiceContext serviceContext,
Attachment file, String id, String referenceUid,
String dossierTemplateNo, String dossierPartNo, String fileTemplateNo, String displayName, String fileType,
String isSync, String formData, String removed, String eForm, Long modifiedDate) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
long dossierId = GetterUtil.getLong(id);
Dossier dossier = null;
if (dossierId != 0) {
dossier = dossierLocalService.fetchDossier(dossierId);
if (Validator.isNull(dossier)) {
dossier = dossierLocalService.getByRef(groupId, id);
}
} else {
dossier = dossierLocalService.getByRef(groupId, id);
}
DataHandler dataHandler = (file != null) ? file.getDataHandler() : null;
long originDossierId = dossier.getOriginDossierId();
DossierPart dossierPart = null;
String originDossierTemplateNo = StringPool.BLANK;
if (originDossierId != 0) {
//HSLT
Dossier hsltDossier = dossierLocalService.fetchDossier(dossier.getDossierId());
dossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId());
ServiceConfig serviceConfig = serviceConfigLocalService.getBySICodeAndGAC(groupId, dossier.getServiceCode(), hsltDossier.getGovAgencyCode());
List<ProcessOption> lstOptions = processOptionLocalService.getByServiceProcessId(serviceConfig.getServiceConfigId());
originDossierTemplateNo = dossier.getDossierTemplateNo();
if (serviceConfig != null) {
if (lstOptions.size() > 0) {
ProcessOption processOption = lstOptions.get(0);
DossierTemplate dossierTemplate = dossierTemplateLocalService.fetchDossierTemplate(processOption.getDossierTemplateId());
List<DossierPart> lstParts = dossierPartLocalService.getByTemplateNo(groupId, dossierTemplate.getTemplateNo());
for (DossierPart dp : lstParts) {
if (dp.getPartNo().equals(dossierPartNo) && dp.getFileTemplateNo().equals(fileTemplateNo)) {
dossierTemplateNo = dp.getTemplateNo();
dossierPart = dp;
break;
}
}
}
}
}
else {
List<DossierPart> lstParts = dossierPartLocalService.getByTemplateNo(groupId, dossier.getDossierTemplateNo());
for (DossierPart dp : lstParts) {
if (dp.getPartNo().equals(dossierPartNo)) {
fileTemplateNo = dp.getFileTemplateNo();
dossierTemplateNo = dossier.getDossierTemplateNo();
dossierPart = dp;
break;
}
}
}
if (originDossierId > 0) {
_log.debug("__Start add file at:" + new Date());
DossierFile dossierFile = null;
DossierFile oldDossierFile = null;
if (Validator.isNotNull(referenceUid)) {
oldDossierFile = dossierFileLocalService.getByDossierAndRef(dossier.getDossierId(), referenceUid);
} else if (dossierPart != null && !dossierPart.getMultiple()) {
// oldDossierFile = dossierFileLocalService.getByGID_DID_TEMP_PART_EFORM(groupId, dossier.getDossierId(),
// dossierTemplateNo, dossierPartNo, false, false);
oldDossierFile = dossierFileLocalService.getByGID_DID_TEMP_PART_EFORM(groupId, dossier.getDossierId(),
originDossierTemplateNo, dossierPartNo, false, false);
}
if (oldDossierFile != null && modifiedDate != null) {
if (oldDossierFile.getModifiedDate() != null && oldDossierFile.getModifiedDate().getTime() < modifiedDate) {
if (dataHandler != null && dataHandler.getInputStream() != null) {
dossierFile = dossierFileLocalService.updateDossierFile(groupId, dossier.getDossierId(),
oldDossierFile.getReferenceUid(), displayName, dataHandler.getName(), 0,
dataHandler.getInputStream(), fileType, isSync, serviceContext);
} else {
dossierFile = dossierFileLocalService.updateDossierFile(groupId, dossier.getDossierId(),
oldDossierFile.getReferenceUid(), displayName, displayName, 0, null, fileType, isSync,
serviceContext);
}
_log.debug("__End add file at:" + new Date());
if(Validator.isNotNull(formData)) {
dossierFile.setFormData(formData);
}
_log.debug("REMOVED:" + removed);
if(Validator.isNotNull(removed)) {
dossierFile.setRemoved(Boolean.parseBoolean(removed));
}
if(Validator.isNotNull(eForm)) {
dossierFile.setEForm(Boolean.parseBoolean(eForm));
}
if (Validator.isNull(eForm) || (Validator.isNotNull(eForm) && !Boolean.parseBoolean(eForm))) {
dossierFile.setFormData(StringPool.BLANK);
dossierFile.setIsNew(false);
}
_log.debug("__Start update dossier file at:" + new Date());
dossierFileLocalService.updateDossierFile(dossierFile);
_log.debug("__End update dossier file at:" + new Date());
_log.debug("__End bind to dossierFile" + new Date());
return dossierFile;
}
else {
throw new DataConflictException("Conflict dossier file");
}
}
else {
_log.debug("__Start add file at:" + new Date());
if (dataHandler != null && dataHandler.getInputStream() != null) {
// dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, dossierTemplateNo,
// dossierPartNo, fileTemplateNo, displayName, dataHandler.getName(), 0,
// dataHandler.getInputStream(), fileType, isSync, serviceContext);
dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, originDossierTemplateNo,
dossierPartNo, fileTemplateNo, displayName, dataHandler.getName(), 0,
dataHandler.getInputStream(), fileType, isSync, serviceContext);
} else {
// dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, dossierTemplateNo,
// dossierPartNo, fileTemplateNo, displayName, displayName, 0, null, fileType, isSync,
// serviceContext);
dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, originDossierTemplateNo,
dossierPartNo, fileTemplateNo, displayName, displayName, 0, null, fileType, isSync,
serviceContext);
}
_log.debug("__End add file at:" + new Date());
if(Validator.isNotNull(formData)) {
dossierFile.setFormData(formData);
}
if(Validator.isNotNull(removed)) {
dossierFile.setRemoved(Boolean.parseBoolean(removed));
}
if(Validator.isNotNull(eForm)) {
dossierFile.setEForm(Boolean.parseBoolean(eForm));
}
if (Validator.isNull(eForm) || (Validator.isNotNull(eForm) && !Boolean.parseBoolean(eForm))) {
dossierFile.setFormData(StringPool.BLANK);
dossierFile.setIsNew(false);
}
_log.debug("__Start update dossier file at:" + new Date());
dossierFileLocalService.updateDossierFile(dossierFile);
_log.debug("__End update dossier file at:" + new Date());
_log.debug("__End bind to dossierFile" + new Date());
return dossierFile;
}
} else {
// DossierFile lastDossierFile = DossierFileLocalServiceUtil.findLastDossierFile(dossier.getDossierId(), fileTemplateNo, dossierTemplateNo);
//_log.info("lastDossierFile: "+lastDossierFile);
DossierFile oldDossierFile = null;
if (Validator.isNotNull(referenceUid)) {
oldDossierFile = DossierFileLocalServiceUtil.getByDossierAndRef(dossier.getDossierId(), referenceUid);
} else if (dossierPart != null && !dossierPart.getMultiple()) {
oldDossierFile = dossierFileLocalService.getByGID_DID_TEMP_PART_EFORM(groupId, dossier.getDossierId(),
dossierTemplateNo, dossierPartNo, false, false);
_log.info("dossierPart.getMultiple: "+dossierPart.getMultiple());
}
_log.info("oldDossierFile: "+oldDossierFile);
if (oldDossierFile != null && modifiedDate != null) {
if (oldDossierFile.getModifiedDate() != null && oldDossierFile.getModifiedDate().getTime() < modifiedDate) {
_log.debug("__Start add file at:" + new Date());
DossierFile dossierFile = null;
if (dataHandler != null && dataHandler.getInputStream() != null) {
dossierFile = dossierFileLocalService.updateDossierFile(groupId, dossier.getDossierId(),
oldDossierFile.getReferenceUid(), displayName, dataHandler.getName(), 0,
dataHandler.getInputStream(), fileType, isSync, serviceContext);
} else {
dossierFile = dossierFileLocalService.updateDossierFile(groupId, dossier.getDossierId(),
oldDossierFile.getReferenceUid(), displayName, displayName, 0, null, fileType, isSync,
serviceContext);
}
_log.debug("__End add file at:" + new Date());
if(Validator.isNotNull(formData)) {
dossierFile.setFormData(formData);
}
if(Validator.isNotNull(removed)) {
dossierFile.setRemoved(Boolean.parseBoolean(removed));
}
if(Validator.isNotNull(eForm)) {
dossierFile.setEForm(Boolean.parseBoolean(eForm));
}
if (Validator.isNull(eForm) || (Validator.isNotNull(eForm) && !Boolean.parseBoolean(eForm))) {
dossierFile.setFormData(StringPool.BLANK);
dossierFile.setIsNew(false);
}
_log.debug("__Start update dossier file at:" + new Date());
DossierFileLocalServiceUtil.updateDossierFile(dossierFile);
_log.debug("__End update dossier file at:" + new Date());
_log.debug("__End bind to dossierFile" + new Date());
return dossierFile;
}
else {
throw new DataConflictException("Conflict dossier file");
}
}
else {
_log.debug("__Start add file at:" + new Date());
DossierFile dossierFile = null;
if (dataHandler != null && dataHandler.getInputStream() != null) {
dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, dossierTemplateNo,
dossierPartNo, fileTemplateNo, displayName, dataHandler.getName(), 0,
dataHandler.getInputStream(), fileType, isSync, serviceContext);
} else {
dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, dossierTemplateNo,
dossierPartNo, fileTemplateNo, displayName, displayName, 0, null, fileType, isSync,
serviceContext);
}
_log.debug("__End add file at:" + new Date());
if(Validator.isNotNull(formData)) {
dossierFile.setFormData(formData);
}
if(Validator.isNotNull(removed)) {
dossierFile.setRemoved(Boolean.parseBoolean(removed));
}
if(Validator.isNotNull(eForm)) {
dossierFile.setEForm(Boolean.parseBoolean(eForm));
}
if (Validator.isNull(eForm) || (Validator.isNotNull(eForm) && !Boolean.parseBoolean(eForm))) {
dossierFile.setFormData(StringPool.BLANK);
dossierFile.setIsNew(false);
}
_log.debug("__Start update dossier file at:" + new Date());
dossierFileLocalService.updateDossierFile(dossierFile);
_log.debug("__End update dossier file at:" + new Date());
_log.debug("__End bind to dossierFile" + new Date());
return dossierFile;
}
}
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public DossierFile updateDossierFile(long groupId, Company company, ServiceContext serviceContext, long id, String referenceUid, Attachment file)
throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
DataHandler dataHandle = file.getDataHandler();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
Dossier dossier = dossierLocalService.fetchDossier(id);
if (dossier != null) {
if (dossier.getOriginDossierId() != 0) {
dossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId());
id = dossier.getDossierId();
}
}
DossierFile dossierFile = dossierFileLocalService.updateDossierFile(groupId, id, referenceUid, dataHandle.getName(),
StringPool.BLANK,
dataHandle.getInputStream(), serviceContext);
return dossierFile;
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public DossierFile updateDossierFileFormData(long groupId, Company company,
ServiceContext serviceContext, long id, String referenceUid, String formdata) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
Dossier dossier = dossierLocalService.fetchDossier(id);
if (dossier != null) {
if (dossier.getOriginDossierId() != 0) {
dossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId());
id = dossier.getOriginDossierId();
}
}
DossierFile dossierFile = dossierFileLocalService.updateFormData(groupId, id, referenceUid, formdata,
serviceContext);
return dossierFile;
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public DossierFile resetformdataDossierFileFormData(long groupId, Company company,
ServiceContext serviceContext, long id, String referenceUid, String formdata) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
Dossier dossier = dossierLocalService.fetchDossier(id);
DossierFile dossierFile = null;
if (dossier != null) {
if (dossier.getOriginDossierId() != 0) {
dossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId());
//id = dossier.getOriginDossierId();
}
dossierFile = dossierFileLocalService.getDossierFileByReferenceUid(dossier.getDossierId(), referenceUid);
String defaultData = StringPool.BLANK;
if (Validator.isNotNull(dossierFile)) {
DossierPart part = dossierPartLocalService.getByFileTemplateNo(groupId,
dossierFile.getFileTemplateNo());
defaultData = AutoFillFormData.sampleDataBinding(part.getSampleData(), dossier.getDossierId(), serviceContext);
dossierFile = dossierFileLocalService.getByReferenceUid(referenceUid).get(0);
JSONObject defaultDataObj = JSONFactoryUtil.createJSONObject(defaultData);
defaultDataObj.put(KeyPayTerm.LicenceNo, dossierFile.getDeliverableCode());
defaultData = defaultDataObj.toJSONString();
}
dossierFile = dossierFileLocalService.updateFormData(groupId, dossier.getDossierId(), referenceUid, defaultData,
serviceContext);
String deliverableCode = dossierFile.getDeliverableCode();
if (Validator.isNotNull(deliverableCode)) {
Deliverable deliverable = deliverableLocalService.getByCode(deliverableCode);
deliverableLocalService.deleteDeliverable(deliverable);
}
}
return dossierFile;
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public PaymentFile createPaymentFileByDossierId(long groupId, ServiceContext serviceContext, String id, PaymentFileInputModel input) throws UnauthenticationException, PortalException, Exception {
long userId = serviceContext.getUserId();
BackendAuth auth = new BackendAuthImpl();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
Dossier dossier = getDossier(id, groupId);
PaymentFile paymentFile = null;
if (dossier != null) {
long dossierId = dossier.getPrimaryKey();
// if (!auth.hasResource(serviceContext, PaymentFile.class.getName(), ActionKeys.ADD_ENTRY)) {
// throw new UnauthorizationException();
// }
PaymentFile oldPaymentFile = paymentFileLocalService.getByDossierId(groupId, dossier.getDossierId());
String referenceUid = input.getReferenceUid();
if (Validator.isNull(referenceUid)) {
referenceUid = PortalUUIDUtil.generate();
}
if (oldPaymentFile != null) {
paymentFile = oldPaymentFile;
}
else {
paymentFile = paymentFileLocalService.createPaymentFiles(userId, groupId, dossierId, referenceUid,
input.getPaymentFee(), input.getAdvanceAmount(), input.getFeeAmount(), input.getServiceAmount(),
input.getShipAmount(), input.getPaymentAmount(), input.getPaymentNote(),
input.getEpaymentProfile(), input.getBankInfo(), 0,
input.getPaymentMethod(), serviceContext);
}
if (Validator.isNotNull(input.getInvoiceTemplateNo())) {
paymentFile.setInvoiceTemplateNo(input.getInvoiceTemplateNo());
}
if(Validator.isNotNull(input.getConfirmFileEntryId())){
paymentFile.setConfirmFileEntryId(input.getConfirmFileEntryId());
}
if(Validator.isNotNull(input.getPaymentStatus())){
paymentFile.setPaymentStatus(input.getPaymentStatus());
}
if(Validator.isNotNull(input.getEinvoice())) {
paymentFile.setEinvoice(input.getEinvoice());
}
if(Validator.isNotNull(input.getPaymentAmount())) {
paymentFile.setPaymentAmount(input.getPaymentAmount());
}
if(Validator.isNotNull(input.getPaymentMethod())){
paymentFile.setPaymentMethod(input.getPaymentMethod());
}
if(Validator.isNotNull(input.getServiceAmount())){
paymentFile.setServiceAmount(input.getServiceAmount());
}
if(Validator.isNotNull(input.getShipAmount())){
paymentFile.setShipAmount(input.getShipAmount());
}
if(Validator.isNotNull(input.getAdvanceAmount())){
paymentFile.setAdvanceAmount(input.getAdvanceAmount());
}
if(Validator.isNotNull(input.getFeeAmount())){
paymentFile.setFeeAmount(input.getFeeAmount());
}
if(Validator.isNotNull(input.getPaymentNote())){
paymentFile.setPaymentNote(input.getPaymentNote());
}
paymentFile = paymentFileLocalService.updatePaymentFile(paymentFile);
}
return paymentFile;
}
private Dossier getDossier(String id, long groupId) throws PortalException {
long dossierId = GetterUtil.getLong(id);
Dossier dossier = null;
if (dossierId != 0) {
dossier = dossierLocalService.fetchDossier(dossierId);
}
if (Validator.isNull(dossier)) {
dossier = dossierLocalService.getByRef(groupId, id);
}
return dossier;
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public Dossier addDossierPublish(long groupId, Company company,
User user, ServiceContext serviceContext, org.opencps.dossiermgt.input.model.DossierPublishModel input) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
DossierActions actions = new DossierActionsImpl();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
String referenceUid = input.getReferenceUid();
int counter = 0;
String serviceCode = input.getServiceCode();
String serviceName = input.getServiceName();
String govAgencyCode = input.getGovAgencyCode();
String govAgencyName = input.getGovAgencyName();
String applicantName = input.getApplicantName();
String applicantType = input.getApplicantIdType();
String applicantIdNo = input.getApplicantIdNo();
String applicantIdDate = input.getApplicantIdDate();
String address = input.getAddress();
String cityCode = input.getCityCode();
String cityName = input.getCityName();
String districtCode = input.getDistrictCode();
String districtName = input.getDistrictName();
String wardCode = input.getWardCode();
String wardName = input.getWardName();
String contactName = input.getContactName();
String contactTelNo = input.getContactTelNo();
String contactEmail = input.getContactEmail();
String dossierTemplateNo = input.getDossierTemplateNo();
String password = input.getPassword();
String online = input.getOnline();
String applicantNote = input.getApplicantNote();
int originality = 0;
long createDateLong = GetterUtil.getLong(input.getCreateDate());
long modifiedDateLong = GetterUtil.getLong(input.getModifiedDate());
long submitDateLong = GetterUtil.getLong(input.getSubmitDate());
long receiveDateLong = GetterUtil.getLong(input.getReceiveDate());
long dueDateLong = GetterUtil.getLong(input.getDueDate());
long releaseDateLong = GetterUtil.getLong(input.getReleaseDate());
long finishDateLong = GetterUtil.getLong(input.getFinishDate());
long cancellingDateLong = GetterUtil.getLong(input.getCancellingDate());
long correcttingDateLong = GetterUtil.getLong(input.getCorrecttingDate());
long endorsementDateLong = GetterUtil.getLong(input.getEndorsementDate());
long extendDateLong = GetterUtil.getLong(input.getExtendDate());
long processDateLong = GetterUtil.getLong(input.getProcessDate());
String submissionNote = input.getSubmissionNote();
String lockState = input.getLockState();
String dossierNo = input.getDossierNo();
Dossier oldDossier = null;
if (Validator.isNotNull(input.getReferenceUid())) {
oldDossier = getDossier(input.getReferenceUid(), groupId);
} else {
oldDossier = DossierLocalServiceUtil.getByDossierNo(groupId, dossierNo);
referenceUid = DossierNumberGenerator.generateReferenceUID(groupId);
}
if (oldDossier == null || oldDossier.getOriginality() == 0) {
Dossier dossier = actions.publishDossier(groupId, 0l, referenceUid, counter, serviceCode, serviceName,
govAgencyCode, govAgencyName, applicantName, applicantType, applicantIdNo, applicantIdDate, address,
cityCode, cityName, districtCode, districtName, wardCode, wardName, contactName, contactTelNo,
contactEmail, dossierTemplateNo, password, 0, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK,
StringPool.BLANK, Boolean.valueOf(online), false, applicantNote, originality,
createDateLong != 0 ? new Date(createDateLong) : null,
modifiedDateLong != 0 ? new Date(modifiedDateLong) : null,
submitDateLong != 0 ? new Date(submitDateLong) : null,
receiveDateLong != 0 ? new Date(receiveDateLong) : null,
dueDateLong != 0 ? new Date(dueDateLong) : null,
releaseDateLong != 0 ? new Date(releaseDateLong) : null,
finishDateLong != 0 ? new Date(finishDateLong) : null,
cancellingDateLong != 0 ? new Date(cancellingDateLong) : null,
correcttingDateLong != 0 ? new Date(correcttingDateLong) : null,
endorsementDateLong != 0 ? new Date(endorsementDateLong) : null,
extendDateLong != 0 ? new Date(extendDateLong) : null,
processDateLong != 0 ? new Date(processDateLong) : null, input.getDossierNo(),
input.getDossierStatus(), input.getDossierStatusText(), input.getDossierSubStatus(),
input.getDossierSubStatusText(),
input.getDossierActionId() != null ? input.getDossierActionId() : 0, submissionNote, lockState,
input.getDelegateName(), input.getDelegateIdNo(), input.getDelegateTelNo(),
input.getDelegateEmail(), input.getDelegateAddress(), input.getDelegateCityCode(),
input.getDelegateCityName(), input.getDelegateDistrictCode(), input.getDelegateDistrictName(),
input.getDelegateWardCode(), input.getDelegateWardName(), input.getDurationCount(),
input.getDurationUnit(), input.getDossierName(), input.getProcessNo(), input.getMetaData(), input.getVnpostalStatus(), input.getVnpostalProfile(), serviceContext);
return dossier;
}
return oldDossier;
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public Dossier addFullDossier(long groupId, Company company, User user, ServiceContext serviceContext,
DossierInputModel input) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
DossierPermission dossierPermission = new DossierPermission();
long start = System.currentTimeMillis();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
ProcessOption option = getProcessOption(input.getServiceCode(), input.getGovAgencyCode(),
input.getDossierTemplateNo(), groupId);
long serviceProcessId = 0;
if (option != null) {
serviceProcessId = option.getServiceProcessId();
}
boolean flag = false;
long userId = serviceContext.getUserId();
Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId);
if (employee != null) {
long employeeId = employee.getEmployeeId();
if (employeeId > 0) {
List<EmployeeJobPos> empJobList = EmployeeJobPosLocalServiceUtil.findByF_EmployeeId(employeeId);
if (empJobList != null && empJobList.size() > 0) {
for (EmployeeJobPos employeeJobPos : empJobList) {
long jobPosId = employeeJobPos.getJobPostId();
if (jobPosId > 0) {
JobPos job = JobPosLocalServiceUtil.fetchJobPos(jobPosId);
if (job != null) {
ServiceProcessRolePK pk = new ServiceProcessRolePK(serviceProcessId,
job.getMappingRoleId());
ServiceProcessRole role = serviceProcessRoleLocalService
.fetchServiceProcessRole(pk);
if (role != null && role.getModerator()) {
flag = true;
break;
}
}
}
}
}
}
} else {
flag = true;
}
if (!flag) {
throw new UnauthenticationException("No permission create dossier");
}
_log.debug("CREATE DOSSIER 1: " + (System.currentTimeMillis() - start) + " ms");
dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(),
input.getGovAgencyCode(), input.getDossierTemplateNo());
//int counter = DossierNumberGenerator.counterDossier(user.getUserId(), groupId);
String referenceUid = input.getReferenceUid();
int counter = 0;
// Create dossierNote
ServiceProcess process = null;
boolean online = GetterUtil.getBoolean(input.getOnline());
int originality = GetterUtil.getInteger(input.getOriginality());
Integer viaPostal = input.getViaPostal();
ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, input.getServiceCode(),
input.getGovAgencyCode());
if (config != null && Validator.isNotNull(viaPostal)) {
viaPostal = config.getPostService() ? (viaPostal == 0 ? 1 : viaPostal) : 0;
}
else if (config != null) {
viaPostal = config.getPostService() ? 1 : 0;
}
if (option != null) {
process = serviceProcessLocalService.getServiceProcess(serviceProcessId);
}
if (process == null) {
throw new NotFoundException("Cant find process");
}
if (Validator.isNull(referenceUid) || referenceUid.trim().length() == 0)
referenceUid = DossierNumberGenerator.generateReferenceUID(groupId);
//Dossier checkDossier = dossierLocalService.getByRef(groupId, referenceUid);
//if (checkDossier != null) {
// return checkDossier;
//}
ServiceInfo service = serviceInfoLocalService.getByCode(groupId, input.getServiceCode());
String serviceName = StringPool.BLANK;
if (service != null) {
serviceName = service.getServiceName();
}
String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, input.getGovAgencyCode());
DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(ADMINISTRATIVE_REGION, groupId);
String cityName = getDictItemName(groupId, dc, input.getCityCode());
String districtName = getDictItemName(groupId, dc, input.getDistrictCode());
String wardName = getDictItemName(groupId, dc, input.getWardCode());
// _log.info("Service code: " + input.getServiceCode());
_log.debug("===ADD DOSSIER CITY NAME:" + cityName);
String password = StringPool.BLANK;
if (Validator.isNotNull(input.getPassword())) {
password = input.getPassword();
} else if (Validator.isNotNull(process.getGeneratePassword()) && process.getGeneratePassword()) {
if (OpenCPSConfigUtil.getDefaultDossierSecretLength() > DossierTerm.PIN_LENGTH) {
password = PwdGenerator.getPassword(OpenCPSConfigUtil.getDefaultDossierSecretLength(), PwdGenerator.KEY1);
}
else {
password = PwdGenerator.getPinNumber();
}
}
String postalCityName = StringPool.BLANK;
if (Validator.isNotNull(input.getPostalCityCode())) {
postalCityName = getDictItemName(groupId, VNPOST_CITY_CODE, input.getPostalCityCode());
}
Long sampleCount = (option != null ? option.getSampleCount() : 1l);
// Process group dossier
if (originality == DossierTerm.ORIGINALITY_HOSONHOM) {
_log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date appIdDate = null;
try {
appIdDate = sdf.parse(input.getApplicantIdDate());
} catch (Exception e) {
_log.debug(e);
}
Dossier dossier = dossierLocalService.initDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName,
input.getGovAgencyCode(), govAgencyName, input.getApplicantName(), input.getApplicantIdType(),
input.getApplicantIdNo(), appIdDate, input.getAddress(), input.getCityCode(),
cityName, input.getDistrictCode(), districtName, input.getWardCode(), wardName,
input.getContactName(), input.getContactTelNo(), input.getContactEmail(),
input.getDossierTemplateNo(), password, viaPostal, input.getPostalAddress(), input.getPostalCityCode(), postalCityName,
input.getPostalTelNo(), online, process.getDirectNotification(), input.getApplicantNote(),
Integer.valueOf(input.getOriginality()),
service, process, option,
serviceContext);
if (Validator.isNotNull(input.getDossierName())) {
dossier.setDossierName(input.getDossierName());
} else {
dossier.setDossierName(serviceName);
}
dossier.setSampleCount(sampleCount);
updateDelegateApplicant(dossier, input);
// Process update dossierNo
LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();
params.put(DossierTerm.GOV_AGENCY_CODE, dossier.getGovAgencyCode());
params.put(DossierTerm.SERVICE_CODE, dossier.getServiceCode());
params.put(DossierTerm.DOSSIER_TEMPLATE_NO, dossier.getDossierTemplateNo());
params.put(DossierTerm.DOSSIER_STATUS, StringPool.BLANK);
if (option != null) {
//Process submition note
dossier.setSubmissionNote(option.getSubmissionNote());
String dossierRef = DossierNumberGenerator.generateDossierNumber(groupId, dossier.getCompanyId(),
dossier.getDossierId(), option.getProcessOptionId(), process.getDossierGroupPattern(), params);
dossier.setDossierNo(dossierRef.trim());
}
dossier.setViaPostal(1);
_log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms");
if (Validator.isNull(dossier)) {
throw new NotFoundException("Can't add DOSSIER");
}
_log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms");
//Create DossierMark
_log.debug("originality: "+originality);
String templateNo = dossier.getDossierTemplateNo();
_log.debug("templateNo: "+templateNo);
if (Validator.isNotNull(input.getDossierMarkArr())) {
JSONArray markArr = JSONFactoryUtil.createJSONArray(input.getDossierMarkArr());
if (markArr != null && markArr.length() > 0) {
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId());
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
for (int i = 0; i < markArr.length(); i++) {
JSONObject jsonMark = markArr.getJSONObject(i);
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[markArr.length()];
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(jsonMark.getString("partNo"));
model.setFileCheck(0);
model.setFileMark(jsonMark.getInt("fileMark"));
model.setFileComment(StringPool.BLANK);
model.setRecordCount(StringPool.BLANK);
marks[i] = model;
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
}
}
} else if (Validator.isNotNull(templateNo)) {
List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo);
// _log.info("partList: "+partList);
if (partList != null && partList.size() > 0) {
_log.debug("partList.size(): "+partList.size());
_log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms");
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()];
int count = 0;
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId());
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
for (DossierPart dossierPart : partList) {
int fileMark = dossierPart.getFileMark();
String dossierPartNo = dossierPart.getPartNo();
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(dossierPartNo);
model.setFileCheck(0);
model.setFileMark(fileMark);
model.setFileComment(StringPool.BLANK);
model.setRecordCount(StringPool.BLANK);
marks[count++] = model;
}
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
_log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms");
}
}
//Create dossier user
List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId());
List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId());
if (lstDus.size() == 0) {
DossierUserActions duActions = new DossierUserActionsImpl();
duActions.initDossierUser(groupId, dossier, process, lstProcessRoles);
}
// if (originality == DossierTerm.ORIGINALITY_DVCTT) {
// dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true);
// }
_log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms");
//Add to dossier user based on service process role
createDossierUsers(groupId, dossier, process, lstProcessRoles);
_log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms");
return dossierLocalService.updateDossier(dossier);
} else {
List<Dossier> oldDossiers = dossierLocalService.getByU_G_GAC_SC_DTNO_DS_O(
userId, groupId, input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo(), StringPool.BLANK, Integer.valueOf(input.getOriginality()));
Dossier dossier = null;
Dossier oldRefDossier = Validator.isNotNull(input.getReferenceUid()) ? dossierLocalService.getByRef(groupId, input.getReferenceUid()) : null;
if (originality == DossierTerm.ORIGINALITY_DVCTT) {
online = true;
}
boolean flagOldDossier = false;
String registerBookCode = (option != null ? (Validator.isNotNull(option.getRegisterBookCode()) ? option.getRegisterBookCode() : StringPool.BLANK) : StringPool.BLANK);
//String registerBookName = (Validator.isNotNull(registerBookCode) ? getDictItemName(groupId, REGISTER_BOOK, registerBookCode) : StringPool.BLANK);
String registerBookName = StringPool.BLANK;
if (Validator.isNotNull(registerBookCode)) {
DynamicReport report = DynamicReportLocalServiceUtil.fetchByG_CODE(groupId, registerBookCode);
if (report != null) {
registerBookName = report.getReportName();
}
}
_log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms");
if (oldRefDossier != null) {
dossier = oldRefDossier;
dossier.setSubmitDate(new Date());
ServiceProcess serviceProcess = process;
double durationCount = 0;
int durationUnit = 0;
if (serviceProcess != null ) {
durationCount = serviceProcess.getDurationCount();
durationUnit = serviceProcess.getDurationUnit();
dossier.setDurationCount(durationCount);
dossier.setDurationUnit(durationUnit);
}
if (durationCount > 0) {
// Date dueDate = HolidayUtils.getDueDate(new Date(), durationCount, durationUnit, groupId);
DueDateUtils dueDateUtils = new DueDateUtils(new Date(), durationCount, durationUnit, groupId);
Date dueDate = dueDateUtils.getDueDate();
dossier.setDueDate(dueDate);
}
}
else if (oldDossiers.size() > 0) {
flagOldDossier = true;
dossier = oldDossiers.get(0);
dossier.setApplicantName(input.getApplicantName());
dossier.setApplicantNote(input.getApplicantNote());
dossier.setApplicantIdNo(input.getApplicantIdNo());
dossier.setAddress(input.getAddress());
dossier.setContactEmail(input.getContactEmail());
dossier.setContactName(input.getContactName());
dossier.setContactTelNo(input.getContactTelNo());
dossier.setDelegateName(input.getDelegateName());
dossier.setDelegateEmail(input.getDelegateEmail());
dossier.setDelegateAddress(input.getDelegateAddress());
dossier.setPostalAddress(input.getPostalAddress());
dossier.setPostalCityCode(input.getPostalCityCode());
dossier.setPostalCityName(postalCityName);
dossier.setPostalTelNo(input.getPostalTelNo());
dossier.setPostalServiceCode(input.getPostalServiceCode());
dossier.setPostalServiceName(input.getPostalServiceName());
dossier.setPostalDistrictCode(input.getPostalDistrictCode());
dossier.setPostalDistrictName(input.getPostalDistrictName());
dossier.setPostalWardCode(input.getPostalWardCode());
dossier.setPostalWardName(input.getPostalWardName());
dossier.setPostalTelNo(input.getPostalTelNo());
dossier.setViaPostal(viaPostal);
dossier.setOriginDossierNo(input.getOriginDossierNo());
if (Validator.isNotNull(registerBookCode)) {
dossier.setRegisterBookCode(registerBookCode);
}
dossier.setRegisterBookName(registerBookName);
dossier.setSampleCount(sampleCount);
dossier.setServiceCode(input.getServiceCode());
dossier.setGovAgencyCode(input.getGovAgencyCode());
dossier.setDossierTemplateNo(input.getDossierTemplateNo());
updateDelegateApplicant(dossier, input);
// dossier.setDossierNo(input.getDossierNo());
dossier.setSubmitDate(new Date());
// ServiceProcess serviceProcess = ServiceProcessLocalServiceUtil.fetchServiceProcess(serviceProcessId);
ServiceProcess serviceProcess = process;
double durationCount = 0;
int durationUnit = 0;
if (serviceProcess != null ) {
durationCount = serviceProcess.getDurationCount();
durationUnit = serviceProcess.getDurationUnit();
dossier.setDurationCount(durationCount);
dossier.setDurationUnit(durationUnit);
}
if (durationCount > 0) {
// Date dueDate = HolidayUtils.getDueDate(new Date(), durationCount, durationUnit, groupId);
DueDateUtils dueDateUtils = new DueDateUtils(new Date(), durationCount, durationUnit, groupId);
Date dueDate = dueDateUtils.getDueDate();
dossier.setDueDate(dueDate);
}
dossier.setOnline(online);
if (Validator.isNotNull(input.getDossierName()))
dossier.setDossierName(input.getDossierName());
if (serviceProcess != null) {
dossier.setProcessNo(serviceProcess.getProcessNo());
}
// dossier = DossierLocalServiceUtil.updateDossier(dossier);
}
else {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date appIdDate = null;
try {
appIdDate = sdf.parse(input.getApplicantIdDate());
} catch (Exception e) {
_log.debug(e);
}
dossier = dossierLocalService.initDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName,
input.getGovAgencyCode(), govAgencyName, input.getApplicantName(), input.getApplicantIdType(),
input.getApplicantIdNo(), appIdDate, input.getAddress(), input.getCityCode(),
cityName, input.getDistrictCode(), districtName, input.getWardCode(), wardName,
input.getContactName(), input.getContactTelNo(), input.getContactEmail(),
input.getDossierTemplateNo(), password, viaPostal, input.getPostalAddress(), input.getPostalCityCode(), postalCityName,
input.getPostalTelNo(), online, process.getDirectNotification(), input.getApplicantNote(),
Integer.valueOf(input.getOriginality()),
service, process, option,
serviceContext);
dossier.setDelegateName(input.getDelegateName());
dossier.setDelegateEmail(input.getDelegateEmail());
dossier.setDelegateAddress(input.getDelegateAddress());
if (Validator.isNotNull(input.getDossierName())) {
dossier.setDossierName(input.getDossierName());
} else {
dossier.setDossierName(serviceName);
}
dossier.setPostalCityName(postalCityName);
dossier.setPostalTelNo(input.getPostalTelNo());
dossier.setPostalServiceCode(input.getPostalServiceCode());
dossier.setPostalServiceName(input.getPostalServiceName());
dossier.setPostalDistrictCode(input.getPostalDistrictCode());
dossier.setPostalDistrictName(input.getPostalDistrictName());
dossier.setPostalWardCode(input.getPostalWardCode());
dossier.setPostalWardName(input.getPostalWardName());
dossier.setOriginDossierNo(input.getOriginDossierNo());
if (Validator.isNotNull(registerBookCode)) {
dossier.setRegisterBookCode(registerBookCode);
}
dossier.setRegisterBookName(registerBookName);
dossier.setSampleCount(sampleCount);
updateDelegateApplicant(dossier, input);
if (process != null) {
dossier.setProcessNo(process.getProcessNo());
}
// dossier = DossierLocalServiceUtil.updateDossier(dossier);
}
_log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms");
if (originality != DossierTerm.ORIGINALITY_LIENTHONG) {
Applicant applicant = ApplicantLocalServiceUtil.fetchByMappingID(serviceContext.getUserId());
if (applicant != null) {
updateApplicantInfo(dossier,
applicant.getApplicantIdDate(),
applicant.getApplicantIdNo(),
applicant.getApplicantIdType(),
applicant.getApplicantName(),
applicant.getAddress(),
applicant.getCityCode(),
applicant.getCityName(),
applicant.getDistrictCode(),
applicant.getDistrictName(),
applicant.getWardCode(),
applicant.getWardName(),
applicant.getContactEmail(),
applicant.getContactTelNo()
);
}
}
if (Validator.isNull(dossier)) {
throw new NotFoundException("Cant add DOSSIER");
}
_log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms");
//Create DossierMark
_log.debug("flagOldDossier: "+flagOldDossier);
_log.debug("originality: "+originality);
if ((originality == DossierTerm.ORIGINALITY_MOTCUA || originality == DossierTerm.ORIGINALITY_LIENTHONG)
&& !flagOldDossier) {
String templateNo = dossier.getDossierTemplateNo();
_log.debug("templateNo: "+templateNo);
if (Validator.isNotNull(templateNo)) {
List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo);
// _log.info("partList: "+partList);
if (partList != null && partList.size() > 0) {
_log.debug("partList.size(): "+partList.size());
_log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms");
org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()];
int count = 0;
List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId());
Map<String, DossierMark> mapMarks = new HashMap<>();
for (DossierMark dm : lstMarks) {
mapMarks.put(dm.getDossierPartNo(), dm);
}
for (DossierPart dossierPart : partList) {
int fileMark = dossierPart.getFileMark();
String dossierPartNo = dossierPart.getPartNo();
org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel();
model.setDossierId(dossier.getDossierId());
model.setDossierPartNo(dossierPartNo);
model.setFileCheck(0);
model.setFileMark(fileMark);
model.setFileComment(StringPool.BLANK);
marks[count++] = model;
// DossierMarkLocalServiceUtil.addDossierMark(groupId, dossier.getDossierId(), dossierPartNo,
// fileMark, 0, StringPool.BLANK, serviceContext);
}
dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext);
_log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms");
}
}
}
//Create dossier user
List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId());
List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId());
if (lstDus.size() == 0) {
DossierUserActions duActions = new DossierUserActionsImpl();
// duActions.initDossierUser(groupId, dossier);
duActions.initDossierUser(groupId, dossier, process, lstProcessRoles);
}
if (originality == DossierTerm.ORIGINALITY_DVCTT) {
dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true);
}
_log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms");
// DossierLocalServiceUtil.updateDossier(dossier);
if (dossier != null) {
//
long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName());
NotificationQueue queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId);
//Process add notification queue
Date now = new Date();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1);
queue.setCreateDate(now);
queue.setModifiedDate(now);
queue.setGroupId(groupId);
queue.setCompanyId(company.getCompanyId());
queue.setNotificationType(NotificationType.DOSSIER_01);
queue.setClassName(Dossier.class.getName());
queue.setClassPK(String.valueOf(dossier.getPrimaryKey()));
queue.setToUsername(dossier.getUserName());
queue.setToUserId(dossier.getUserId());
if (isEmailNotify(dossier)) {
queue.setToEmail(dossier.getContactEmail());
}
if (isSmsNotify(dossier)) {
queue.setToTelNo(dossier.getContactTelNo());
}
JSONObject payload = JSONFactoryUtil.createJSONObject();
try {
// _log.info("START PAYLOAD: ");
payload.put(
"Dossier", JSONFactoryUtil.createJSONObject(
JSONFactoryUtil.looseSerialize(dossier)));
}
catch (JSONException parse) {
_log.error(parse);
}
// _log.info("payloadTest: "+payload.toJSONString());
queue.setPayload(payload.toJSONString());
queue.setExpireDate(cal.getTime());
NotificationQueueLocalServiceUtil.addNotificationQueue(queue);
}
_log.debug("CREATE DOSSIER 6: " + (System.currentTimeMillis() - start) + " ms");
//Add to dossier user based on service process role
createDossierUsers(groupId, dossier, process, lstProcessRoles);
_log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms");
dossierLocalService.updateDossier(dossier);
_log.debug("CREATE DOSSIER 8: " + (System.currentTimeMillis() - start) + " ms");
return dossier;
}
}
public static final String GOVERNMENT_AGENCY = ReadFilePropertiesUtils.get(ConstantUtils.GOVERNMENT_AGENCY);
public static final String ADMINISTRATIVE_REGION = ReadFilePropertiesUtils.get(ConstantUtils.VALUE_ADMINISTRATIVE_REGION);
public static final String VNPOST_CITY_CODE = ReadFilePropertiesUtils.get(ConstantUtils.VNPOST_CITY_CODE);
public static final String REGISTER_BOOK = ReadFilePropertiesUtils.get(ConstantUtils.REGISTER_BOOK);
private static final long VALUE_CONVERT_DATE_TIMESTAMP = 1000 * 60 * 60 * 24;
private static final long VALUE_CONVERT_HOUR_TIMESTAMP = 1000 * 60 * 60;
private static ProcessAction getProcessAction(long userId, long groupId, Dossier dossier, String actionCode,
long serviceProcessId) throws PortalException {
//_log.debug("GET PROCESS ACTION____");
ProcessAction action = null;
DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId());
User systemUser = UserLocalServiceUtil.fetchUser(userId);
try {
List<ProcessAction> actions = ProcessActionLocalServiceUtil.getByActionCode(groupId, actionCode,
serviceProcessId);
//_log.debug("GET PROCESS ACTION____" + groupId + "," + actionCode + "," + serviceProcessId);
String dossierStatus = dossier.getDossierStatus();
String dossierSubStatus = dossier.getDossierSubStatus();
String preStepCode;
String curStepCode = StringPool.BLANK;
if (dossier.getDossierActionId() > 0) {
DossierAction curAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId());
if (curAction != null) {
curStepCode = curAction.getStepCode();
}
}
for (ProcessAction act : actions) {
preStepCode = act.getPreStepCode();
//_log.debug("LamTV_preStepCode: "+preStepCode);
if (Validator.isNotNull(curStepCode) && !preStepCode.contentEquals(curStepCode)) continue;
ProcessStep step = ProcessStepLocalServiceUtil.fetchBySC_GID(preStepCode, groupId, serviceProcessId);
// _log.info("LamTV_ProcessStep: "+step);
if (Validator.isNull(step) && dossierAction == null) {
action = act;
break;
} else {
String stepStatus = step != null ? step.getDossierStatus() : StringPool.BLANK;
String stepSubStatus = step != null ? step.getDossierSubStatus() : StringPool.BLANK;
boolean flagCheck = false;
if (dossierAction != null) {
if (act.getPreStepCode().equals(dossierAction.getStepCode())) {
flagCheck = true;
}
}
else {
flagCheck = true;
}
//_log.debug("LamTV_preStepCode: "+stepStatus + "," + stepSubStatus + "," + dossierStatus + "," + dossierSubStatus + "," + act.getPreCondition() + "," + flagCheck);
if (stepStatus.contentEquals(dossierStatus)
&& StringUtil.containsIgnoreCase(stepSubStatus, dossierSubStatus)
&& flagCheck) {
if (Validator.isNotNull(act.getPreCondition()) && DossierMgtUtils.checkPreCondition(act.getPreCondition().split(StringPool.COMMA), dossier, systemUser)) {
action = act;
break;
}
else if (Validator.isNull(act.getPreCondition())) {
action = act;
break;
}
}
}
}
} catch (Exception e) {
_log.debug(e);
}
return action;
}
private JSONObject getFileAttachMailForApplicant (Dossier dossier, ProcessAction proAction) {
// processAction
// returnDossierFile
JSONObject filesAttach = JSONFactoryUtil.createJSONObject();
JSONArray files = JSONFactoryUtil.createJSONArray();
JSONArray documents = JSONFactoryUtil.createJSONArray();
JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
_log.debug("============getFileAttachMailForApplicant=================");
try {
List<String> returnFileTempNoList = ListUtil.toList(StringUtil.split(proAction.getReturnDossierFiles()));
_log.debug("==========proAction.getReturnDossierFiles()===========" + proAction.getReturnDossierFiles());
if (returnFileTempNoList.size() > 0) {
List<DossierFile> dossierFiles = dossierFileLocalService.getDossierFilesByD_DP(dossier.getDossierId(), DossierPartTerm.DOSSIER_PART_TYPE_OUTPUT);
for (DossierFile dossierFile : dossierFiles) {
// TODO: xu ly loc dossierFIle de dinh kem mail thong bao bo sung
_log.info("================DOSSIERFILE=============" + dossierFile.getFileEntryId());
if (returnFileTempNoList.indexOf(dossierFile.getFileTemplateNo()) >= 0) {
_log.debug("=============dossierFile.getFileTemplateNo()================");
FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(dossierFile.getFileEntryId());
if (fileEntry != null) {
jsonObject = JSONFactoryUtil.createJSONObject();
jsonObject.put("name", fileEntry.getFileName());
jsonObject.put("url", "documents/" + fileEntry.getGroupId() + StringPool.FORWARD_SLASH + fileEntry.getFolderId() + StringPool.FORWARD_SLASH + fileEntry.getTitle());
files.put(jsonObject);
}
}
}
List<DossierDocument> dossierDocuments = DossierDocumentLocalServiceUtil.getDossierDocumentList(dossier.getDossierId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS);
for (DossierDocument dossierDocument : dossierDocuments) {
// TODO: xu ly loc dossierDocument de dinh kem mail thong bao bo sung
_log.info("================dossierDocument=============" + dossierDocument.getDocumentFileId());
if (returnFileTempNoList.indexOf(dossierDocument.getDocumentType()) >= 0) {
_log.info("================dossierDocument.getDocumentType()=============");
FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(dossierDocument.getDocumentFileId());
if (fileEntry != null) {
jsonObject = JSONFactoryUtil.createJSONObject();
jsonObject.put("name", fileEntry.getFileName());
jsonObject.put("url", "documents/" + fileEntry.getGroupId() + StringPool.FORWARD_SLASH + fileEntry.getFolderId() + StringPool.FORWARD_SLASH + fileEntry.getTitle());
documents.put(jsonObject);
}
}
}
}
}
catch (Exception e) {
_log.error(e);
e.printStackTrace();
}
filesAttach.put("dossierFiles", files);
filesAttach.put("dossierDocuments", documents);
return filesAttach;
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class })
public Dossier eparPublish(long groupId, Company company,
User user, ServiceContext serviceContext, long id, org.opencps.dossiermgt.input.model.DossierPublishModel input) throws UnauthenticationException, PortalException, Exception {
BackendAuth auth = new BackendAuthImpl();
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
// String referenceUid = input.getReferenceUid();
int counter = 0;
String serviceCode = input.getServiceCode();
String serviceName = input.getServiceName();
String govAgencyCode = input.getGovAgencyCode();
String govAgencyName = input.getGovAgencyName();
String applicantName = input.getApplicantName();
String applicantType = input.getApplicantIdType();
String applicantIdNo = input.getApplicantIdNo();
String applicantIdDate = input.getApplicantIdDate();
String address = input.getAddress();
String cityCode = input.getCityCode();
String cityName = input.getCityName();
String districtCode = input.getDistrictCode();
String districtName = input.getDistrictName();
String wardCode = input.getWardCode();
String wardName = input.getWardName();
String contactName = input.getContactName();
String contactTelNo = input.getContactTelNo();
String contactEmail = input.getContactEmail();
String dossierTemplateNo = input.getDossierTemplateNo();
String password = input.getPassword();
String online = input.getOnline();
String applicantNote = input.getApplicantNote();
int originality = 0;
long createDateLong = GetterUtil.getLong(input.getCreateDate());
long modifiedDateLong = GetterUtil.getLong(input.getModifiedDate());
long submitDateLong = GetterUtil.getLong(input.getSubmitDate());
long receiveDateLong = GetterUtil.getLong(input.getReceiveDate());
long dueDateLong = GetterUtil.getLong(input.getDueDate());
long releaseDateLong = GetterUtil.getLong(input.getReleaseDate());
long finishDateLong = GetterUtil.getLong(input.getFinishDate());
long cancellingDateLong = GetterUtil.getLong(input.getCancellingDate());
long correcttingDateLong = GetterUtil.getLong(input.getCorrecttingDate());
long endorsementDateLong = GetterUtil.getLong(input.getEndorsementDate());
long extendDateLong = GetterUtil.getLong(input.getExtendDate());
long processDateLong = GetterUtil.getLong(input.getProcessDate());
String submissionNote = input.getSubmissionNote();
String lockState = input.getLockState();
Dossier oldDossier = null;
oldDossier = DossierLocalServiceUtil.fetchDossier(id);
if (oldDossier != null && oldDossier.getOriginality() == DossierTerm.ORIGINALITY_DVCTT) {
Date appIdDate = null;
SimpleDateFormat sdf = new SimpleDateFormat(APIDateTimeUtils._NORMAL_DATE);
try {
appIdDate = sdf.parse(applicantIdDate);
} catch (Exception e) {
_log.debug(e);
}
Dossier dossier = dossierLocalService.eparPublishDossier(groupId, 0l, oldDossier.getReferenceUid(), counter, serviceCode, serviceName,
govAgencyCode, govAgencyName, applicantName, applicantType, applicantIdNo, appIdDate, address,
cityCode, cityName, districtCode, districtName, wardCode, wardName, contactName, contactTelNo,
contactEmail, dossierTemplateNo, password, 0, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK,
StringPool.BLANK, Boolean.valueOf(online), false, applicantNote, originality,
createDateLong != 0 ? new Date(createDateLong) : null,
modifiedDateLong != 0 ? new Date(modifiedDateLong) : null,
submitDateLong != 0 ? new Date(submitDateLong) : null,
receiveDateLong != 0 ? new Date(receiveDateLong) : null,
dueDateLong != 0 ? new Date(dueDateLong) : null,
releaseDateLong != 0 ? new Date(releaseDateLong) : null,
finishDateLong != 0 ? new Date(finishDateLong) : null,
cancellingDateLong != 0 ? new Date(cancellingDateLong) : null,
correcttingDateLong != 0 ? new Date(correcttingDateLong) : null,
endorsementDateLong != 0 ? new Date(endorsementDateLong) : null,
extendDateLong != 0 ? new Date(extendDateLong) : null,
processDateLong != 0 ? new Date(processDateLong) : null, input.getDossierNo(),
input.getDossierStatus(), input.getDossierStatusText(), input.getDossierSubStatus(),
input.getDossierSubStatusText(),
input.getDossierActionId() != null ? input.getDossierActionId() : 0, submissionNote, lockState,
input.getDelegateName(), input.getDelegateIdNo(), input.getDelegateTelNo(),
input.getDelegateEmail(), input.getDelegateAddress(), input.getDelegateCityCode(),
input.getDelegateCityName(), input.getDelegateDistrictCode(), input.getDelegateDistrictName(),
input.getDelegateWardCode(), input.getDelegateWardName(), input.getDurationCount(),
input.getDurationUnit(), input.getDossierName(), input.getProcessNo(), input.getMetaData(), serviceContext);
return dossier;
}
return oldDossier;
}
private Dossier setDossierNoNDueDate(Dossier dossier, ServiceProcess serviceProcess, ProcessOption option,
boolean setDossierNo, boolean setDueDate, Date dueDateStart,
LinkedHashMap<String, Object> params) {
if (setDueDate) {
Double durationCount = serviceProcess.getDurationCount();
int durationUnit = serviceProcess.getDurationUnit();
Date dueDate = null;
if (Validator.isNotNull(durationCount) && durationCount > 0 && !areEqualDouble(durationCount, 0.00d, 3)) {
// dueDate = HolidayUtils.getDueDate(now, durationCount, durationUnit,
// dossier.getGroupId());
DueDateUtils dueDateUtils = new DueDateUtils(dueDateStart, durationCount, durationUnit, dossier.getGroupId());
dueDate = dueDateUtils.getDueDate();
}
if (Validator.isNotNull(dueDate)) {
dossier.setDueDate(dueDate);
// DossierLocalServiceUtil.updateDueDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), dueDate, context);
// bResult.put(DossierTerm.DUE_DATE, true);
}
dossier.setDurationCount(durationCount);
dossier.setDurationUnit(durationUnit);
}
if (setDossierNo) {
if (dossier.getCounter() == 0 && Validator.isNotNull(dossier.getRegisterBookCode())) {
long counterCode = DossierNumberGenerator.countByRegiterBookCode(dossier.getGroupId(),
dossier.getRegisterBookCode());
dossier.setCounter(counterCode);
}
if (Validator.isNull(dossier.getDossierNo())) {
try {
String dossierRef = DossierNumberGenerator.generateDossierNumber(dossier.getGroupId(), dossier.getCompanyId(),
dossier.getDossierId(), option.getProcessOptionId(), serviceProcess.getDossierNoPattern(),
params);
dossier.setDossierNo(dossierRef.trim());
} catch (Exception e) {
_log.debug(e);
}
}
if (Validator.isNull(dossier.getDossierCounter()) && Validator.isNotNull(serviceProcess.getCounterCode())) {
ConfigCounter counterConfig = ConfigCounterLocalServiceUtil.fetchByCountrCode(dossier.getGroupId(),
serviceProcess.getCounterCode());
if (counterConfig != null) {
if (Validator.isNotNull(counterConfig.getStartCounter()) && counterConfig.getStartCounter() > 0) {
String patternCode = counterConfig.getPatternCode();
try {
_log.info("dossierId: " + dossier.getDossierId() + "| option.getProcessOptionId(): "
+ option.getProcessOptionId() + "| serviceProcess.getCounterCode(): "
+ serviceProcess.getCounterCode() + "| getStartCounter(): "
+ counterConfig.getStartCounter());
String dossierCounter = ConfigCounterNumberGenerator.generateCounterNumber(dossier.getGroupId(),
dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(),
patternCode, counterConfig, params);
dossier.setDossierCounter(dossierCounter.trim());
_log.info("dossierCounter: " + dossierCounter);
} catch (Exception e) {
_log.debug(e);
}
} else {
String patternCode = counterConfig.getPatternCode();
try {
_log.info("dossierId: " + dossier.getDossierId() + "| option.getProcessOptionId(): "
+ option.getProcessOptionId() + "| serviceProcess.getCounterCode(): "
+ serviceProcess.getCounterCode());
String dossierCounter = ConfigCounterNumberGenerator.generateCounterNumber(dossier.getGroupId(),
dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(),
patternCode, counterConfig, params);
dossier.setDossierCounter(dossierCounter.trim());
_log.info("dossierCounter: " + dossierCounter);
} catch (Exception e) {
_log.debug(e);
}
}
}
}
}
return dossier;
}
private static Log _log = LogFactoryUtil.getLog(CPSDossierBusinessLocalServiceImpl.class);
}
|
Update create cross dossier
|
modules/backend-dossiermgt/backend-dossiermgt-service/src/main/java/org/opencps/dossiermgt/service/impl/CPSDossierBusinessLocalServiceImpl.java
|
Update create cross dossier
|
|
Java
|
agpl-3.0
|
f54e998a6c529adef894fd82c9ffd1d656b04c4a
| 0
|
deepstupid/sphinx5
|
/*
* Copyright 1999-2002 Carnegie Mellon University.
* Portions Copyright 2002 Sun Microsystems, Inc.
* Portions Copyright 2002 Mitsubishi Electric Research Laboratories.
* All Rights Reserved. Use is subject to license terms.
*
* See the file "license.terms" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*
*/
package edu.cmu.sphinx.linguist.language.ngram;
import edu.cmu.sphinx.linguist.WordSequence;
import edu.cmu.sphinx.linguist.dictionary.Dictionary;
import edu.cmu.sphinx.linguist.dictionary.Word;
import edu.cmu.sphinx.util.LogMath;
import edu.cmu.sphinx.util.props.ConfigurationManagerUtils;
import edu.cmu.sphinx.util.props.PropertyException;
import edu.cmu.sphinx.util.props.PropertySheet;
import edu.cmu.sphinx.util.props.S4Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
/**
* An ASCII ARPA language model loader. This loader makes no attempt to optimize storage, so it can only load very small
* language models
* <p/>
* Note that all probabilities in the grammar are stored in LogMath log base format. Language Probabilities in the
* language model file are stored in log 10 base.
*/
public class SimpleNGramModel implements LanguageModel, BackoffLanguageModel {
/** The property that defines the logMath component. */
@S4Component(type = LogMath.class)
public final static String PROP_LOG_MATH = "logMath";
// ----------------------------
// Configuration data
// ----------------------------
private String name;
private LogMath logMath;
private URL urlLocation;
private float unigramWeight;
private Dictionary dictionary;
private int desiredMaxDepth;
private int maxNGram;
private Map<WordSequence, Probability> map;
private Set<String> vocabulary;
protected int lineNumber;
protected BufferedReader reader;
protected String fileName;
private boolean allocated;
public SimpleNGramModel(String location, Dictionary dictionary, float unigramWeight, LogMath logMath,
int desiredMaxDepth ) throws MalformedURLException, ClassNotFoundException {
this(ConfigurationManagerUtils.resourceToURL(location), dictionary, unigramWeight, logMath, desiredMaxDepth );
}
public SimpleNGramModel(URL urlLocation, Dictionary dictionary, float unigramWeight, LogMath logMath,
int desiredMaxDepth ) {
this.urlLocation = urlLocation;
this.unigramWeight = unigramWeight;
this.logMath = logMath;
this.desiredMaxDepth = desiredMaxDepth;
this.dictionary = dictionary;
this.map = new HashMap<WordSequence, Probability>();
this.vocabulary = new HashSet<String>();
}
public SimpleNGramModel() {
}
/*
* (non-Javadoc)
*
* @see edu.cmu.sphinx.util.props.Configurable#newProperties(edu.cmu.sphinx.util.props.PropertySheet)
*/
@Override
public void newProperties(PropertySheet ps) throws PropertyException {
if (allocated) {
throw new RuntimeException("Can't change properties after allocation");
}
urlLocation = ConfigurationManagerUtils.getResource(PROP_LOCATION, ps);
unigramWeight = ps.getFloat(PROP_UNIGRAM_WEIGHT);
logMath = (LogMath) ps.getComponent(PROP_LOG_MATH);
desiredMaxDepth = ps.getInt(PROP_MAX_DEPTH);
dictionary = (Dictionary) ps.getComponent(PROP_DICTIONARY);
map = new HashMap<WordSequence, Probability>();
vocabulary = new HashSet<String>();
}
/*
* (non-Javadoc)
*
* @see edu.cmu.sphinx.linguist.language.ngram.LanguageModel#allocate()
*/
@Override
public void allocate() throws IOException {
allocated = true;
load(urlLocation, unigramWeight, dictionary);
if (desiredMaxDepth > 0) {
if (desiredMaxDepth < maxNGram) {
maxNGram = desiredMaxDepth;
}
}
}
/*
* (non-Javadoc)
*
* @see edu.cmu.sphinx.linguist.language.ngram.LanguageModel#deallocate()
*/
@Override
public void deallocate() {
allocated = false;
}
/*
* (non-Javadoc)
*
* @see edu.cmu.sphinx.util.props.Configurable#getName()
*/
public String getName() {
return name;
}
/** Called before a recognition */
@Override
public void start() {
}
/** Called after a recognition */
@Override
public void stop() {
}
/**
* Gets the ngram probability of the word sequence represented by the word list
*
* @param wordSequence the word sequence
* @return the probability of the word sequence. Probability is in logMath log base
*/
@Override
public float getProbability(WordSequence wordSequence) {
float logProbability = 0.0f;
Probability prob = getProb(wordSequence);
if (prob == null) {
if (wordSequence.size() > 1) {
logProbability = getBackoff(wordSequence.getOldest())
+ getProbability(wordSequence.getNewest());
} else { // if the single word is not in the model at all
// then its zero likelihood that we'll use it
logProbability = LogMath.getLogZero();
}
} else {
logProbability = prob.logProbability;
}
// System.out.println("Search: " + wordSequence + " : "
// + logProbability + " "
// + logMath.logToLinear(logProbability));
return logProbability;
}
/**
* Dummy implementation for backoff
*/
public ProbDepth getProbDepth (WordSequence sequence) {
return new ProbDepth (getProbability(sequence), desiredMaxDepth);
}
/**
* Gets the smear term for the given wordSequence
*
* @param wordSequence the word sequence
* @return the smear term associated with this word sequence
*/
@Override
public float getSmear(WordSequence wordSequence) {
return 0.0f; // TODO not implemented
}
/**
* Returns the backoff probability for the give sequence of words
*
* @param wordSequence the sequence of words
* @return the backoff probability in LogMath log base
*/
public float getBackoff(WordSequence wordSequence) {
float logBackoff = 0.0f; // log of 1.0
Probability prob = getProb(wordSequence);
if (prob != null) {
logBackoff = prob.logBackoff;
}
return logBackoff;
}
/**
* Returns the maximum depth of the language model
*
* @return the maximum depth of the language model
*/
@Override
public int getMaxDepth() {
return maxNGram;
}
/**
* Returns the set of words in the language model. The set is unmodifiable.
*
* @return the unmodifiable set of words
*/
@Override
public Set<String> getVocabulary() {
return Collections.unmodifiableSet(vocabulary);
}
/**
* Gets the probability entry for the given word sequence or null if there is no entry
*
* @param wordSequence a word sequence
* @return the probability entry for the wordlist or null
*/
private Probability getProb(WordSequence wordSequence) {
return map.get(wordSequence);
}
/**
* Converts a wordList to a string
*
* @param wordList the wordList
* @return the string
*/
@SuppressWarnings("unused")
private String listToString(List<Word> wordList) {
StringBuilder sb = new StringBuilder();
for (Word word : wordList)
sb.append(word).append(' ');
return sb.toString();
}
/** Dumps the language model */
public void dump() {
for (Map.Entry<WordSequence, Probability> entry : map.entrySet())
System.out.println(entry.getKey() + " " + entry.getValue());
}
/**
* Retrieves a string representation of the wordlist, suitable for map access
*
* @param wordList the list of words
* @return a string representation of the word list
*/
@SuppressWarnings("unused")
private String getRepresentation(List<String> wordList) {
if (wordList.isEmpty())
return "";
StringBuilder sb = new StringBuilder();
for (String word : wordList)
sb.append(word).append('+');
sb.setLength(sb.length() - 1);
return sb.toString();
}
/**
* Loads the language model from the given location.
*
* @param location the URL location of the model
* @param unigramWeight the unigram weight
* @throws IOException if an error occurs while loading
*/
private void load(URL location, float unigramWeight,
Dictionary dictionary) throws IOException {
String line;
float logUnigramWeight = logMath.linearToLog(unigramWeight);
float inverseLogUnigramWeight = logMath
.linearToLog(1.0 - unigramWeight);
open(location);
// look for beginning of data
readUntil("\\data\\");
// look for ngram statements
List<Integer> ngramList = new ArrayList<Integer>();
while ((line = readLine()) != null) {
if (line.startsWith("ngram")) {
StringTokenizer st = new StringTokenizer(line, " \t\n\r\f=");
if (st.countTokens() != 3) {
corrupt("corrupt ngram field " + line + ' '
+ st.countTokens());
}
st.nextToken();
int index = Integer.parseInt(st.nextToken());
int count = Integer.parseInt(st.nextToken());
ngramList.add(index - 1, count);
if (index > maxNGram) {
maxNGram = index;
}
} else if (line.equals("\\1-grams:")) {
break;
}
}
int numUnigrams = ngramList.get(0) - 1;
// -log(x) = log(1/x)
float logUniformProbability = -logMath.linearToLog(numUnigrams);
for (int index = 0; index < ngramList.size(); index++) {
int ngram = index + 1;
int ngramCount = ngramList.get(index);
for (int i = 0; i < ngramCount; i++) {
StringTokenizer tok = new StringTokenizer(readLine());
int tokenCount = tok.countTokens();
if (tokenCount != ngram + 1 && tokenCount != ngram + 2) {
corrupt("Bad format");
}
float log10Prob = Float.parseFloat(tok.nextToken());
float log10Backoff = 0.0f;
// construct the WordSequence for this N-Gram
List<Word> wordList = new ArrayList<Word>(maxNGram);
for (int j = 0; j < ngram; j++) {
String word = tok.nextToken().toLowerCase();
vocabulary.add(word);
Word wordObject = dictionary.getWord(word);
if (wordObject == null) {
wordObject = Word.UNKNOWN;
}
wordList.add(wordObject);
}
WordSequence wordSequence = new WordSequence(wordList);
if (tok.hasMoreTokens()) {
log10Backoff = Float.parseFloat(tok.nextToken());
}
float logProb = logMath.log10ToLog(log10Prob);
float logBackoff = logMath.log10ToLog(log10Backoff);
// Apply unigram weights if this is a unigram probability
if (ngram == 1) {
float p1 = logProb + logUnigramWeight;
float p2 = logUniformProbability + inverseLogUnigramWeight;
logProb = logMath.addAsLinear(p1, p2);
// System.out
// .println("p1 " + p1 + " p2 " + p2 + " luw "
// + logUnigramWeight + " iluw "
// + inverseLogUnigramWeight + " lup "
// + logUniformProbability + " logprog "
// + logProb);
}
put(wordSequence, logProb, logBackoff);
}
if (index < ngramList.size() - 1) {
String next = "\\" + (ngram + 1) + "-grams:";
readUntil(next);
}
}
readUntil("\\end\\");
close();
}
/**
* Puts the probability into the map
*
* @param wordSequence the tag for the prob.
* @param logProb the probability in log math base
* @param logBackoff the backoff probability in log math base
*/
private void put(WordSequence wordSequence, float logProb, float logBackoff) {
// System.out.println("Putting " + wordSequence + " p " + logProb
// + " b " + logBackoff);
map.put(wordSequence, new Probability(logProb, logBackoff));
}
/**
* Reads the next line from the LM file. Keeps track of line number.
*
* @throws IOException if an error occurs while reading the input or an EOF is encountered.
*/
private String readLine() throws IOException {
String line;
lineNumber++;
line = reader.readLine();
if (line == null) {
corrupt("Premature EOF");
}
return line.trim();
}
/**
* Opens the language model at the given location
*
* @param location the path to the language model
* @throws IOException if an error occurs while opening the file
*/
private void open(URL location) throws
IOException {
lineNumber = 0;
fileName = location.toString();
reader = new BufferedReader
(new InputStreamReader(location.openStream()));
}
/**
* Reads from the input stream until the input matches the given string
*
* @param match the string to match on
* @throws IOException if an error occurs while reading the input or an EOF is encountered before finding the match
*/
private void readUntil(String match) throws IOException {
try {
while (!readLine().equals(match)) {
}
} catch (IOException ioe) {
corrupt("Premature EOF while waiting for " + match);
}
}
/**
* Closes the language model file
*
* @throws IOException if an error occurs
*/
private void close() throws IOException {
reader.close();
reader = null;
}
/**
* Generates a 'corrupt' IO exception
*
* @throws IOException with the given string
*/
private void corrupt(String why) throws IOException {
throw new IOException("Corrupt Language Model " + fileName
+ " at line " + lineNumber + ':' + why);
}
}
/** Represents a probability and a backoff probability */
class Probability {
final float logProbability;
final float logBackoff;
/**
* Constructs a probability
*
* @param logProbability the probability
* @param logBackoff the backoff probability
*/
Probability(float logProbability, float logBackoff) {
this.logProbability = logProbability;
this.logBackoff = logBackoff;
}
/**
* Returns a string representation of this object
*
* @return the string form of this object
*/
@Override
public String toString() {
return "Prob: " + logProbability + ' ' + logBackoff;
}
}
|
src/sphinx4/edu/cmu/sphinx/linguist/language/ngram/SimpleNGramModel.java
|
/*
* Copyright 1999-2002 Carnegie Mellon University.
* Portions Copyright 2002 Sun Microsystems, Inc.
* Portions Copyright 2002 Mitsubishi Electric Research Laboratories.
* All Rights Reserved. Use is subject to license terms.
*
* See the file "license.terms" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*
*/
package edu.cmu.sphinx.linguist.language.ngram;
import edu.cmu.sphinx.linguist.WordSequence;
import edu.cmu.sphinx.linguist.dictionary.Dictionary;
import edu.cmu.sphinx.linguist.dictionary.Word;
import edu.cmu.sphinx.util.LogMath;
import edu.cmu.sphinx.util.props.ConfigurationManagerUtils;
import edu.cmu.sphinx.util.props.PropertyException;
import edu.cmu.sphinx.util.props.PropertySheet;
import edu.cmu.sphinx.util.props.S4Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
/**
* An ASCII ARPA language model loader. This loader makes no attempt to optimize storage, so it can only load very small
* language models
* <p/>
* Note that all probabilities in the grammar are stored in LogMath log base format. Language Probabilities in the
* language model file are stored in log 10 base.
*/
public class SimpleNGramModel implements LanguageModel, BackoffLanguageModel {
/** The property that defines the logMath component. */
@S4Component(type = LogMath.class)
public final static String PROP_LOG_MATH = "logMath";
// ----------------------------
// Configuration data
// ----------------------------
private String name;
private LogMath logMath;
private URL urlLocation;
private float unigramWeight;
private Dictionary dictionary;
private int desiredMaxDepth;
private int maxNGram;
private Map<WordSequence, Probability> map;
private Set<String> vocabulary;
protected int lineNumber;
protected BufferedReader reader;
protected String fileName;
private boolean allocated;
public SimpleNGramModel(String location, Dictionary dictionary, float unigramWeight, LogMath logMath,
int desiredMaxDepth ) throws MalformedURLException, ClassNotFoundException {
this(ConfigurationManagerUtils.resourceToURL(location), dictionary, unigramWeight, logMath, desiredMaxDepth );
}
public SimpleNGramModel(URL urlLocation, Dictionary dictionary, float unigramWeight, LogMath logMath,
int desiredMaxDepth ) {
this.urlLocation = urlLocation;
this.unigramWeight = unigramWeight;
this.logMath = logMath;
this.desiredMaxDepth = desiredMaxDepth;
this.dictionary = dictionary;
this.map = new HashMap<WordSequence, Probability>();
this.vocabulary = new HashSet<String>();
}
public SimpleNGramModel() {
}
/*
* (non-Javadoc)
*
* @see edu.cmu.sphinx.util.props.Configurable#newProperties(edu.cmu.sphinx.util.props.PropertySheet)
*/
@Override
public void newProperties(PropertySheet ps) throws PropertyException {
if (allocated) {
throw new RuntimeException("Can't change properties after allocation");
}
urlLocation = ConfigurationManagerUtils.getResource(PROP_LOCATION, ps);
unigramWeight = ps.getFloat(PROP_UNIGRAM_WEIGHT);
logMath = (LogMath) ps.getComponent(PROP_LOG_MATH);
desiredMaxDepth = ps.getInt(PROP_MAX_DEPTH);
dictionary = (Dictionary) ps.getComponent(PROP_DICTIONARY);
map = new HashMap<WordSequence, Probability>();
vocabulary = new HashSet<String>();
}
/*
* (non-Javadoc)
*
* @see edu.cmu.sphinx.linguist.language.ngram.LanguageModel#allocate()
*/
@Override
public void allocate() throws IOException {
allocated = true;
load(urlLocation, unigramWeight, dictionary);
if (desiredMaxDepth > 0) {
if (desiredMaxDepth < maxNGram) {
maxNGram = desiredMaxDepth;
}
}
}
/*
* (non-Javadoc)
*
* @see edu.cmu.sphinx.linguist.language.ngram.LanguageModel#deallocate()
*/
@Override
public void deallocate() {
allocated = false;
}
/*
* (non-Javadoc)
*
* @see edu.cmu.sphinx.util.props.Configurable#getName()
*/
public String getName() {
return name;
}
/** Called before a recognition */
@Override
public void start() {
}
/** Called after a recognition */
@Override
public void stop() {
}
/**
* Gets the ngram probability of the word sequence represented by the word list
*
* @param wordSequence the word sequence
* @return the probability of the word sequence. Probability is in logMath log base
*/
@Override
public float getProbability(WordSequence wordSequence) {
float logProbability = 0.0f;
Probability prob = getProb(wordSequence);
if (prob == null) {
if (wordSequence.size() > 1) {
logProbability = getBackoff(wordSequence.getOldest())
+ getProbability(wordSequence.getNewest());
} else { // if the single word is not in the model at all
// then its zero likelihood that we'll use it
logProbability = LogMath.getLogZero();
}
} else {
logProbability = prob.logProbability;
}
// System.out.println("Search: " + wordSequence + " : "
// + logProbability + " "
// + logMath.logToLinear(logProbability));
return logProbability;
}
/**
* Dummy implementation for backoff
*/
public ProbDepth getProbDepth (WordSequence sequence) {
return new ProbDepth (getProbability(sequence), desiredMaxDepth);
}
/**
* Gets the smear term for the given wordSequence
*
* @param wordSequence the word sequence
* @return the smear term associated with this word sequence
*/
@Override
public float getSmear(WordSequence wordSequence) {
return 0.0f; // TODO not implemented
}
/**
* Returns the backoff probability for the give sequence of words
*
* @param wordSequence the sequence of words
* @return the backoff probability in LogMath log base
*/
public float getBackoff(WordSequence wordSequence) {
float logBackoff = 0.0f; // log of 1.0
Probability prob = getProb(wordSequence);
if (prob != null) {
logBackoff = prob.logBackoff;
}
return logBackoff;
}
/**
* Returns the maximum depth of the language model
*
* @return the maximum depth of the language model
*/
@Override
public int getMaxDepth() {
return maxNGram;
}
/**
* Returns the set of words in the language model. The set is unmodifiable.
*
* @return the unmodifiable set of words
*/
@Override
public Set<String> getVocabulary() {
return Collections.unmodifiableSet(vocabulary);
}
/**
* Gets the probability entry for the given word sequence or null if there is no entry
*
* @param wordSequence a word sequence
* @return the probability entry for the wordlist or null
*/
private Probability getProb(WordSequence wordSequence) {
return map.get(wordSequence);
}
/**
* Converts a wordList to a string
*
* @param wordList the wordList
* @return the string
*/
@SuppressWarnings("unused")
private String listToString(List<Word> wordList) {
StringBuilder sb = new StringBuilder();
for (Word word : wordList)
sb.append(word).append(' ');
return sb.toString();
}
/** Dumps the language model */
public void dump() {
for (Map.Entry<WordSequence, Probability> entry : map.entrySet())
System.out.println(entry.getKey() + " " + entry.getValue());
}
/**
* Retrieves a string representation of the wordlist, suitable for map access
*
* @param wordList the list of words
* @return a string representation of the word list
*/
@SuppressWarnings("unused")
private String getRepresentation(List<String> wordList) {
if (wordList.isEmpty())
return "";
StringBuilder sb = new StringBuilder();
for (String word : wordList)
sb.append(word).append('+');
sb.setLength(sb.length() - 1);
return sb.toString();
}
/**
* Loads the language model from the given location.
*
* @param location the URL location of the model
* @param unigramWeight the unigram weight
* @throws IOException if an error occurs while loading
*/
private void load(URL location, float unigramWeight,
Dictionary dictionary) throws IOException {
String line;
float logUnigramWeight = logMath.linearToLog(unigramWeight);
float inverseLogUnigramWeight = logMath
.linearToLog(1.0 - unigramWeight);
open(location);
// look for beginning of data
readUntil("\\data\\");
// look for ngram statements
List<Integer> ngramList = new ArrayList<Integer>();
while ((line = readLine()) != null) {
if (line.startsWith("ngram")) {
StringTokenizer st = new StringTokenizer(line, " \t\n\r\f=");
if (st.countTokens() != 3) {
corrupt("corrupt ngram field " + line + ' '
+ st.countTokens());
}
st.nextToken();
int index = Integer.parseInt(st.nextToken());
int count = Integer.parseInt(st.nextToken());
ngramList.add(index - 1, count);
if (index > maxNGram) {
maxNGram = index;
}
} else if (line.equals("\\1-grams:")) {
break;
}
}
int numUnigrams = ngramList.get(0) - 1;
// -log(x) = log(1/x)
float logUniformProbability = -logMath.linearToLog(numUnigrams);
for (int index = 0; index < ngramList.size(); index++) {
int ngram = index + 1;
int ngramCount = ngramList.get(index);
for (int i = 0; i < ngramCount; i++) {
StringTokenizer tok = new StringTokenizer(readLine());
int tokenCount = tok.countTokens();
if (tokenCount != ngram + 1 && tokenCount != ngram + 2) {
corrupt("Bad format");
}
float log10Prob = Float.parseFloat(tok.nextToken());
float log10Backoff = 0.0f;
// construct the WordSequence for this N-Gram
List<Word> wordList = new ArrayList<Word>(maxNGram);
for (int j = 0; j < ngram; j++) {
String word = tok.nextToken().toLowerCase();
vocabulary.add(word);
Word wordObject = dictionary.getWord(word);
if (wordObject == null) {
wordObject = Word.UNKNOWN;
}
wordList.add(wordObject);
}
WordSequence wordSequence = new WordSequence(wordList);
if (tok.hasMoreTokens()) {
log10Backoff = Float.parseFloat(tok.nextToken());
}
float logProb = logMath.log10ToLog(log10Prob);
float logBackoff = logMath.log10ToLog(log10Backoff);
// Apply unigram weights if this is a unigram probability
if (ngram == 1) {
float p1 = logProb + logUnigramWeight;
float p2 = logUniformProbability + inverseLogUnigramWeight;
logProb = logMath.addAsLinear(p1, p2);
// System.out
// .println("p1 " + p1 + " p2 " + p2 + " luw "
// + logUnigramWeight + " iluw "
// + inverseLogUnigramWeight + " lup "
// + logUniformProbability + " logprog "
// + logProb);
}
put(wordSequence, logProb, logBackoff);
}
if (index < ngramList.size() - 1) {
String next = "\\" + (ngram + 1) + "-grams:";
readUntil(next);
}
}
readUntil("\\end\\");
close();
}
/**
* Puts the probability into the map
*
* @param wordSequence the tag for the prob.
* @param logProb the probability in log math base
* @param logBackoff the backoff probability in log math base
*/
private void put(WordSequence wordSequence, float logProb, float logBackoff) {
// System.out.println("Putting " + wordSequence + " p " + logProb
// + " b " + logBackoff);
map.put(wordSequence, new Probability(logProb, logBackoff));
}
/**
* Reads the next line from the LM file. Keeps track of line number.
*
* @throws IOException if an error occurs while reading the input or an EOF is encountered.
*/
private String readLine() throws IOException {
String line;
lineNumber++;
line = reader.readLine();
if (line == null) {
corrupt("Premature EOF");
}
return line;
}
/**
* Opens the language model at the given location
*
* @param location the path to the language model
* @throws IOException if an error occurs while opening the file
*/
private void open(URL location) throws
IOException {
lineNumber = 0;
fileName = location.toString();
reader = new BufferedReader
(new InputStreamReader(location.openStream()));
}
/**
* Reads from the input stream until the input matches the given string
*
* @param match the string to match on
* @throws IOException if an error occurs while reading the input or an EOF is encountered before finding the match
*/
private void readUntil(String match) throws IOException {
try {
while (!readLine().equals(match)) {
}
} catch (IOException ioe) {
corrupt("Premature EOF while waiting for " + match);
}
}
/**
* Closes the language model file
*
* @throws IOException if an error occurs
*/
private void close() throws IOException {
reader.close();
reader = null;
}
/**
* Generates a 'corrupt' IO exception
*
* @throws IOException with the given string
*/
private void corrupt(String why) throws IOException {
throw new IOException("Corrupt Language Model " + fileName
+ " at line " + lineNumber + ':' + why);
}
}
/** Represents a probability and a backoff probability */
class Probability {
final float logProbability;
final float logBackoff;
/**
* Constructs a probability
*
* @param logProbability the probability
* @param logBackoff the backoff probability
*/
Probability(float logProbability, float logBackoff) {
this.logProbability = logProbability;
this.logBackoff = logBackoff;
}
/**
* Returns a string representation of this object
*
* @return the string form of this object
*/
@Override
public String toString() {
return "Prob: " + logProbability + ' ' + logBackoff;
}
}
|
Be nicer about file format. Patch by Firas Al Khalil. Fixes issue
https://sourceforge.net/tracker/?func=detail&atid=301904&aid=3195662&group_id=1904
git-svn-id: a8b04003a33e1d3e001b9d20391fa392a9f62d91@10792 94700074-3cef-4d97-a70e-9c8c206c02f5
|
src/sphinx4/edu/cmu/sphinx/linguist/language/ngram/SimpleNGramModel.java
|
Be nicer about file format. Patch by Firas Al Khalil. Fixes issue
|
|
Java
|
lgpl-2.1
|
80b7d904707326f294ee4c1f0c483f997c89c6c5
| 0
|
xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.rendering.wikimacro.internal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.xwiki.component.annotation.Component;
import org.xwiki.context.Execution;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.SpaceReference;
import org.xwiki.model.reference.WikiReference;
import org.xwiki.query.Query;
import org.xwiki.query.QueryManager;
import org.xwiki.rendering.macro.wikibridge.InsufficientPrivilegesException;
import org.xwiki.rendering.macro.wikibridge.WikiMacro;
import org.xwiki.rendering.macro.wikibridge.WikiMacroException;
import org.xwiki.rendering.macro.wikibridge.WikiMacroFactory;
import org.xwiki.rendering.macro.wikibridge.WikiMacroInitializer;
import org.xwiki.rendering.macro.wikibridge.WikiMacroManager;
import org.xwiki.rendering.syntax.Syntax;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.user.api.XWikiRightService;
/**
* A {@link DefaultWikiMacroInitializer} providing wiki macros.
*
* @version $Id$
* @since 2.0M2
*/
@Component
@Singleton
public class DefaultWikiMacroInitializer implements WikiMacroInitializer, WikiMacroConstants
{
/**
* The {@link org.xwiki.rendering.macro.wikibridge.WikiMacroFactory} component.
*/
@Inject
private WikiMacroFactory wikiMacroFactory;
/**
* The {@link WikiMacroManager} component.
*/
@Inject
private WikiMacroManager wikiMacroManager;
/**
* The {@link Execution} component used for accessing XWikiContext.
*/
@Inject
private Execution execution;
/**
* The logger to log.
*/
@Inject
private Logger logger;
/**
* Utility method for accessing XWikiContext.
*
* @return the XWikiContext.
*/
private XWikiContext getContext()
{
return (XWikiContext) this.execution.getContext().getProperty("xwikicontext");
}
@Override
public void registerExistingWikiMacros() throws Exception
{
registerExistingWikiMacros(false, null);
}
@Override
public void registerExistingWikiMacros(String wiki) throws Exception
{
registerExistingWikiMacros(true, wiki);
}
/**
* Registers the wiki macros for all the wikis or a specific wiki, according to the passed parameter. <br />
* FIXME: I don't like this way of passing params, but it's kinda the best I can do for the moment without
* duplicating at least the logic inside this function, if not some code as well.
*
* @param local false if only macros in a specified wiki are to be registered, in which case, the name of the wiki
* should be specified in the second parameter, false if the macros in all the wikis should be
* registered, in which case the value of the second parameter is ignored
* @param wiki the name of the wiki to register macros for, if local is true
* @throws Exception if xwiki classes required for defining wiki macros are missing or if an error occurs while
* searching for existing wiki macros.
*/
private void registerExistingWikiMacros(boolean local, String wiki) throws Exception
{
XWikiContext xcontext = getContext();
// Register the wiki macros that exist
String originalWiki = xcontext.getDatabase();
try {
if (!local) {
Set<String> wikiNames = new HashSet<String>();
// Add the list of all subwikis
wikiNames.addAll(xcontext.getWiki().getVirtualWikisDatabaseNames(xcontext));
for (String wikiName : wikiNames) {
registerMacrosForWiki(wikiName, xcontext);
}
} else {
registerMacrosForWiki(wiki, xcontext);
}
} finally {
xcontext.setDatabase(originalWiki);
}
}
/**
* Search and register all the macros from the given wiki.
*
* @param wikiName the name of the wiki to process, lowercase database name
* @param xcontext the current request context
*/
private void registerMacrosForWiki(String wikiName, XWikiContext xcontext)
{
try {
this.logger.debug("Registering all wiki macros found in wiki [{}]", wikiName);
// Set the context to be in that wiki so that both the search for XWikiMacro class objects and the
// registration of macros registered for the current wiki will work.
// TODO: In the future when we have APIs for it, move the code to set the current wiki and the current user
// (see below) to the WikiMacroManager's implementation.
xcontext.setDatabase(wikiName);
// Make sure classes exists and are up to date in this wiki
installOrUpgradeWikiMacroClasses();
// Search for all those documents with macro definitions and for each register the macro
for (Object[] wikiMacroDocumentData : getWikiMacroDocumentData(xcontext)) {
// In the database the space and page names are always specified for a document. However the wiki
// part isn't, so we need to replace the wiki reference with the current wiki.
DocumentReference wikiMacroDocumentReference =
new DocumentReference((String) wikiMacroDocumentData[1], new SpaceReference(
(String) wikiMacroDocumentData[0], new WikiReference(wikiName)));
registerMacro(wikiMacroDocumentReference, (String) wikiMacroDocumentData[2], xcontext);
}
} catch (Exception ex) {
this.logger.warn("Failed to register macros for wiki [{}]: {}", wikiName, ex.getMessage());
}
}
/**
* Search for all wiki macros in the current wiki.
*
* @param xcontext the current request context
* @return a list of documents containing wiki macros, each item as a List of 3 strings: space name, document name,
* last author of the document
* @throws Exception if the database search fails
*/
private List<Object[]> getWikiMacroDocumentData(XWikiContext xcontext) throws Exception
{
final QueryManager qm = xcontext.getWiki().getStore().getQueryManager();
final Query q = qm.getNamedQuery("getWikiMacroDocuments");
return (List<Object[]>) (List) q.execute();
}
/**
* Register a wiki macro in the component manager, if the macro author has the required rights.
*
* @param wikiMacroDocumentReference the document holding the macro definition
* @param wikiMacroDocumentAuthor the author of the macro document
* @param xcontext the current request context
*/
private void registerMacro(DocumentReference wikiMacroDocumentReference, String wikiMacroDocumentAuthor,
XWikiContext xcontext)
{
this.logger.debug("Registering macro [{}]...", wikiMacroDocumentReference);
DocumentReference originalAuthor = xcontext.getUserReference();
try {
WikiMacro macro = this.wikiMacroFactory.createWikiMacro(wikiMacroDocumentReference);
this.wikiMacroManager.registerWikiMacro(wikiMacroDocumentReference, macro);
this.logger.debug("Macro [{}] is now registered.", wikiMacroDocumentReference);
} catch (InsufficientPrivilegesException ex) {
// Just log the exception and skip to the next.
// We only log at the debug level here as this is not really an error
this.logger.debug(ex.getMessage(), ex);
} catch (WikiMacroException ex) {
// Just log the exception and skip to the next.
this.logger.error(ex.getMessage(), ex);
} finally {
xcontext.setUserReference(originalAuthor);
}
}
private boolean setWikiMacroClassesDocumentFields(XWikiDocument doc, String title)
{
boolean needsUpdate = false;
if (StringUtils.isBlank(doc.getCreator())) {
needsUpdate = true;
doc.setCreator(XWikiRightService.SUPERADMIN_USER);
}
if (StringUtils.isBlank(doc.getAuthor())) {
needsUpdate = true;
doc.setAuthorReference(doc.getCreatorReference());
}
if (StringUtils.isBlank(doc.getParent())) {
needsUpdate = true;
doc.setParent("XWiki.XWikiClasses");
}
if (StringUtils.isBlank(doc.getTitle())) {
needsUpdate = true;
doc.setTitle(title);
}
if (StringUtils.isBlank(doc.getContent()) || !Syntax.XWIKI_2_0.equals(doc.getSyntax())) {
needsUpdate = true;
doc.setContent("{{include document=\"XWiki.ClassSheet\" /}}");
doc.setSyntax(Syntax.XWIKI_2_0);
}
if (!doc.isHidden()) {
needsUpdate = true;
doc.setHidden(true);
}
return needsUpdate;
}
@Override
public void installOrUpgradeWikiMacroClasses() throws Exception
{
XWikiContext xcontext = getContext();
// Install or Upgrade XWiki.WikiMacroClass
XWikiDocument doc = xcontext.getWiki().getDocument(WIKI_MACRO_CLASS, xcontext);
BaseClass bclass = doc.getXClass();
boolean needsUpdate = false;
needsUpdate |= setWikiMacroClassesDocumentFields(doc, "XWiki Wiki Macro Class");
needsUpdate |= bclass.addTextField(MACRO_ID_PROPERTY, "Macro id", 30);
needsUpdate |= bclass.addTextField(MACRO_NAME_PROPERTY, "Macro name", 30);
needsUpdate |= bclass.addTextAreaField(MACRO_DESCRIPTION_PROPERTY, "Macro description", 40, 5);
needsUpdate |= bclass.addTextField(MACRO_DEFAULT_CATEGORY_PROPERTY, "Default category", 30);
needsUpdate |= bclass.addBooleanField(MACRO_INLINE_PROPERTY, "Supports inline mode", "yesno");
needsUpdate |=
bclass.addStaticListField(MACRO_VISIBILITY_PROPERTY, "Macro visibility", 1, false,
"Current User|Current Wiki|Global", "select", "|");
needsUpdate |=
bclass.addStaticListField(MACRO_CONTENT_TYPE_PROPERTY, "Macro content type", 1, false,
"Optional|Mandatory|No content", "select", "|");
needsUpdate |=
bclass.addTextAreaField(MACRO_CONTENT_DESCRIPTION_PROPERTY,
"Content description (Not applicable for \"No content\" type)", 40, 5);
needsUpdate |= bclass.addTextAreaField(MACRO_CODE_PROPERTY, "Macro code", 40, 20);
if (needsUpdate) {
update(doc);
}
// Install or Upgrade XWiki.WikiMacroParameterClass
doc = xcontext.getWiki().getDocument(WIKI_MACRO_PARAMETER_CLASS, xcontext);
bclass = doc.getXClass();
needsUpdate = false;
needsUpdate |= setWikiMacroClassesDocumentFields(doc, "XWiki Wiki Macro Parameter Class");
needsUpdate |= bclass.addTextField(PARAMETER_NAME_PROPERTY, "Parameter name", 30);
needsUpdate |= bclass.addTextAreaField(PARAMETER_DESCRIPTION_PROPERTY, "Parameter description", 40, 5);
needsUpdate |= bclass.addBooleanField(PARAMETER_MANDATORY_PROPERTY, "Parameter mandatory", "yesno");
needsUpdate |= bclass.addTextField(PARAMETER_DEFAULT_VALUE_PROPERTY, "Parameter default value", 30);
if (needsUpdate) {
update(doc);
}
}
/**
* Utility method for updating a wiki macro class definition document.
*
* @param doc xwiki document containing the wiki macro class.
* @throws XWikiException if an error occurs while saving the document.
*/
private void update(XWikiDocument doc) throws Exception
{
XWikiContext xcontext = getContext();
if (doc.isNew()) {
doc.setParent("XWiki.WebHome");
}
xcontext.getWiki().saveDocument(doc, xcontext);
}
}
|
xwiki-platform-core/xwiki-platform-rendering/xwiki-platform-rendering-wikimacro/xwiki-platform-rendering-wikimacro-store/src/main/java/org/xwiki/rendering/wikimacro/internal/DefaultWikiMacroInitializer.java
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.rendering.wikimacro.internal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.xwiki.component.annotation.Component;
import org.xwiki.context.Execution;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.SpaceReference;
import org.xwiki.model.reference.WikiReference;
import org.xwiki.query.Query;
import org.xwiki.query.QueryManager;
import org.xwiki.rendering.macro.wikibridge.InsufficientPrivilegesException;
import org.xwiki.rendering.macro.wikibridge.WikiMacro;
import org.xwiki.rendering.macro.wikibridge.WikiMacroException;
import org.xwiki.rendering.macro.wikibridge.WikiMacroFactory;
import org.xwiki.rendering.macro.wikibridge.WikiMacroInitializer;
import org.xwiki.rendering.macro.wikibridge.WikiMacroManager;
import org.xwiki.rendering.syntax.Syntax;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.user.api.XWikiRightService;
/**
* A {@link DefaultWikiMacroInitializer} providing wiki macros.
*
* @version $Id$
* @since 2.0M2
*/
@Component
@Singleton
public class DefaultWikiMacroInitializer implements WikiMacroInitializer, WikiMacroConstants
{
/**
* The {@link org.xwiki.rendering.macro.wikibridge.WikiMacroFactory} component.
*/
@Inject
private WikiMacroFactory wikiMacroFactory;
/**
* The {@link WikiMacroManager} component.
*/
@Inject
private WikiMacroManager wikiMacroManager;
/**
* The {@link Execution} component used for accessing XWikiContext.
*/
@Inject
private Execution execution;
/**
* The logger to log.
*/
@Inject
private Logger logger;
/**
* Utility method for accessing XWikiContext.
*
* @return the XWikiContext.
*/
private XWikiContext getContext()
{
return (XWikiContext) this.execution.getContext().getProperty("xwikicontext");
}
@Override
public void registerExistingWikiMacros() throws Exception
{
registerExistingWikiMacros(false, null);
}
@Override
public void registerExistingWikiMacros(String wiki) throws Exception
{
registerExistingWikiMacros(true, wiki);
}
/**
* Registers the wiki macros for all the wikis or a specific wiki, according to the passed parameter. <br />
* FIXME: I don't like this way of passing params, but it's kinda the best I can do for the moment without
* duplicating at least the logic inside this function, if not some code as well.
*
* @param local false if only macros in a specified wiki are to be registered, in which case, the name of the wiki
* should be specified in the second parameter, false if the macros in all the wikis should be
* registered, in which case the value of the second parameter is ignored
* @param wiki the name of the wiki to register macros for, if local is true
* @throws Exception if xwiki classes required for defining wiki macros are missing or if an error occurs while
* searching for existing wiki macros.
*/
private void registerExistingWikiMacros(boolean local, String wiki) throws Exception
{
XWikiContext xcontext = getContext();
// Register the wiki macros that exist
String originalWiki = xcontext.getDatabase();
try {
if (!local) {
Set<String> wikiNames = new HashSet<String>();
// Add the list of all subwikis
wikiNames.addAll(xcontext.getWiki().getVirtualWikisDatabaseNames(xcontext));
for (String wikiName : wikiNames) {
registerMacrosForWiki(wikiName, xcontext);
}
} else {
registerMacrosForWiki(wiki, xcontext);
}
} finally {
xcontext.setDatabase(originalWiki);
}
}
/**
* Search and register all the macros from the given wiki.
*
* @param wikiName the name of the wiki to process, lowercase database name
* @param xcontext the current request context
*/
private void registerMacrosForWiki(String wikiName, XWikiContext xcontext)
{
try {
this.logger.debug("Registering wiki macros for wiki {}", wikiName);
// Set the context to be in that wiki so that both the search for XWikiMacro class objects and the
// registration of macros registered for the current wiki will work.
// TODO: In the future when we have APIs for it, move the code to set the current wiki and the current user
// (see below) to the WikiMacroManager's implementation.
xcontext.setDatabase(wikiName);
// Make sure classes exists and are up to date in this wiki
installOrUpgradeWikiMacroClasses();
// Search for all those documents with macro definitions and for each register the macro
for (Object[] wikiMacroDocumentData : getWikiMacroDocumentData(xcontext)) {
// In the database the space and page names are always specified for a document. However the wiki
// part isn't, so we need to replace the wiki reference with the current wiki.
DocumentReference wikiMacroDocumentReference =
new DocumentReference((String) wikiMacroDocumentData[1], new SpaceReference(
(String) wikiMacroDocumentData[0], new WikiReference(wikiName)));
registerMacro(wikiMacroDocumentReference, (String) wikiMacroDocumentData[2], xcontext);
}
} catch (Exception ex) {
this.logger.warn("Failed to register macros for wiki [{}]: {}", wikiName, ex.getMessage());
}
}
/**
* Search for all wiki macros in the current wiki.
*
* @param xcontext the current request context
* @return a list of documents containing wiki macros, each item as a List of 3 strings: space name, document name,
* last author of the document
* @throws Exception if the database search fails
*/
private List<Object[]> getWikiMacroDocumentData(XWikiContext xcontext) throws Exception
{
final QueryManager qm = xcontext.getWiki().getStore().getQueryManager();
final Query q = qm.getNamedQuery("getWikiMacroDocuments");
return (List<Object[]>) (List) q.execute();
}
/**
* Register a wiki macro in the component manager, if the macro author has the required rights.
*
* @param wikiMacroDocumentReference the document holding the macro definition
* @param wikiMacroDocumentAuthor the author of the macro document
* @param xcontext the current request context
*/
private void registerMacro(DocumentReference wikiMacroDocumentReference, String wikiMacroDocumentAuthor,
XWikiContext xcontext)
{
this.logger.debug("Found macro: {}", wikiMacroDocumentReference);
DocumentReference originalAuthor = xcontext.getUserReference();
try {
WikiMacro macro = this.wikiMacroFactory.createWikiMacro(wikiMacroDocumentReference);
this.wikiMacroManager.registerWikiMacro(wikiMacroDocumentReference, macro);
this.logger.debug("Registered macro " + wikiMacroDocumentReference);
} catch (InsufficientPrivilegesException ex) {
// Just log the exception and skip to the next.
// We only log at the debug level here as this is not really an error
this.logger.debug(ex.getMessage(), ex);
} catch (WikiMacroException ex) {
// Just log the exception and skip to the next.
this.logger.error(ex.getMessage(), ex);
} finally {
xcontext.setUserReference(originalAuthor);
}
}
private boolean setWikiMacroClassesDocumentFields(XWikiDocument doc, String title)
{
boolean needsUpdate = false;
if (StringUtils.isBlank(doc.getCreator())) {
needsUpdate = true;
doc.setCreator(XWikiRightService.SUPERADMIN_USER);
}
if (StringUtils.isBlank(doc.getAuthor())) {
needsUpdate = true;
doc.setAuthorReference(doc.getCreatorReference());
}
if (StringUtils.isBlank(doc.getParent())) {
needsUpdate = true;
doc.setParent("XWiki.XWikiClasses");
}
if (StringUtils.isBlank(doc.getTitle())) {
needsUpdate = true;
doc.setTitle(title);
}
if (StringUtils.isBlank(doc.getContent()) || !Syntax.XWIKI_2_0.equals(doc.getSyntax())) {
needsUpdate = true;
doc.setContent("{{include document=\"XWiki.ClassSheet\" /}}");
doc.setSyntax(Syntax.XWIKI_2_0);
}
if (!doc.isHidden()) {
needsUpdate = true;
doc.setHidden(true);
}
return needsUpdate;
}
@Override
public void installOrUpgradeWikiMacroClasses() throws Exception
{
XWikiContext xcontext = getContext();
// Install or Upgrade XWiki.WikiMacroClass
XWikiDocument doc = xcontext.getWiki().getDocument(WIKI_MACRO_CLASS, xcontext);
BaseClass bclass = doc.getXClass();
boolean needsUpdate = false;
needsUpdate |= setWikiMacroClassesDocumentFields(doc, "XWiki Wiki Macro Class");
needsUpdate |= bclass.addTextField(MACRO_ID_PROPERTY, "Macro id", 30);
needsUpdate |= bclass.addTextField(MACRO_NAME_PROPERTY, "Macro name", 30);
needsUpdate |= bclass.addTextAreaField(MACRO_DESCRIPTION_PROPERTY, "Macro description", 40, 5);
needsUpdate |= bclass.addTextField(MACRO_DEFAULT_CATEGORY_PROPERTY, "Default category", 30);
needsUpdate |= bclass.addBooleanField(MACRO_INLINE_PROPERTY, "Supports inline mode", "yesno");
needsUpdate |=
bclass.addStaticListField(MACRO_VISIBILITY_PROPERTY, "Macro visibility", 1, false,
"Current User|Current Wiki|Global", "select", "|");
needsUpdate |=
bclass.addStaticListField(MACRO_CONTENT_TYPE_PROPERTY, "Macro content type", 1, false,
"Optional|Mandatory|No content", "select", "|");
needsUpdate |=
bclass.addTextAreaField(MACRO_CONTENT_DESCRIPTION_PROPERTY,
"Content description (Not applicable for \"No content\" type)", 40, 5);
needsUpdate |= bclass.addTextAreaField(MACRO_CODE_PROPERTY, "Macro code", 40, 20);
if (needsUpdate) {
update(doc);
}
// Install or Upgrade XWiki.WikiMacroParameterClass
doc = xcontext.getWiki().getDocument(WIKI_MACRO_PARAMETER_CLASS, xcontext);
bclass = doc.getXClass();
needsUpdate = false;
needsUpdate |= setWikiMacroClassesDocumentFields(doc, "XWiki Wiki Macro Parameter Class");
needsUpdate |= bclass.addTextField(PARAMETER_NAME_PROPERTY, "Parameter name", 30);
needsUpdate |= bclass.addTextAreaField(PARAMETER_DESCRIPTION_PROPERTY, "Parameter description", 40, 5);
needsUpdate |= bclass.addBooleanField(PARAMETER_MANDATORY_PROPERTY, "Parameter mandatory", "yesno");
needsUpdate |= bclass.addTextField(PARAMETER_DEFAULT_VALUE_PROPERTY, "Parameter default value", 30);
if (needsUpdate) {
update(doc);
}
}
/**
* Utility method for updating a wiki macro class definition document.
*
* @param doc xwiki document containing the wiki macro class.
* @throws XWikiException if an error occurs while saving the document.
*/
private void update(XWikiDocument doc) throws Exception
{
XWikiContext xcontext = getContext();
if (doc.isNew()) {
doc.setParent("XWiki.WebHome");
}
xcontext.getWiki().saveDocument(doc, xcontext);
}
}
|
[Misc] Improve logging slightly
|
xwiki-platform-core/xwiki-platform-rendering/xwiki-platform-rendering-wikimacro/xwiki-platform-rendering-wikimacro-store/src/main/java/org/xwiki/rendering/wikimacro/internal/DefaultWikiMacroInitializer.java
|
[Misc] Improve logging slightly
|
|
Java
|
lgpl-2.1
|
f9d3831593f88d9410b66d2ea92c52a83762e547
| 0
|
sbliven/biojava,sbliven/biojava,sbliven/biojava
|
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
* Created on 11.05.2004
*/
package org.biojava.bio.program.das.dasalignment;
import java.util.ArrayList;
import java.util.List;
import org.biojava.bio.Annotation;
import org.biojava.bio.AnnotationType;
import org.biojava.bio.CardinalityConstraint;
import org.biojava.bio.CollectionConstraint;
import org.biojava.bio.PropertyConstraint;
/**
* Alignment object to contain/manage a DAS alignment.
* @see also DAS specification at http://wwwdev.sanger.ac.uk/xml/das/documentation/new_spec.html
*
* @author Andreas Prlic
* @since 1.4
*/
public class Alignment {
private List objects;
private List scores;
private List blocks;
private static final AnnotationType objectType;
private static final AnnotationType scoreType;
private static final AnnotationType blockType;
private static final AnnotationType segmentType;
static {
objectType = getObjectAnnotationType() ;
scoreType = getScoreAnnotationType() ;
segmentType = getSegmentAnnotationType();
blockType = getBlockAnnotationType() ;
}
/**
* Construct a new empty Alignment object.
*/
public Alignment() {
objects = new ArrayList();
scores = new ArrayList() ;
blocks = new ArrayList() ;
}
/** define the alignment Score Annotation Type */
public static AnnotationType getScoreAnnotationType() {
AnnotationType annType ;
annType = new AnnotationType.Impl();
annType.setConstraints("methodName",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE ) ;
annType.setConstraints("value",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE ) ;
return annType ;
}
/** define the alignment Block Annotation Type */
public static AnnotationType getBlockAnnotationType() {
AnnotationType annType ;
annType = new AnnotationType.Impl();
annType.setConstraints("blockOrder",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE ) ;
annType.setConstraints("blockScore",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ANY ) ;
PropertyConstraint prop = new PropertyConstraint.ByAnnotationType(segmentType) ;
annType.setConstraint("segments",
new CollectionConstraint.AllValuesIn(prop,CardinalityConstraint.ANY)) ;
return annType ;
}
/** define the alignment Segment Annotation Type */
public static AnnotationType getSegmentAnnotationType() {
AnnotationType annType ;
annType = new AnnotationType.Impl();
annType.setConstraints("intObjectId",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE ) ;
annType.setConstraints("start",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ANY ) ;
annType.setConstraints("end",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ANY) ;
annType.setConstraints("strand",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ANY ) ;
annType.setConstraints("cigar",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ANY ) ;
return annType ;
}
/** define the alignment object Annotation Type */
public static AnnotationType getObjectAnnotationType() {
AnnotationType annType;
annType = new AnnotationType.Impl();
//annType.setDefaultConstraints(PropertyConstraint.ANY, CardinalityConstraint.ANY) ;
annType.setConstraints("dbAccessionId",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE );
annType.setConstraints("intObjectId",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE );
annType.setConstraints("objectVersion",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE );
// type is an enumeration ... Hm.
annType.setConstraints("type",
new PropertyConstraint.Enumeration(new Object[] {"DNA","PROTEIN","STRUCTURE"}),
CardinalityConstraint.ANY );
annType.setConstraints("dbSource",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE );
annType.setConstraints("dbVersion",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE );
// optional
annType.setConstraints("dbCoordSys",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ANY );
return annType ;
}
public void addObject(Annotation object)
throws DASException
{
// check if object is valid, throws DASException ...
//checkObjectHash(object);
if(objectType.instanceOf(object)) {
objects.add(object) ;
} else {
throw new
IllegalArgumentException(
"Expecting an annotation conforming to: " +
objectType + " but got: " + object
);
}
}
public List getObjects(){
return objects ;
}
public void addScore(Annotation score)
throws DASException
{
//checkScoreHash(score) ;
if(scoreType.instanceOf(score)) {
scores.add(score) ;
} else {
throw new
IllegalArgumentException(
"Expecting an annotation conforming to: " +
scoreType + " but got: " + score
);
}
}
public List getScores(){
return scores ;
}
public void addBlock(Annotation block)
throws DASException
{
//checkBlockList(segment);
//blocks.add(segment);
if(blockType.instanceOf(block)) {
blocks.add(block) ;
} else {
throw new
IllegalArgumentException(
"Expecting an annotation conforming to: " +
blockType + " but got: " + block
);
}
}
public List getBlocks() {
return blocks;
}
public String toString() {
String str = "" ;
for ( int i=0;i<objects.size();i++){
Annotation object = (Annotation)objects.get(i);
str += "object: "+ (String)object.getProperty("dbAccessionId")+"\n";
}
str += "number of blocks: "+blocks.size();
return str ;
}
/*
static void validateMap(Map m, Object[] requiredKeys)
throws DASException
{
for (int i = 0; i < requiredKeys.length; ++i) {
if (!m.containsKey(requiredKeys[i])) {
throw new DASException("Required key >" + requiredKeys[i] + "< is not present");
}
}
}
*/
}
|
src/org/biojava/bio/program/das/dasalignment/Alignment.java
|
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
* Created on 11.05.2004
*/
package org.biojava.bio.program.das.dasalignment;
import org.biojava.bio.program.ssbind.* ;
import org.biojava.bio.* ;
import org.biojava.bio.CollectionConstraint.AllValuesIn ;
import java.util.* ;
/**
* Alignment object to contain/manage a DAS alignment.
* @see also DAS specification at http://wwwdev.sanger.ac.uk/xml/das/documentation/new_spec.html
* @author Andreas Prlic
*/
public class Alignment {
ArrayList objects ;
ArrayList scores ;
ArrayList blocks ;
AnnotationType objectType ;
AnnotationType scoreType ;
AnnotationType blockType ;
AnnotationType segmentType ;
public Alignment() {
objects = new ArrayList();
scores = new ArrayList() ;
blocks = new ArrayList() ;
// define the Annotation types used for object score and block:
objectType = getObjectAnnotationType() ;
scoreType = getScoreAnnotationType() ;
//segmentType is initialized in getBlockAnnotationType
blockType = getBlockAnnotationType() ;
}
/** define the alignment Score Annotation Type */
public AnnotationType getScoreAnnotationType() {
AnnotationType annType ;
annType = new AnnotationType.Impl();
annType.setConstraints("methodName",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE ) ;
annType.setConstraints("value",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE ) ;
return annType ;
}
/** define the alignment Block Annotation Type */
public AnnotationType getBlockAnnotationType() {
AnnotationType annType ;
segmentType = getSegmentAnnotationType();
annType = new AnnotationType.Impl();
annType.setConstraints("blockOrder",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE ) ;
annType.setConstraints("blockScore",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ANY ) ;
PropertyConstraint prop = new PropertyConstraint.ByAnnotationType(segmentType) ;
annType.setConstraint("segments",
new CollectionConstraint.AllValuesIn(prop,CardinalityConstraint.ANY)) ;
return annType ;
}
/** define the alignment Segment Annotation Type */
public AnnotationType getSegmentAnnotationType() {
AnnotationType annType ;
annType = new AnnotationType.Impl();
annType.setConstraints("intObjectId",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE ) ;
annType.setConstraints("start",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ANY ) ;
annType.setConstraints("end",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ANY) ;
annType.setConstraints("strand",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ANY ) ;
annType.setConstraints("cigar",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ANY ) ;
return annType ;
}
/** define the alignment object Annotation Type */
public AnnotationType getObjectAnnotationType() {
AnnotationType annType;
annType = new AnnotationType.Impl();
//annType.setDefaultConstraints(PropertyConstraint.ANY, CardinalityConstraint.ANY) ;
annType.setConstraints("dbAccessionId",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE );
annType.setConstraints("intObjectId",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE );
annType.setConstraints("objectVersion",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE );
// type is an enumeration ... Hm.
annType.setConstraints("type",
new PropertyConstraint.Enumeration(new Object[] {"DNA","PROTEIN","STRUCTURE"}),
CardinalityConstraint.ANY );
annType.setConstraints("dbSource",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE );
annType.setConstraints("dbVersion",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ONE );
// optional
annType.setConstraints("dbCoordSys",
new PropertyConstraint.ByClass(String.class),
CardinalityConstraint.ANY );
return annType ;
}
public void addObject(Annotation object)
throws DASException
{
// check if object is valid, throws DASException ...
//checkObjectHash(object);
if(objectType.instanceOf(object)) {
objects.add(object) ;
} else {
throw new
IllegalArgumentException(
"Expecting an annotation conforming to: " +
objectType + " but got: " + object
);
}
}
public ArrayList getObjects(){
return objects ;
}
public void addScore(Annotation score)
throws DASException
{
//checkScoreHash(score) ;
if(scoreType.instanceOf(score)) {
scores.add(score) ;
} else {
throw new
IllegalArgumentException(
"Expecting an annotation conforming to: " +
scoreType + " but got: " + score
);
}
}
public ArrayList getScores(){
return scores ;
}
public void addBlock(Annotation block)
throws DASException
{
//checkBlockList(segment);
//blocks.add(segment);
if(blockType.instanceOf(block)) {
blocks.add(block) ;
} else {
throw new
IllegalArgumentException(
"Expecting an annotation conforming to: " +
blockType + " but got: " + block
);
}
}
public ArrayList getBlocks() {
return blocks;
}
public String toString() {
String str = "" ;
for ( int i=0;i<objects.size();i++){
Annotation object = (Annotation)objects.get(i);
str += "object: "+ (String)object.getProperty("dbAccessionId")+"\n";
}
str += "number of blocks: "+blocks.size();
return str ;
}
/*
static void validateMap(Map m, Object[] requiredKeys)
throws DASException
{
for (int i = 0; i < requiredKeys.length; ++i) {
if (!m.containsKey(requiredKeys[i])) {
throw new DASException("Required key >" + requiredKeys[i] + "< is not present");
}
}
}
*/
}
|
Refer to interfaces rather than concrete types (ArrayList -> List)
Made the annotation types singletons.
git-svn-id: ed25c26de1c5325e8eb0deed0b990ab8af8a4def@3270 7c6358e6-4a41-0410-a743-a5b2a554c398
|
src/org/biojava/bio/program/das/dasalignment/Alignment.java
|
Refer to interfaces rather than concrete types (ArrayList -> List)
Made the annotation types singletons.
|
|
Java
|
lgpl-2.1
|
61aec8a04dc82b970d70d4734e4e73aaebda1194
| 0
|
exedio/copernica,exedio/copernica,exedio/copernica
|
/*
* Copyright (C) 2004-2006 exedio GmbH (www.exedio.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.
*
* 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 com.exedio.cope.pattern;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.exedio.cope.Item;
import com.exedio.cope.Model;
import com.exedio.cope.NoSuchIDException;
import com.exedio.cope.Pattern;
public abstract class MediaPath extends Pattern
{
private String urlPath = null;
private String mediaRootUrl = null;
@Override
public void initialize()
{
final String name = getName();
urlPath = getType().getID() + '/' + name + '/';
}
final String getUrlPath()
{
if(urlPath==null)
throw new RuntimeException("not yet initialized");
return urlPath;
}
private final String getMediaRootUrl()
{
if(mediaRootUrl==null)
mediaRootUrl = getType().getModel().getProperties().getMediaRootUrl();
return mediaRootUrl;
}
private static final HashMap<String, String> contentTypeToExtension = new HashMap<String, String>();
static
{
contentTypeToExtension.put("image/jpeg", ".jpg");
contentTypeToExtension.put("image/pjpeg", ".jpg");
contentTypeToExtension.put("image/gif", ".gif");
contentTypeToExtension.put("image/png", ".png");
contentTypeToExtension.put("text/html", ".html");
contentTypeToExtension.put("text/plain", ".txt");
contentTypeToExtension.put("text/css", ".css");
contentTypeToExtension.put("application/java-archive", ".jar");
}
/**
* Returns a URL the content of this media path is available under,
* if a {@link MediaServlet} is properly installed.
* Returns null, if there is no such content.
*/
public final String getURL(final Item item)
{
final String contentType = getContentType(item);
if(contentType==null)
return null;
final StringBuffer bf = new StringBuffer(getMediaRootUrl());
bf.append(getUrlPath()).
append(item.getCopeID());
final String extension = contentTypeToExtension.get(contentType);
if(extension!=null)
bf.append(extension);
return bf.toString();
}
public static final Log noSuchPath = new Log("no such path", HttpServletResponse.SC_NOT_FOUND);
public final Log exception = new Log("exception", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
public final Log notAnItem = new Log("not an item", HttpServletResponse.SC_NOT_FOUND);
public final Log noSuchItem = new Log("no such item", HttpServletResponse.SC_NOT_FOUND);
public final Log isNull = new Log("is null", HttpServletResponse.SC_NOT_FOUND);
public final Log notComputable = new Log("not computable", HttpServletResponse.SC_NOT_FOUND);
public final Log notModified = new Log("not modified", HttpServletResponse.SC_OK);
public final Log delivered = new Log("delivered", HttpServletResponse.SC_OK);
final Media.Log doGet(
final HttpServletRequest request, final HttpServletResponse response,
final String subPath)
throws ServletException, IOException
{
//final long start = System.currentTimeMillis();
final int firstDot = subPath.indexOf('.');
final int dot = (firstDot>=0) ? subPath.indexOf('.', firstDot+1) : firstDot;
//System.out.println("trailingDot="+trailingDot);
final String id;
final String extension;
if(dot>=0)
{
id = subPath.substring(0, dot);
extension = subPath.substring(dot);
}
else
{
id = subPath;
extension = "";
}
//System.out.println("ID="+id);
final Model model = getType().getModel();
try
{
model.startTransaction("MediaServlet");
final Item item = model.findByID(id);
//System.out.println("item="+item);
final Media.Log result = doGet(request, response, item, extension);
model.commit();
//System.out.println("request for " + toString() + " took " + (System.currentTimeMillis() - start) + " ms.");
return result;
}
catch(NoSuchIDException e)
{
return e.notAnID() ? notAnItem : noSuchItem;
}
finally
{
model.rollbackIfNotCommitted();
}
}
public abstract String getContentType(Item item);
public abstract Media.Log doGet(HttpServletRequest request, HttpServletResponse response, Item item, String extension)
throws ServletException, IOException;
// logs --------------------------
private final long start = System.currentTimeMillis();
public final Date getStart()
{
return new Date(start);
}
public final static class Log
{
private int counter = 0;
private final Object lock = new Object();
final String name;
public final int responseStatus;
Log(final String name, final int responseStatus)
{
if(name==null)
throw new NullPointerException();
switch(responseStatus)
{
case HttpServletResponse.SC_OK:
case HttpServletResponse.SC_NOT_FOUND:
case HttpServletResponse.SC_INTERNAL_SERVER_ERROR:
break;
default:
throw new RuntimeException(String.valueOf(responseStatus));
}
this.name = name;
this.responseStatus = responseStatus;
}
public final void increment()
{
synchronized(lock)
{
counter++;
}
}
public final int get()
{
synchronized(lock)
{
return counter;
}
}
}
}
|
runtime/servletsrc/com/exedio/cope/pattern/MediaPath.java
|
/*
* Copyright (C) 2004-2006 exedio GmbH (www.exedio.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.
*
* 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 com.exedio.cope.pattern;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.exedio.cope.Item;
import com.exedio.cope.Model;
import com.exedio.cope.NoSuchIDException;
import com.exedio.cope.Pattern;
public abstract class MediaPath extends Pattern
{
private String urlPath = null;
private String mediaRootUrl = null;
@Override
public void initialize()
{
final String name = getName();
urlPath = getType().getID() + '/' + name + '/';
}
final String getUrlPath()
{
if(urlPath==null)
throw new RuntimeException("not yet initialized");
return urlPath;
}
private final String getMediaRootUrl()
{
if(mediaRootUrl==null)
mediaRootUrl = getType().getModel().getProperties().getMediaRootUrl();
return mediaRootUrl;
}
private static final HashMap<String, String> contentTypeToExtension = new HashMap<String, String>();
static
{
contentTypeToExtension.put("image/jpeg", ".jpg");
contentTypeToExtension.put("image/pjpeg", ".jpg");
contentTypeToExtension.put("image/gif", ".gif");
contentTypeToExtension.put("image/png", ".png");
contentTypeToExtension.put("text/html", ".html");
contentTypeToExtension.put("text/plain", ".txt");
contentTypeToExtension.put("text/css", ".css");
contentTypeToExtension.put("application/java-archive", ".jar");
}
/**
* Returns a URL the content of this media path is available under,
* if a {@link MediaServlet} is properly installed.
* Returns null, if there is no such content.
*/
public final String getURL(final Item item)
{
final String contentType = getContentType(item);
if(contentType==null)
return null;
final StringBuffer bf = new StringBuffer(getMediaRootUrl());
bf.append(getUrlPath()).
append(item.getCopeID());
final String extension = contentTypeToExtension.get(contentType);
if(extension!=null)
bf.append(extension);
return bf.toString();
}
public static final Log noSuchPath = new Log("no such path", HttpServletResponse.SC_NOT_FOUND);
public final Log exception = new Log("exception", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
public final Log notAnItem = new Log("not an item", HttpServletResponse.SC_NOT_FOUND);
public final Log noSuchItem = new Log("no such item", HttpServletResponse.SC_NOT_FOUND);
public final Log isNull = new Log("is null", HttpServletResponse.SC_NOT_FOUND);
public final Log notComputable = new Log("not computable", HttpServletResponse.SC_NOT_FOUND);
public final Log notModified = new Log("not modified", HttpServletResponse.SC_OK);
public final Log delivered = new Log("delivered", HttpServletResponse.SC_OK);
final Media.Log doGet(
final HttpServletRequest request, final HttpServletResponse response,
final String subPath)
throws ServletException, IOException
{
final int firstDot = subPath.indexOf('.');
final int dot = (firstDot>=0) ? subPath.indexOf('.', firstDot+1) : firstDot;
//System.out.println("trailingDot="+trailingDot);
final String id;
final String extension;
if(dot>=0)
{
id = subPath.substring(0, dot);
extension = subPath.substring(dot);
}
else
{
id = subPath;
extension = "";
}
//System.out.println("ID="+id);
final Model model = getType().getModel();
try
{
model.startTransaction("MediaServlet");
final Item item = model.findByID(id);
//System.out.println("item="+item);
final Media.Log result = doGet(request, response, item, extension);
model.commit();
return result;
}
catch(NoSuchIDException e)
{
return e.notAnID() ? notAnItem : noSuchItem;
}
finally
{
model.rollbackIfNotCommitted();
}
}
public abstract String getContentType(Item item);
public abstract Media.Log doGet(HttpServletRequest request, HttpServletResponse response, Item item, String extension)
throws ServletException, IOException;
// logs --------------------------
private final long start = System.currentTimeMillis();
public final Date getStart()
{
return new Date(start);
}
public final static class Log
{
private int counter = 0;
private final Object lock = new Object();
final String name;
public final int responseStatus;
Log(final String name, final int responseStatus)
{
if(name==null)
throw new NullPointerException();
switch(responseStatus)
{
case HttpServletResponse.SC_OK:
case HttpServletResponse.SC_NOT_FOUND:
case HttpServletResponse.SC_INTERNAL_SERVER_ERROR:
break;
default:
throw new RuntimeException(String.valueOf(responseStatus));
}
this.name = name;
this.responseStatus = responseStatus;
}
public final void increment()
{
synchronized(lock)
{
counter++;
}
}
public final int get()
{
synchronized(lock)
{
return counter;
}
}
}
}
|
add disabled clock for requests
git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@6954 e7d4fc99-c606-0410-b9bf-843393a9eab7
|
runtime/servletsrc/com/exedio/cope/pattern/MediaPath.java
|
add disabled clock for requests
|
|
Java
|
lgpl-2.1
|
b934d4e7cf91e02fe579b33cbf26e648f9330cb9
| 0
|
neoedmund/jediterm,neoedmund/jediterm
|
package com.jediterm.terminal.ui;
import com.google.common.base.Ascii;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Lists;
import com.jediterm.terminal.*;
import com.jediterm.terminal.TextStyle.Option;
import com.jediterm.terminal.display.*;
import com.jediterm.terminal.emulator.ColorPalette;
import com.jediterm.terminal.emulator.mouse.TerminalMouseListener;
import com.jediterm.terminal.ui.settings.SettingsProvider;
import com.jediterm.terminal.util.Pair;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.font.TextHitInfo;
import java.awt.im.InputMethodRequests;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.AttributedCharacterIterator;
import java.text.CharacterIterator;
import java.util.List;
public class TerminalPanel extends JComponent implements TerminalDisplay, ClipboardOwner, StyledTextConsumer, TerminalActionProvider {
private static final Logger LOG = Logger.getLogger(TerminalPanel.class);
private static final long serialVersionUID = -1048763516632093014L;
private static final double FPS = 50;
public static final double SCROLL_SPEED = 0.05;
/*images*/
private BufferedImage myImage;
protected Graphics2D myGfx;
private BufferedImage myImageForSelection;
private Graphics2D myGfxForSelection;
private BufferedImage myImageForCursor;
private Graphics2D myGfxForCursor;
private final Component myTerminalPanel = this;
/*font related*/
private Font myNormalFont;
private Font myBoldFont;
private int myDescent = 0;
protected Dimension myCharSize = new Dimension();
private boolean myMonospaced;
protected Dimension myTermSize = new Dimension(80, 24);
private TerminalStarter myTerminalStarter = null;
private Point mySelectionStartPoint = null;
private TerminalSelection mySelection = null;
private Clipboard myClipboard;
private TerminalPanelListener myTerminalPanelListener;
private SettingsProvider mySettingsProvider;
final private BackBuffer myBackBuffer;
final private StyleState myStyleState;
/*scroll and cursor*/
final private TerminalCursor myCursor = new TerminalCursor();
private final BoundedRangeModel myBoundedRangeModel = new DefaultBoundedRangeModel(0, 80, 0, 80);
protected int myClientScrollOrigin;
protected int newClientScrollOrigin;
protected KeyListener myKeyListener;
private long myLastCursorChange;
private boolean myCursorIsShown;
private long myLastResize;
private boolean myScrollingEnabled = true;
private String myWindowTitle = "Terminal";
private TerminalActionProvider myNextActionProvider;
private String myInputMethodUncommitedChars;
public TerminalPanel(@NotNull SettingsProvider settingsProvider, @NotNull BackBuffer backBuffer, @NotNull StyleState styleState) {
mySettingsProvider = settingsProvider;
myBackBuffer = backBuffer;
myStyleState = styleState;
myTermSize.width = backBuffer.getWidth();
myTermSize.height = backBuffer.getHeight();
updateScrolling();
enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.INPUT_METHOD_EVENT_MASK);
enableInputMethods(true);
}
public void init() {
myNormalFont = createFont();
myBoldFont = myNormalFont.deriveFont(Font.BOLD);
establishFontMetrics();
setupImages();
setUpClipboard();
setPreferredSize(new Dimension(getPixelWidth(), getPixelHeight()));
setFocusable(true);
enableInputMethods(true);
setFocusTraversalKeysEnabled(false);
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(final MouseEvent e) {
final Point charCoords = panelToCharCoords(e.getPoint());
if (mySelection == null) {
// prevent unlikely case where drag started outside terminal panel
if (mySelectionStartPoint == null) {
mySelectionStartPoint = charCoords;
}
mySelection = new TerminalSelection(new Point(mySelectionStartPoint));
}
repaint();
mySelection.updateEnd(charCoords);
if (mySettingsProvider.copyOnSelect()) {
handleCopy(false);
}
if (e.getPoint().y < 0) {
moveScrollBar((int)((e.getPoint().y) * SCROLL_SPEED));
}
if (e.getPoint().y > getPixelHeight()) {
moveScrollBar((int)((e.getPoint().y - getPixelHeight()) * SCROLL_SPEED));
}
}
});
addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
int notches = e.getWheelRotation();
moveScrollBar(notches);
}
});
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
if (e.getClickCount() == 1) {
mySelectionStartPoint = panelToCharCoords(e.getPoint());
mySelection = null;
repaint();
}
}
}
@Override
public void mouseReleased(final MouseEvent e) {
requestFocusInWindow();
repaint();
}
@Override
public void mouseClicked(final MouseEvent e) {
requestFocusInWindow();
if (e.getButton() == MouseEvent.BUTTON1) {
int count = e.getClickCount();
if (count == 1) {
// do nothing
}
else if (count == 2) {
// select word
final Point charCoords = panelToCharCoords(e.getPoint());
Point start = SelectionUtil.getPreviousSeparator(charCoords, myBackBuffer);
Point stop = SelectionUtil.getNextSeparator(charCoords, myBackBuffer);
mySelection = new TerminalSelection(start);
mySelection.updateEnd(stop);
if (mySettingsProvider.copyOnSelect()) {
handleCopy(false);
}
}
else if (count == 3) {
// select line
final Point charCoords = panelToCharCoords(e.getPoint());
int startLine = charCoords.y;
while (startLine > -getScrollBuffer().getLineCount()
&& myBackBuffer.getLine(startLine - 1).isWrapped()) {
startLine--;
}
int endLine = charCoords.y;
while (endLine < myBackBuffer.getHeight()
&& myBackBuffer.getLine(endLine).isWrapped()) {
endLine++;
}
mySelection = new TerminalSelection(new Point(0, startLine));
mySelection.updateEnd(new Point(myTermSize.width, endLine));
if (mySettingsProvider.copyOnSelect()) {
handleCopy(false);
}
}
}
else if (e.getButton() == MouseEvent.BUTTON2 && mySettingsProvider.pasteOnMiddleMouseClick()) {
handlePaste();
}
else if (e.getButton() == MouseEvent.BUTTON3) {
JPopupMenu popup = createPopupMenu();
popup.show(e.getComponent(), e.getX(), e.getY());
}
repaint();
}
});
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent e) {
myLastResize = System.currentTimeMillis();
sizeTerminalFromComponent();
}
});
myBoundedRangeModel.addChangeListener(new ChangeListener() {
public void stateChanged(final ChangeEvent e) {
newClientScrollOrigin = myBoundedRangeModel.getValue();
}
});
Timer redrawTimer = new Timer((int)(1000 / FPS), new WeakRedrawTimer(this));
setDoubleBuffered(true);
redrawTimer.start();
repaint();
}
protected boolean isRetina() {
return UIUtil.isRetina();
}
static class WeakRedrawTimer implements ActionListener {
private WeakReference<TerminalPanel> ref;
public WeakRedrawTimer(TerminalPanel terminalPanel) {
this.ref = new WeakReference<TerminalPanel>(terminalPanel);
}
@Override
public void actionPerformed(ActionEvent e) {
TerminalPanel terminalPanel = ref.get();
if (terminalPanel != null) {
try {
terminalPanel.redraw();
}
catch (Exception ex) {
LOG.error("Error while terminal panel redraw", ex);
}
}
else { // terminalPanel was garbage collected
Timer timer = (Timer)e.getSource();
timer.removeActionListener(this);
timer.stop();
}
}
}
private void scrollToBottom() {
myBoundedRangeModel.setValue(myTermSize.height);
}
private void moveScrollBar(int k) {
myBoundedRangeModel.setValue(myBoundedRangeModel.getValue() + k);
}
protected Font createFont() {
return mySettingsProvider.getTerminalFont();
}
protected Point panelToCharCoords(final Point p) {
int x = Math.min(p.x / myCharSize.width, getColumnCount() - 1);
x = Math.max(0, x);
int y = Math.min(p.y / myCharSize.height, getRowCount() - 1) + myClientScrollOrigin;
return new Point(x, y);
}
protected Point charToPanelCoords(final Point p) {
return new Point(p.x * myCharSize.width, (p.y - myClientScrollOrigin) * myCharSize.height);
}
void setUpClipboard() {
myClipboard = Toolkit.getDefaultToolkit().getSystemSelection();
if (myClipboard == null) {
myClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
}
}
protected void copySelection(final Point selectionStart, final Point selectionEnd) {
if (selectionStart == null || selectionEnd == null) {
return;
}
final String selectionText = SelectionUtil
.getSelectionText(selectionStart, selectionEnd, myBackBuffer);
if (selectionText.length() != 0) {
try {
setCopyContents(new StringSelection(selectionText));
}
catch (final IllegalStateException e) {
LOG.error("Could not set clipboard:", e);
}
}
}
protected void setCopyContents(StringSelection selection) {
myClipboard.setContents(selection, this);
}
protected void pasteSelection() {
final String selection = getClipboardString();
try {
myTerminalStarter.sendString(selection);
}
catch (RuntimeException e) {
LOG.info(e);
}
}
private String getClipboardString() {
try {
return getClipboardContent();
}
catch (final Exception e) {
LOG.info(e);
}
return null;
}
protected String getClipboardContent() throws IOException, UnsupportedFlavorException {
try {
return (String)myClipboard.getData(DataFlavor.stringFlavor);
}
catch (Exception e) {
LOG.info(e);
return null;
}
}
/* Do not care
*/
public void lostOwnership(final Clipboard clipboard, final Transferable contents) {
}
private void setupImages() {
final BufferedImage oldImage = myImage;
int width = getPixelWidth();
int height = getPixelHeight();
if (width > 0 && height > 0) {
Pair<BufferedImage, Graphics2D> imageAndGfx = createAndInitImage(width, height);
myImage = imageAndGfx.first;
myGfx = imageAndGfx.second;
imageAndGfx = createAndInitImage(width, height);
myImageForSelection = imageAndGfx.first;
myGfxForSelection = imageAndGfx.second;
imageAndGfx = createAndInitImage(width, height);
myImageForCursor = imageAndGfx.first;
myGfxForCursor = imageAndGfx.second;
if (oldImage != null) {
drawImage(myGfx, oldImage);
}
}
}
private void drawImage(Graphics2D gfx, BufferedImage image) {
drawImage(gfx, image, 0, 0, myTerminalPanel);
}
protected void drawImage(Graphics2D gfx, BufferedImage image, int x, int y, ImageObserver observer) {
gfx.drawImage(image, x, y,
image.getWidth(), image.getHeight(), observer);
}
private Pair<BufferedImage, Graphics2D> createAndInitImage(int width, int height) {
BufferedImage image = createBufferedImage(width, height);
Graphics2D gfx = image.createGraphics();
setupAntialiasing(gfx);
gfx.setColor(getBackground());
gfx.fillRect(0, 0, width, height);
return Pair.create(image, gfx);
}
protected BufferedImage createBufferedImage(int width, int height) {
return new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
}
private void sizeTerminalFromComponent() {
if (myTerminalStarter != null) {
final int newWidth = getWidth() / myCharSize.width;
final int newHeight = getHeight() / myCharSize.height;
if (newHeight > 0 && newWidth > 0) {
final Dimension newSize = new Dimension(newWidth, newHeight);
myTerminalStarter.postResize(newSize, RequestOrigin.User);
}
}
}
public void setTerminalStarter(final TerminalStarter terminalStarter) {
myTerminalStarter = terminalStarter;
sizeTerminalFromComponent();
}
public void setKeyListener(final KeyListener keyListener) {
this.myKeyListener = keyListener;
}
public Dimension requestResize(final Dimension newSize,
final RequestOrigin origin,
int cursorY,
JediTerminal.ResizeHandler resizeHandler) {
if (!newSize.equals(myTermSize)) {
myBackBuffer.lock();
try {
myBackBuffer.resize(newSize, origin, cursorY, resizeHandler, mySelection);
myTermSize = (Dimension)newSize.clone();
// resize images..
setupImages();
final Dimension pixelDimension = new Dimension(getPixelWidth(), getPixelHeight());
setPreferredSize(pixelDimension);
if (myTerminalPanelListener != null) {
myTerminalPanelListener.onPanelResize(pixelDimension, origin);
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateScrolling();
}
});
}
finally {
myBackBuffer.unlock();
}
}
return new Dimension(getPixelWidth(), getPixelHeight());
}
public void setTerminalPanelListener(final TerminalPanelListener resizeDelegate) {
myTerminalPanelListener = resizeDelegate;
}
private void establishFontMetrics() {
final BufferedImage img = createBufferedImage(1, 1);
final Graphics2D graphics = img.createGraphics();
graphics.setFont(myNormalFont);
final float lineSpace = mySettingsProvider.getLineSpace();
final FontMetrics fo = graphics.getFontMetrics();
myDescent = fo.getDescent();
myCharSize.width = fo.charWidth('W');
myCharSize.height = fo.getHeight() + (int)(lineSpace * 2);
myDescent += lineSpace;
myMonospaced = isMonospaced(fo);
if (!myMonospaced) {
LOG.info("WARNING: Font " + myNormalFont.getName() + " is non-monospaced");
}
img.flush();
graphics.dispose();
}
private static boolean isMonospaced(FontMetrics fontMetrics) {
boolean isMonospaced = true;
int charWidth = -1;
for (int codePoint = 0; codePoint < 128; codePoint++) {
if (Character.isValidCodePoint(codePoint)) {
char character = (char)codePoint;
if (isWordCharacter(character)) {
int w = fontMetrics.charWidth(character);
if (charWidth != -1) {
if (w != charWidth) {
isMonospaced = false;
break;
}
}
else {
charWidth = w;
}
}
}
}
return isMonospaced;
}
private static boolean isWordCharacter(char character) {
return Character.isLetterOrDigit(character);
}
protected void setupAntialiasing(Graphics graphics) {
if (graphics instanceof Graphics2D) {
Graphics2D myGfx = (Graphics2D)graphics;
final Object mode = mySettingsProvider.useAntialiasing() ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON
: RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;
final RenderingHints hints = new RenderingHints(
RenderingHints.KEY_TEXT_ANTIALIASING, mode);
myGfx.setRenderingHints(hints);
}
}
@Override
public Color getBackground() {
return getPalette().getColor(myStyleState.getBackground());
}
@Override
public Color getForeground() {
return getPalette().getColor(myStyleState.getForeground());
}
@Override
public void paintComponent(final Graphics g) {
Graphics2D gfx = (Graphics2D)g;
if (myImage != null) {
drawImage(gfx, myImage);
drawMargins(gfx, myImage.getWidth(), myImage.getHeight());
drawSelection(myImageForSelection, gfx);
if (mySettingsProvider.useInverseSelectionColor()) {
myCursor.drawCursor(gfx, myImageForSelection, myImage);
}
else {
myCursor.drawCursor(gfx, myImageForCursor, inSelection(myCursor.getCoordX(), myCursor.getCoordY()) ? myImageForSelection : myImage);
}
drawInputMethodUncommitedChars(gfx);
}
}
private void drawInputMethodUncommitedChars(Graphics2D gfx) {
if (myInputMethodUncommitedChars != null && myInputMethodUncommitedChars.length()>0) {
int x = myCursor.getCoordX() * myCharSize.width;
int y = (myCursor.getCoordY()) * myCharSize.height - 2;
int len = (myInputMethodUncommitedChars.length()) * myCharSize.width;
gfx.setColor(getBackground());
gfx.fillRect(x, (myCursor.getCoordY()-1)*myCharSize.height, len, myCharSize.height);
gfx.setColor(getForeground());
gfx.setFont(myNormalFont);
gfx.drawString(myInputMethodUncommitedChars, x, y);
Stroke saved = gfx.getStroke();
BasicStroke dotted = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[]{0, 2, 0, 2}, 0);
gfx.setStroke(dotted);
gfx.drawLine(x, y, x + len, y);
gfx.setStroke(saved);
}
}
private boolean inSelection(int x, int y) {
return mySelection != null && mySelection.contains(new Point(x, y));
}
@Override
public void processKeyEvent(final KeyEvent e) {
handleKeyEvent(e);
e.consume();
}
public void handleKeyEvent(KeyEvent e) {
final int id = e.getID();
if (id == KeyEvent.KEY_PRESSED) {
myKeyListener.keyPressed(e);
}
else if (id == KeyEvent.KEY_RELEASED) {
/* keyReleased(e); */
}
else if (id == KeyEvent.KEY_TYPED) {
myKeyListener.keyTyped(e);
}
}
public int getPixelWidth() {
return myCharSize.width * myTermSize.width;
}
public int getPixelHeight() {
return myCharSize.height * myTermSize.height;
}
public int getColumnCount() {
return myTermSize.width;
}
public int getRowCount() {
return myTermSize.height;
}
public String getWindowTitle() {
return myWindowTitle;
}
public void addTerminalMouseListener(final TerminalMouseListener listener) {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (mySettingsProvider.enableMouseReporting()) {
Point p = panelToCharCoords(e.getPoint());
listener.mousePressed(p.x, p.y, e);
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (mySettingsProvider.enableMouseReporting()) {
Point p = panelToCharCoords(e.getPoint());
listener.mouseReleased(p.x, p.y, e);
}
}
});
}
public void initKeyHandler() {
setKeyListener(new TerminalKeyHandler());
}
public class TerminalCursor {
private boolean myCursorHasChanged;
protected Point myCursorCoordinates = new Point();
private boolean myShouldDrawCursor = true;
private boolean myBlinking = true;
private boolean calculateIsCursorShown(long currentTime) {
if (!isBlinking()) {
return true;
}
if (myCursorHasChanged) {
return true;
}
if (cursorShouldChangeBlinkState(currentTime)) {
return !myCursorIsShown;
}
else {
return myCursorIsShown;
}
}
private boolean cursorShouldChangeBlinkState(long currentTime) {
return currentTime - myLastCursorChange > mySettingsProvider.caretBlinkingMs();
}
public void drawCursor(Graphics2D g, BufferedImage imageForCursor, BufferedImage normalImage) {
if (needsRepaint()) {
final int y = getCoordY();
final int x = getCoordX();
if (y >= 0 && y < myTermSize.height) {
boolean isCursorShown = calculateIsCursorShown(System.currentTimeMillis());
BufferedImage imageToDraw;
if (isCursorShown) {
imageToDraw = imageForCursor;
}
else {
imageToDraw = normalImage;
}
drawImage(g, imageToDraw, x * myCharSize.width, y * myCharSize.height,
(x + 1) * myCharSize.width, (y + 1) * myCharSize.height);
myCursorIsShown = isCursorShown;
myLastCursorChange = System.currentTimeMillis();
myCursorHasChanged = false;
}
}
}
public boolean needsRepaint() {
long currentTime = System.currentTimeMillis();
return isShouldDrawCursor() &&
isFocusOwner() &&
noRecentResize(currentTime) &&
(myCursorHasChanged || cursorShouldChangeBlinkState(currentTime));
}
public void setX(int x) {
myCursorCoordinates.x = x;
myCursorHasChanged = true;
}
public void setY(int y) {
myCursorCoordinates.y = y;
myCursorHasChanged = true;
}
public int getCoordX() {
return myCursorCoordinates.x;
}
public int getCoordY() {
return myCursorCoordinates.y - 1 - myClientScrollOrigin;
}
public void setShouldDrawCursor(boolean shouldDrawCursor) {
myShouldDrawCursor = shouldDrawCursor;
}
public boolean isShouldDrawCursor() {
return myShouldDrawCursor;
}
private boolean noRecentResize(long time) {
return time - myLastResize > mySettingsProvider.caretBlinkingMs();
}
public void setBlinking(boolean blinking) {
myBlinking = blinking;
}
public boolean isBlinking() {
return myBlinking && (mySettingsProvider.caretBlinkingMs() > 0);
}
}
public void drawSelection(BufferedImage imageForSelection, Graphics2D g) {
/* which is the top one */
if (mySelection == null) {
return;
}
Pair<Point, Point> points = mySelection.pointsForRun(myTermSize.width);
Point start = points.first;
Point end = points.second;
if (start.y == end.y) { /* same line */
if (start.x == end.x) {
return;
}
copyImage(g, imageForSelection, start.x * myCharSize.width, (start.y - myClientScrollOrigin) * myCharSize.height,
(end.x - start.x) * myCharSize.width, myCharSize.height);
}
else {
/* to end of first line */
copyImage(g, imageForSelection, start.x * myCharSize.width, (start.y - myClientScrollOrigin) * myCharSize.height,
(myTermSize.width - start.x) * myCharSize.width, myCharSize.height);
if (end.y - start.y > 1) {
/* intermediate lines */
int startInScreen = start.y + 1 - myClientScrollOrigin;
int heightInScreen = end.y - start.y - 1;
if (startInScreen < 0) {
heightInScreen += startInScreen;
startInScreen = 0;
}
heightInScreen = Math.min(myTermSize.height - startInScreen, heightInScreen);
copyImage(g, imageForSelection, 0, startInScreen * myCharSize.height,
myTermSize.width * myCharSize.width, heightInScreen
* myCharSize.height);
}
/* from beginning of last line */
copyImage(g, imageForSelection, 0, (end.y - myClientScrollOrigin) * myCharSize.height, end.x
* myCharSize.width, myCharSize.height);
}
}
private void drawImage(Graphics2D g, BufferedImage image, int x1, int y1, int x2, int y2) {
drawImage(g, image, x1, y1, x2, y2, x1, y1, x2, y2);
}
protected void drawImage(Graphics2D g, BufferedImage image, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2) {
g.drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null);
}
private void copyImage(Graphics2D g, BufferedImage image, int x, int y, int width, int height) {
drawImage(g, image, x, y, x + width, y + height, x, y, x + width, y + height);
}
@Override
public void consume(int x, int y, @NotNull TextStyle style, @NotNull CharBuffer buf, int startRow) {
if (myGfx != null) {
drawCharacters(x, y, style, buf, myGfx);
}
if (myGfxForSelection != null) {
TextStyle selectionStyle = style.clone();
if (mySettingsProvider.useInverseSelectionColor()) {
selectionStyle = getInversedStyle(style);
}
else {
TextStyle mySelectionStyle = mySettingsProvider.getSelectionColor();
selectionStyle.setBackground(mySelectionStyle.getBackground());
selectionStyle.setForeground(mySelectionStyle.getForeground());
}
drawCharacters(x, y, selectionStyle, buf, myGfxForSelection);
}
if (myGfxForCursor != null) {
TextStyle cursorStyle = getInversedStyle(style);
drawCharacters(x, y, cursorStyle, buf, myGfxForCursor);
}
}
private TextStyle getInversedStyle(TextStyle style) {
TextStyle selectionStyle;
selectionStyle = style.clone();
selectionStyle.setOption(Option.INVERSE, !selectionStyle.hasOption(Option.INVERSE));
if (selectionStyle.getForeground() == null) {
selectionStyle.setForeground(myStyleState.getForeground());
}
if (selectionStyle.getBackground() == null) {
selectionStyle.setBackground(myStyleState.getBackground());
}
return selectionStyle;
}
private void drawCharacters(int x, int y, TextStyle style, CharBuffer buf, Graphics2D gfx) {
gfx.setColor(getPalette().getColor(myStyleState.getBackground(style.getBackgroundForRun())));
int textLength = CharacterUtils.getTextLength(buf.getBuf(), buf.getStart(), buf.getLength());
gfx.fillRect(x * myCharSize.width,
(y - myClientScrollOrigin) * myCharSize.height,
textLength * myCharSize.width,
myCharSize.height);
drawChars(x, y, buf, style, gfx);
gfx.setClip(x * myCharSize.width,
(y - myClientScrollOrigin) * myCharSize.height,
textLength * myCharSize.width,
myCharSize.height);
gfx.setColor(getPalette().getColor(myStyleState.getForeground(style.getForegroundForRun())));
int baseLine = (y + 1 - myClientScrollOrigin) * myCharSize.height - myDescent;
if (style.hasOption(TextStyle.Option.UNDERLINED)) {
gfx.drawLine(x * myCharSize.width, baseLine + 1, (x + textLength) * myCharSize.width, baseLine + 1);
}
gfx.setClip(null);
}
/**
* Draw every char in separate terminal cell to guaranty equal width for different lines.
* Nevertheless to improve kerning we draw word characters as one block for monospaced fonts.
*/
private void drawChars(int x, int y, CharBuffer buf, TextStyle style, Graphics2D gfx) {
int newBlockLen = 1;
int offset = 0;
int drawCharsOffset = 0;
while (offset + newBlockLen <= buf.getLength()) {
Font font = getFontToDisplay(buf.charAt(offset + newBlockLen - 1), style);
while (myMonospaced && (offset + newBlockLen < buf.getLength()) && isWordCharacter(buf.charAt(offset + newBlockLen - 1))
&& (font == getFontToDisplay(buf.charAt(offset + newBlockLen - 1), style))) {
newBlockLen++;
}
gfx.setFont(font);
int descent = gfx.getFontMetrics(font).getDescent();
int baseLine = (y + 1 - myClientScrollOrigin) * myCharSize.height - descent;
int charWidth = gfx.getFontMetrics(font).charsWidth(buf.getBuf(), buf.getStart() + offset, newBlockLen);
int xCoord = (x + drawCharsOffset) * myCharSize.width;
gfx.setClip(xCoord,
(y - myClientScrollOrigin) * myCharSize.height,
charWidth,
myCharSize.height);
gfx.setColor(getPalette().getColor(myStyleState.getForeground(style.getForegroundForRun())));
gfx.drawChars(buf.getBuf(), buf.getStart() + offset, newBlockLen, xCoord, baseLine);
drawCharsOffset += CharacterUtils.getTextLength(buf.getBuf(), buf.getStart() + offset, newBlockLen);
offset += newBlockLen;
newBlockLen = 1;
}
}
protected Font getFontToDisplay(char c, TextStyle style) {
return style.hasOption(TextStyle.Option.BOLD) ? myBoldFont : myNormalFont;
}
private ColorPalette getPalette() {
return mySettingsProvider.getTerminalColorPalette();
}
private void clientScrollOriginChanged(int oldOrigin) {
int dy = myClientScrollOrigin - oldOrigin;
int dyPix = dy * myCharSize.height;
copyAndClearAreaOnScroll(dyPix, myGfx, myImage);
copyAndClearAreaOnScroll(dyPix, myGfxForSelection, myImageForSelection);
copyAndClearAreaOnScroll(dyPix, myGfxForCursor, myImageForCursor);
if (dy < 0) {
// Scrolling up; Copied down
// New area at the top to be filled in - can only be from scroll buffer
//
myBackBuffer.getScrollBuffer().processLines(myClientScrollOrigin, -dy, this);
}
else {
// Scrolling down; Copied up
// New area at the bottom to be filled - can be from both
int oldEnd = oldOrigin + myTermSize.height;
// Either its the whole amount above the back buffer + some more
// Or its the whole amount we moved
// Or we are already out of the scroll buffer
int portionInScroll = oldEnd < 0 ? Math.min(-oldEnd, dy) : 0;
int portionInBackBuffer = dy - portionInScroll;
if (portionInScroll > 0) {
myBackBuffer.getScrollBuffer().processLines(oldEnd, portionInScroll, this);
}
if (portionInBackBuffer > 0) {
myBackBuffer.processBufferRows(oldEnd + portionInScroll, portionInBackBuffer, this);
}
}
}
private void copyAndClearAreaOnScroll(int dy, Graphics2D gfx, BufferedImage image) {
if (getPixelHeight() > Math.abs(dy)) {
copyArea(gfx, image, 0, Math.max(0, dy),
getPixelWidth(), getPixelHeight() - Math.abs(dy),
0, -dy);
}
//clear rect before drawing scroll buffer on it
gfx.setColor(getBackground());
if (dy < 0) {
gfx.fillRect(0, 0, getPixelWidth(), Math.min(getPixelHeight(), Math.abs(dy)));
}
else {
gfx.fillRect(0, Math.max(getPixelHeight() - dy, 0), getPixelWidth(), Math.min(getPixelHeight(), dy));
}
}
private void copyArea(Graphics2D gfx, BufferedImage image, int x, int y, int width, int height, int dx, int dy) {
if (isRetina()) {
Pair<BufferedImage, Graphics2D> pair = createAndInitImage(x + width, y + height);
drawImage(pair.second, image,
x, y, x + width, y + height
);
drawImage(gfx, pair.first,
x + dx, y + dy, x + dx + width, y + dy + height, //destination
x, y, x + width, y + height //source
);
}
else {
gfx.copyArea(x, y, width, height, dx, dy);
}
}
int myNoDamage = 0;
int myFramesSkipped = 0;
public void redraw() {
if (tryRedrawDamagedPartFromBuffer() || myCursor.needsRepaint()) {
repaint();
}
}
/**
* This method tries to get a lock for back buffer. If it fails it increments skippedFrames counter and tries next time.
* After 5 attempts it locks buffer anyway.
*
* @return true if was successfully redrawn and there is anything to repaint
*/
private boolean tryRedrawDamagedPartFromBuffer() {
final int newOrigin = newClientScrollOrigin;
if (!myBackBuffer.tryLock()) {
if (myFramesSkipped >= 5) {
myBackBuffer.lock();
}
else {
myFramesSkipped++;
return false;
}
}
try {
myFramesSkipped = 0;
boolean serverScroll = pendingScrolls.enact(myGfx, myImage, getPixelWidth(), myCharSize.height);
boolean clientScroll = myClientScrollOrigin != newOrigin;
if (clientScroll) {
final int oldOrigin = myClientScrollOrigin;
myClientScrollOrigin = newOrigin;
clientScrollOriginChanged(oldOrigin);
}
boolean hasDamage = myBackBuffer.hasDamage();
if (hasDamage) {
myNoDamage = 0;
myBackBuffer.processDamagedCells(this);
myBackBuffer.resetDamage();
}
else {
myNoDamage++;
}
return serverScroll || clientScroll || hasDamage;
}
finally {
myBackBuffer.unlock();
}
}
private void drawMargins(Graphics2D gfx, int width, int height) {
gfx.setColor(getBackground());
gfx.fillRect(0, height, getWidth(), getHeight() - height);
gfx.fillRect(width, 0, getWidth() - width, getHeight());
}
public void scrollArea(final int scrollRegionTop, final int scrollRegionSize, int dy) {
if (dy < 0) {
//Moving lines off the top of the screen
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateScrolling();
}
});
}
mySelection = null;
pendingScrolls.add(scrollRegionTop, scrollRegionSize, dy);
}
private void updateScrolling() {
if (myScrollingEnabled) {
myBoundedRangeModel
.setRangeProperties(0, myTermSize.height, -myBackBuffer.getScrollBuffer().getLineCount(), myTermSize.height, false);
}
else {
myBoundedRangeModel.setRangeProperties(0, myTermSize.height, 0, myTermSize.height, false);
}
}
private class PendingScrolls {
int[] ys = new int[10];
int[] hs = new int[10];
int[] dys = new int[10];
int scrollCount = -1;
void ensureArrays(int index) {
int curLen = ys.length;
if (index >= curLen) {
ys = Util.copyOf(ys, curLen * 2);
hs = Util.copyOf(hs, curLen * 2);
dys = Util.copyOf(dys, curLen * 2);
}
}
void add(int y, int h, int dy) {
if (dy == 0) return;
if (scrollCount >= 0 &&
y == ys[scrollCount] &&
h == hs[scrollCount]) {
dys[scrollCount] += dy;
}
else {
scrollCount++;
ensureArrays(scrollCount);
ys[scrollCount] = y;
hs[scrollCount] = h;
dys[scrollCount] = dy;
}
}
boolean enact(Graphics2D gfx, BufferedImage image, int width, int charHeight) {
if (scrollCount < 0) return false;
for (int i = 0; i <= scrollCount; i++) {
if (dys[i] == 0 || Math.abs(dys[i]) >= hs[i]) { // nothing to do
continue;
}
if (dys[i] > 0) {
copyArea(gfx, image, 0, (ys[i] - 1) * charHeight, width, (hs[i] - dys[i]) * charHeight, 0, dys[i] * charHeight);
}
else {
copyArea(gfx, image, 0, (ys[i] - dys[i] - 1) * charHeight, width, (hs[i] + dys[i]) * charHeight, 0, dys[i] * charHeight);
}
}
scrollCount = -1;
return true;
}
}
final PendingScrolls pendingScrolls = new PendingScrolls();
public void setCursor(final int x, final int y) {
myCursor.setX(x);
myCursor.setY(y);
}
public void beep() {
if (mySettingsProvider.audibleBell()) {
Toolkit.getDefaultToolkit().beep();
}
}
public BoundedRangeModel getBoundedRangeModel() {
return myBoundedRangeModel;
}
public BackBuffer getBackBuffer() {
return myBackBuffer;
}
public TerminalSelection getSelection() {
return mySelection;
}
public LinesBuffer getScrollBuffer() {
return myBackBuffer.getScrollBuffer();
}
public void lock() {
myBackBuffer.lock();
}
public void unlock() {
myBackBuffer.unlock();
}
@Override
public void setCursorVisible(boolean shouldDrawCursor) {
myCursor.setShouldDrawCursor(shouldDrawCursor);
}
protected JPopupMenu createPopupMenu() {
JPopupMenu popup = new JPopupMenu();
TerminalAction.addToMenu(popup, this);
return popup;
}
public void setScrollingEnabled(boolean scrollingEnabled) {
myScrollingEnabled = scrollingEnabled;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateScrolling();
}
});
}
@Override
public void setBlinkingCursor(boolean enabled) {
myCursor.setBlinking(enabled);
}
public TerminalCursor getTerminalCursor() {
return myCursor;
}
public TerminalOutputStream getTerminalOutputStream() {
return myTerminalStarter;
}
@Override
public void setWindowTitle(String name) {
myWindowTitle = name;
if (myTerminalPanelListener != null) {
myTerminalPanelListener.onTitleChanged(myWindowTitle);
}
}
@Override
public List<TerminalAction> getActions() {
return Lists.newArrayList(
new TerminalAction("Copy", mySettingsProvider.getCopyKeyStrokes(), new Predicate<KeyEvent>() {
@Override
public boolean apply(KeyEvent input) {
return handleCopy(true);
}
}).withMnemonicKey(KeyEvent.VK_C).withEnabledSupplier(new Supplier<Boolean>() {
@Override
public Boolean get() {
return mySelection != null;
}
}),
new TerminalAction("Paste", mySettingsProvider.getPasteKeyStrokes(), new Predicate<KeyEvent>() {
@Override
public boolean apply(KeyEvent input) {
handlePaste();
return true;
}
}).withMnemonicKey(KeyEvent.VK_P).withEnabledSupplier(new Supplier<Boolean>() {
@Override
public Boolean get() {
return getClipboardString() != null;
}
}));
}
@Override
public TerminalActionProvider getNextProvider() {
return myNextActionProvider;
}
@Override
public void setNextProvider(TerminalActionProvider provider) {
myNextActionProvider = provider;
}
private void processTerminalKeyPressed(KeyEvent e) {
try {
final int keycode = e.getKeyCode();
final char keychar = e.getKeyChar();
// numLock does not change the code sent by keypad VK_DELETE
// although it send the char '.'
if (keycode == KeyEvent.VK_DELETE && keychar == '.') {
myTerminalStarter.sendBytes(new byte[]{'.'});
return;
}
// CTRL + Space is not handled in KeyEvent; handle it manually
else if (keychar == ' ' && (e.getModifiers() & KeyEvent.CTRL_MASK) != 0) {
myTerminalStarter.sendBytes(new byte[]{Ascii.NUL});
return;
}
final byte[] code = myTerminalStarter.getCode(keycode);
if (code != null) {
myTerminalStarter.sendBytes(code);
}
else if ((keychar & 0xff00) == 0) {
final byte[] obuffer = new byte[1];
obuffer[0] = (byte)keychar;
myTerminalStarter.sendBytes(obuffer);
if (mySettingsProvider.scrollToBottomOnTyping()) {
scrollToBottom();
}
}
}
catch (final Exception ex) {
LOG.error("Error sending key to emulator", ex);
}
}
private void processTerminalKeyTyped(KeyEvent e) {
final char keychar = e.getKeyChar();
if ((keychar & 0xff00) != 0) {
final char[] foo = new char[1];
foo[0] = keychar;
try {
myTerminalStarter.sendString(new String(foo));
if (mySettingsProvider.scrollToBottomOnTyping()) {
scrollToBottom();
}
}
catch (final RuntimeException ex) {
LOG.error("Error sending key to emulator", ex);
}
}
}
public class TerminalKeyHandler implements KeyListener {
public TerminalKeyHandler() {
}
public void keyPressed(final KeyEvent e) {
if (!TerminalAction.processEvent(TerminalPanel.this, e)) {
processTerminalKeyPressed(e);
}
}
public void keyTyped(final KeyEvent e) {
processTerminalKeyTyped(e);
}
//Ignore releases
public void keyReleased(KeyEvent e) {
}
}
private void handlePaste() {
pasteSelection();
}
// "unselect" is needed to handle Ctrl+C copy shortcut collision with ^C signal shortcut
private boolean handleCopy(boolean unselect) {
if (mySelection != null) {
Pair<Point, Point> points = mySelection.pointsForRun(myTermSize.width);
copySelection(points.first, points.second);
if (unselect) {
mySelection = null;
repaint();
}
return true;
}
return false;
}
/**
* InputMethod implementation
* For details read http://docs.oracle.com/javase/7/docs/technotes/guides/imf/api-tutorial.html
*/
@Override
protected void processInputMethodEvent(InputMethodEvent e) {
int commitCount = e.getCommittedCharacterCount();
if (commitCount > 0) {
myInputMethodUncommitedChars = null;
AttributedCharacterIterator text = e.getText();
if (text != null) {
//noinspection ForLoopThatDoesntUseLoopVariable
for (char c = text.first(); commitCount > 0; c = text.next(), commitCount--) {
if (c >= 0x20 && c != 0x7F) { // Hack just like in javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction
int id = (c & 0xff00) == 0 ? KeyEvent.KEY_PRESSED : KeyEvent.KEY_TYPED;
handleKeyEvent(new KeyEvent(this, id, e.getWhen(), 0, 0, c));
}
}
}
}
else {
myInputMethodUncommitedChars = uncommitedChars(e.getText());
}
}
private static String uncommitedChars(AttributedCharacterIterator text) {
StringBuilder sb = new StringBuilder();
for (char c = text.first(); c != CharacterIterator.DONE; c = text.next()) {
if (c >= 0x20 && c != 0x7F) { // Hack just like in javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction
sb.append(c);
}
}
return sb.toString();
}
@Override
public InputMethodRequests getInputMethodRequests() {
return new MyInputMethodRequests();
}
private class MyInputMethodRequests implements InputMethodRequests {
@Override
public Rectangle getTextLocation(TextHitInfo offset) {
Rectangle r = new Rectangle(myCursor.getCoordX() * myCharSize.width, (myCursor.getCoordY() + 1) * myCharSize.height,
0, 0);
Point p = TerminalPanel.this.getLocationOnScreen();
r.translate(p.x, p.y);
return r;
}
@Nullable
@Override
public TextHitInfo getLocationOffset(int x, int y) {
return null;
}
@Override
public int getInsertPositionOffset() {
return 0;
}
@Override
public AttributedCharacterIterator getCommittedText(int beginIndex, int endIndex, AttributedCharacterIterator.Attribute[] attributes) {
return null;
}
@Override
public int getCommittedTextLength() {
return 0;
}
@Nullable
@Override
public AttributedCharacterIterator cancelLatestCommittedText(AttributedCharacterIterator.Attribute[] attributes) {
return null;
}
@Nullable
@Override
public AttributedCharacterIterator getSelectedText(AttributedCharacterIterator.Attribute[] attributes) {
return null;
}
}
}
|
src-terminal/com/jediterm/terminal/ui/TerminalPanel.java
|
package com.jediterm.terminal.ui;
import com.google.common.base.Ascii;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Lists;
import com.jediterm.terminal.*;
import com.jediterm.terminal.TextStyle.Option;
import com.jediterm.terminal.display.*;
import com.jediterm.terminal.emulator.ColorPalette;
import com.jediterm.terminal.emulator.mouse.TerminalMouseListener;
import com.jediterm.terminal.ui.settings.SettingsProvider;
import com.jediterm.terminal.util.Pair;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.font.TextHitInfo;
import java.awt.im.InputMethodRequests;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.AttributedCharacterIterator;
import java.text.CharacterIterator;
import java.util.List;
public class TerminalPanel extends JComponent implements TerminalDisplay, ClipboardOwner, StyledTextConsumer, TerminalActionProvider {
private static final Logger LOG = Logger.getLogger(TerminalPanel.class);
private static final long serialVersionUID = -1048763516632093014L;
private static final double FPS = 50;
public static final double SCROLL_SPEED = 0.05;
/*images*/
private BufferedImage myImage;
protected Graphics2D myGfx;
private BufferedImage myImageForSelection;
private Graphics2D myGfxForSelection;
private BufferedImage myImageForCursor;
private Graphics2D myGfxForCursor;
private final Component myTerminalPanel = this;
/*font related*/
private Font myNormalFont;
private Font myBoldFont;
private int myDescent = 0;
protected Dimension myCharSize = new Dimension();
private boolean myMonospaced;
protected Dimension myTermSize = new Dimension(80, 24);
private TerminalStarter myTerminalStarter = null;
private Point mySelectionStartPoint = null;
private TerminalSelection mySelection = null;
private Clipboard myClipboard;
private TerminalPanelListener myTerminalPanelListener;
private SettingsProvider mySettingsProvider;
final private BackBuffer myBackBuffer;
final private StyleState myStyleState;
/*scroll and cursor*/
final private TerminalCursor myCursor = new TerminalCursor();
private final BoundedRangeModel myBoundedRangeModel = new DefaultBoundedRangeModel(0, 80, 0, 80);
protected int myClientScrollOrigin;
protected int newClientScrollOrigin;
protected KeyListener myKeyListener;
private long myLastCursorChange;
private boolean myCursorIsShown;
private long myLastResize;
private boolean myScrollingEnabled = true;
private String myWindowTitle = "Terminal";
private TerminalActionProvider myNextActionProvider;
private String myInputMethodUncommitedChars;
public TerminalPanel(@NotNull SettingsProvider settingsProvider, @NotNull BackBuffer backBuffer, @NotNull StyleState styleState) {
mySettingsProvider = settingsProvider;
myBackBuffer = backBuffer;
myStyleState = styleState;
myTermSize.width = backBuffer.getWidth();
myTermSize.height = backBuffer.getHeight();
updateScrolling();
enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.INPUT_METHOD_EVENT_MASK);
enableInputMethods(true);
}
public void init() {
myNormalFont = createFont();
myBoldFont = myNormalFont.deriveFont(Font.BOLD);
establishFontMetrics();
setupImages();
setUpClipboard();
setPreferredSize(new Dimension(getPixelWidth(), getPixelHeight()));
setFocusable(true);
enableInputMethods(true);
setFocusTraversalKeysEnabled(false);
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(final MouseEvent e) {
final Point charCoords = panelToCharCoords(e.getPoint());
if (mySelection == null) {
// prevent unlikely case where drag started outside terminal panel
if (mySelectionStartPoint == null) {
mySelectionStartPoint = charCoords;
}
mySelection = new TerminalSelection(new Point(mySelectionStartPoint));
}
repaint();
mySelection.updateEnd(charCoords);
if (mySettingsProvider.copyOnSelect()) {
handleCopy(false);
}
if (e.getPoint().y < 0) {
moveScrollBar((int)((e.getPoint().y) * SCROLL_SPEED));
}
if (e.getPoint().y > getPixelHeight()) {
moveScrollBar((int)((e.getPoint().y - getPixelHeight()) * SCROLL_SPEED));
}
}
});
addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
int notches = e.getWheelRotation();
moveScrollBar(notches);
}
});
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
if (e.getClickCount() == 1) {
mySelectionStartPoint = panelToCharCoords(e.getPoint());
mySelection = null;
repaint();
}
}
}
@Override
public void mouseReleased(final MouseEvent e) {
requestFocusInWindow();
repaint();
}
@Override
public void mouseClicked(final MouseEvent e) {
requestFocusInWindow();
if (e.getButton() == MouseEvent.BUTTON1) {
int count = e.getClickCount();
if (count == 1) {
// do nothing
}
else if (count == 2) {
// select word
final Point charCoords = panelToCharCoords(e.getPoint());
Point start = SelectionUtil.getPreviousSeparator(charCoords, myBackBuffer);
Point stop = SelectionUtil.getNextSeparator(charCoords, myBackBuffer);
mySelection = new TerminalSelection(start);
mySelection.updateEnd(stop);
if (mySettingsProvider.copyOnSelect()) {
handleCopy(false);
}
}
else if (count == 3) {
// select line
final Point charCoords = panelToCharCoords(e.getPoint());
int startLine = charCoords.y;
while (startLine > -getScrollBuffer().getLineCount()
&& myBackBuffer.getLine(startLine - 1).isWrapped()) {
startLine--;
}
int endLine = charCoords.y;
while (endLine < myBackBuffer.getHeight()
&& myBackBuffer.getLine(endLine).isWrapped()) {
endLine++;
}
mySelection = new TerminalSelection(new Point(0, startLine));
mySelection.updateEnd(new Point(myTermSize.width, endLine));
if (mySettingsProvider.copyOnSelect()) {
handleCopy(false);
}
}
}
else if (e.getButton() == MouseEvent.BUTTON2 && mySettingsProvider.pasteOnMiddleMouseClick()) {
handlePaste();
}
else if (e.getButton() == MouseEvent.BUTTON3) {
JPopupMenu popup = createPopupMenu();
popup.show(e.getComponent(), e.getX(), e.getY());
}
repaint();
}
});
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent e) {
myLastResize = System.currentTimeMillis();
sizeTerminalFromComponent();
}
});
myBoundedRangeModel.addChangeListener(new ChangeListener() {
public void stateChanged(final ChangeEvent e) {
newClientScrollOrigin = myBoundedRangeModel.getValue();
}
});
Timer redrawTimer = new Timer((int)(1000 / FPS), new WeakRedrawTimer(this));
setDoubleBuffered(true);
redrawTimer.start();
repaint();
}
protected boolean isRetina() {
return UIUtil.isRetina();
}
static class WeakRedrawTimer implements ActionListener {
private WeakReference<TerminalPanel> ref;
public WeakRedrawTimer(TerminalPanel terminalPanel) {
this.ref = new WeakReference<TerminalPanel>(terminalPanel);
}
@Override
public void actionPerformed(ActionEvent e) {
TerminalPanel terminalPanel = ref.get();
if (terminalPanel != null) {
try {
terminalPanel.redraw();
}
catch (Exception ex) {
LOG.error("Error while terminal panel redraw", ex);
}
}
else { // terminalPanel was garbage collected
Timer timer = (Timer)e.getSource();
timer.removeActionListener(this);
timer.stop();
}
}
}
private void scrollToBottom() {
myBoundedRangeModel.setValue(myTermSize.height);
}
private void moveScrollBar(int k) {
myBoundedRangeModel.setValue(myBoundedRangeModel.getValue() + k);
}
protected Font createFont() {
return mySettingsProvider.getTerminalFont();
}
protected Point panelToCharCoords(final Point p) {
int x = Math.min(p.x / myCharSize.width, getColumnCount() - 1);
x = Math.max(0, x);
int y = Math.min(p.y / myCharSize.height, getRowCount() - 1) + myClientScrollOrigin;
return new Point(x, y);
}
protected Point charToPanelCoords(final Point p) {
return new Point(p.x * myCharSize.width, (p.y - myClientScrollOrigin) * myCharSize.height);
}
void setUpClipboard() {
myClipboard = Toolkit.getDefaultToolkit().getSystemSelection();
if (myClipboard == null) {
myClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
}
}
protected void copySelection(final Point selectionStart, final Point selectionEnd) {
if (selectionStart == null || selectionEnd == null) {
return;
}
final String selectionText = SelectionUtil
.getSelectionText(selectionStart, selectionEnd, myBackBuffer);
if (selectionText.length() != 0) {
try {
setCopyContents(new StringSelection(selectionText));
}
catch (final IllegalStateException e) {
LOG.error("Could not set clipboard:", e);
}
}
}
protected void setCopyContents(StringSelection selection) {
myClipboard.setContents(selection, this);
}
protected void pasteSelection() {
final String selection = getClipboardString();
try {
myTerminalStarter.sendString(selection);
}
catch (RuntimeException e) {
LOG.info(e);
}
}
private String getClipboardString() {
try {
return getClipboardContent();
}
catch (final Exception e) {
LOG.info(e);
}
return null;
}
protected String getClipboardContent() throws IOException, UnsupportedFlavorException {
try {
return (String)myClipboard.getData(DataFlavor.stringFlavor);
}
catch (Exception e) {
LOG.info(e);
return null;
}
}
/* Do not care
*/
public void lostOwnership(final Clipboard clipboard, final Transferable contents) {
}
private void setupImages() {
final BufferedImage oldImage = myImage;
int width = getPixelWidth();
int height = getPixelHeight();
if (width > 0 && height > 0) {
Pair<BufferedImage, Graphics2D> imageAndGfx = createAndInitImage(width, height);
myImage = imageAndGfx.first;
myGfx = imageAndGfx.second;
imageAndGfx = createAndInitImage(width, height);
myImageForSelection = imageAndGfx.first;
myGfxForSelection = imageAndGfx.second;
imageAndGfx = createAndInitImage(width, height);
myImageForCursor = imageAndGfx.first;
myGfxForCursor = imageAndGfx.second;
if (oldImage != null) {
drawImage(myGfx, oldImage);
}
}
}
private void drawImage(Graphics2D gfx, BufferedImage image) {
drawImage(gfx, image, 0, 0, myTerminalPanel);
}
protected void drawImage(Graphics2D gfx, BufferedImage image, int x, int y, ImageObserver observer) {
gfx.drawImage(image, x, y,
image.getWidth(), image.getHeight(), observer);
}
private Pair<BufferedImage, Graphics2D> createAndInitImage(int width, int height) {
BufferedImage image = createBufferedImage(width, height);
Graphics2D gfx = image.createGraphics();
setupAntialiasing(gfx);
gfx.setColor(getBackground());
gfx.fillRect(0, 0, width, height);
return Pair.create(image, gfx);
}
protected BufferedImage createBufferedImage(int width, int height) {
return new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
}
private void sizeTerminalFromComponent() {
if (myTerminalStarter != null) {
final int newWidth = getWidth() / myCharSize.width;
final int newHeight = getHeight() / myCharSize.height;
if (newHeight > 0 && newWidth > 0) {
final Dimension newSize = new Dimension(newWidth, newHeight);
myTerminalStarter.postResize(newSize, RequestOrigin.User);
}
}
}
public void setTerminalStarter(final TerminalStarter terminalStarter) {
myTerminalStarter = terminalStarter;
sizeTerminalFromComponent();
}
public void setKeyListener(final KeyListener keyListener) {
this.myKeyListener = keyListener;
}
public Dimension requestResize(final Dimension newSize,
final RequestOrigin origin,
int cursorY,
JediTerminal.ResizeHandler resizeHandler) {
if (!newSize.equals(myTermSize)) {
myBackBuffer.lock();
try {
myBackBuffer.resize(newSize, origin, cursorY, resizeHandler, mySelection);
myTermSize = (Dimension)newSize.clone();
// resize images..
setupImages();
final Dimension pixelDimension = new Dimension(getPixelWidth(), getPixelHeight());
setPreferredSize(pixelDimension);
if (myTerminalPanelListener != null) {
myTerminalPanelListener.onPanelResize(pixelDimension, origin);
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateScrolling();
}
});
}
finally {
myBackBuffer.unlock();
}
}
return new Dimension(getPixelWidth(), getPixelHeight());
}
public void setTerminalPanelListener(final TerminalPanelListener resizeDelegate) {
myTerminalPanelListener = resizeDelegate;
}
private void establishFontMetrics() {
final BufferedImage img = createBufferedImage(1, 1);
final Graphics2D graphics = img.createGraphics();
graphics.setFont(myNormalFont);
final float lineSpace = mySettingsProvider.getLineSpace();
final FontMetrics fo = graphics.getFontMetrics();
myDescent = fo.getDescent();
myCharSize.width = fo.charWidth('W');
myCharSize.height = fo.getHeight() + (int)(lineSpace * 2);
myDescent += lineSpace;
myMonospaced = isMonospaced(fo);
if (!myMonospaced) {
LOG.info("WARNING: Font " + myNormalFont.getName() + " is non-monospaced");
}
img.flush();
graphics.dispose();
}
private static boolean isMonospaced(FontMetrics fontMetrics) {
boolean isMonospaced = true;
int charWidth = -1;
for (int codePoint = 0; codePoint < 128; codePoint++) {
if (Character.isValidCodePoint(codePoint)) {
char character = (char)codePoint;
if (isWordCharacter(character)) {
int w = fontMetrics.charWidth(character);
if (charWidth != -1) {
if (w != charWidth) {
isMonospaced = false;
break;
}
}
else {
charWidth = w;
}
}
}
}
return isMonospaced;
}
private static boolean isWordCharacter(char character) {
return Character.isLetterOrDigit(character);
}
protected void setupAntialiasing(Graphics graphics) {
if (graphics instanceof Graphics2D) {
Graphics2D myGfx = (Graphics2D)graphics;
final Object mode = mySettingsProvider.useAntialiasing() ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON
: RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;
final RenderingHints hints = new RenderingHints(
RenderingHints.KEY_TEXT_ANTIALIASING, mode);
myGfx.setRenderingHints(hints);
}
}
@Override
public Color getBackground() {
return getPalette().getColor(myStyleState.getBackground());
}
@Override
public Color getForeground() {
return getPalette().getColor(myStyleState.getForeground());
}
@Override
public void paintComponent(final Graphics g) {
Graphics2D gfx = (Graphics2D)g;
if (myImage != null) {
drawImage(gfx, myImage);
drawMargins(gfx, myImage.getWidth(), myImage.getHeight());
drawSelection(myImageForSelection, gfx);
if (mySettingsProvider.useInverseSelectionColor()) {
myCursor.drawCursor(gfx, myImageForSelection, myImage);
}
else {
myCursor.drawCursor(gfx, myImageForCursor, inSelection(myCursor.getCoordX(), myCursor.getCoordY()) ? myImageForSelection : myImage);
}
drawInputMethodUncommitedChars(gfx);
}
}
private void drawInputMethodUncommitedChars(Graphics2D gfx) {
if (myInputMethodUncommitedChars != null) {
gfx.setColor(getForeground());
gfx.setFont(myNormalFont);
int x = myCursor.getCoordX() * myCharSize.width;
int y = (myCursor.getCoordY()) * myCharSize.height - 2;
gfx.drawString(myInputMethodUncommitedChars, x, y);
Stroke saved = gfx.getStroke();
BasicStroke dotted = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[]{0, 2, 0, 2}, 0);
gfx.setStroke(dotted);
gfx.drawLine(x, y, x + (myInputMethodUncommitedChars.length()) * myCharSize.width, y);
gfx.setStroke(saved);
}
}
private boolean inSelection(int x, int y) {
return mySelection != null && mySelection.contains(new Point(x, y));
}
@Override
public void processKeyEvent(final KeyEvent e) {
handleKeyEvent(e);
e.consume();
}
public void handleKeyEvent(KeyEvent e) {
final int id = e.getID();
if (id == KeyEvent.KEY_PRESSED) {
myKeyListener.keyPressed(e);
}
else if (id == KeyEvent.KEY_RELEASED) {
/* keyReleased(e); */
}
else if (id == KeyEvent.KEY_TYPED) {
myKeyListener.keyTyped(e);
}
}
public int getPixelWidth() {
return myCharSize.width * myTermSize.width;
}
public int getPixelHeight() {
return myCharSize.height * myTermSize.height;
}
public int getColumnCount() {
return myTermSize.width;
}
public int getRowCount() {
return myTermSize.height;
}
public String getWindowTitle() {
return myWindowTitle;
}
public void addTerminalMouseListener(final TerminalMouseListener listener) {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (mySettingsProvider.enableMouseReporting()) {
Point p = panelToCharCoords(e.getPoint());
listener.mousePressed(p.x, p.y, e);
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (mySettingsProvider.enableMouseReporting()) {
Point p = panelToCharCoords(e.getPoint());
listener.mouseReleased(p.x, p.y, e);
}
}
});
}
public void initKeyHandler() {
setKeyListener(new TerminalKeyHandler());
}
public class TerminalCursor {
private boolean myCursorHasChanged;
protected Point myCursorCoordinates = new Point();
private boolean myShouldDrawCursor = true;
private boolean myBlinking = true;
private boolean calculateIsCursorShown(long currentTime) {
if (!isBlinking()) {
return true;
}
if (myCursorHasChanged) {
return true;
}
if (cursorShouldChangeBlinkState(currentTime)) {
return !myCursorIsShown;
}
else {
return myCursorIsShown;
}
}
private boolean cursorShouldChangeBlinkState(long currentTime) {
return currentTime - myLastCursorChange > mySettingsProvider.caretBlinkingMs();
}
public void drawCursor(Graphics2D g, BufferedImage imageForCursor, BufferedImage normalImage) {
if (needsRepaint()) {
final int y = getCoordY();
final int x = getCoordX();
if (y >= 0 && y < myTermSize.height) {
boolean isCursorShown = calculateIsCursorShown(System.currentTimeMillis());
BufferedImage imageToDraw;
if (isCursorShown) {
imageToDraw = imageForCursor;
}
else {
imageToDraw = normalImage;
}
drawImage(g, imageToDraw, x * myCharSize.width, y * myCharSize.height,
(x + 1) * myCharSize.width, (y + 1) * myCharSize.height);
myCursorIsShown = isCursorShown;
myLastCursorChange = System.currentTimeMillis();
myCursorHasChanged = false;
}
}
}
public boolean needsRepaint() {
long currentTime = System.currentTimeMillis();
return isShouldDrawCursor() &&
isFocusOwner() &&
noRecentResize(currentTime) &&
(myCursorHasChanged || cursorShouldChangeBlinkState(currentTime));
}
public void setX(int x) {
myCursorCoordinates.x = x;
myCursorHasChanged = true;
}
public void setY(int y) {
myCursorCoordinates.y = y;
myCursorHasChanged = true;
}
public int getCoordX() {
return myCursorCoordinates.x;
}
public int getCoordY() {
return myCursorCoordinates.y - 1 - myClientScrollOrigin;
}
public void setShouldDrawCursor(boolean shouldDrawCursor) {
myShouldDrawCursor = shouldDrawCursor;
}
public boolean isShouldDrawCursor() {
return myShouldDrawCursor;
}
private boolean noRecentResize(long time) {
return time - myLastResize > mySettingsProvider.caretBlinkingMs();
}
public void setBlinking(boolean blinking) {
myBlinking = blinking;
}
public boolean isBlinking() {
return myBlinking && (mySettingsProvider.caretBlinkingMs() > 0);
}
}
public void drawSelection(BufferedImage imageForSelection, Graphics2D g) {
/* which is the top one */
if (mySelection == null) {
return;
}
Pair<Point, Point> points = mySelection.pointsForRun(myTermSize.width);
Point start = points.first;
Point end = points.second;
if (start.y == end.y) { /* same line */
if (start.x == end.x) {
return;
}
copyImage(g, imageForSelection, start.x * myCharSize.width, (start.y - myClientScrollOrigin) * myCharSize.height,
(end.x - start.x) * myCharSize.width, myCharSize.height);
}
else {
/* to end of first line */
copyImage(g, imageForSelection, start.x * myCharSize.width, (start.y - myClientScrollOrigin) * myCharSize.height,
(myTermSize.width - start.x) * myCharSize.width, myCharSize.height);
if (end.y - start.y > 1) {
/* intermediate lines */
int startInScreen = start.y + 1 - myClientScrollOrigin;
int heightInScreen = end.y - start.y - 1;
if (startInScreen < 0) {
heightInScreen += startInScreen;
startInScreen = 0;
}
heightInScreen = Math.min(myTermSize.height - startInScreen, heightInScreen);
copyImage(g, imageForSelection, 0, startInScreen * myCharSize.height,
myTermSize.width * myCharSize.width, heightInScreen
* myCharSize.height);
}
/* from beginning of last line */
copyImage(g, imageForSelection, 0, (end.y - myClientScrollOrigin) * myCharSize.height, end.x
* myCharSize.width, myCharSize.height);
}
}
private void drawImage(Graphics2D g, BufferedImage image, int x1, int y1, int x2, int y2) {
drawImage(g, image, x1, y1, x2, y2, x1, y1, x2, y2);
}
protected void drawImage(Graphics2D g, BufferedImage image, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2) {
g.drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null);
}
private void copyImage(Graphics2D g, BufferedImage image, int x, int y, int width, int height) {
drawImage(g, image, x, y, x + width, y + height, x, y, x + width, y + height);
}
@Override
public void consume(int x, int y, @NotNull TextStyle style, @NotNull CharBuffer buf, int startRow) {
if (myGfx != null) {
drawCharacters(x, y, style, buf, myGfx);
}
if (myGfxForSelection != null) {
TextStyle selectionStyle = style.clone();
if (mySettingsProvider.useInverseSelectionColor()) {
selectionStyle = getInversedStyle(style);
}
else {
TextStyle mySelectionStyle = mySettingsProvider.getSelectionColor();
selectionStyle.setBackground(mySelectionStyle.getBackground());
selectionStyle.setForeground(mySelectionStyle.getForeground());
}
drawCharacters(x, y, selectionStyle, buf, myGfxForSelection);
}
if (myGfxForCursor != null) {
TextStyle cursorStyle = getInversedStyle(style);
drawCharacters(x, y, cursorStyle, buf, myGfxForCursor);
}
}
private TextStyle getInversedStyle(TextStyle style) {
TextStyle selectionStyle;
selectionStyle = style.clone();
selectionStyle.setOption(Option.INVERSE, !selectionStyle.hasOption(Option.INVERSE));
if (selectionStyle.getForeground() == null) {
selectionStyle.setForeground(myStyleState.getForeground());
}
if (selectionStyle.getBackground() == null) {
selectionStyle.setBackground(myStyleState.getBackground());
}
return selectionStyle;
}
private void drawCharacters(int x, int y, TextStyle style, CharBuffer buf, Graphics2D gfx) {
gfx.setColor(getPalette().getColor(myStyleState.getBackground(style.getBackgroundForRun())));
int textLength = CharacterUtils.getTextLength(buf.getBuf(), buf.getStart(), buf.getLength());
gfx.fillRect(x * myCharSize.width,
(y - myClientScrollOrigin) * myCharSize.height,
textLength * myCharSize.width,
myCharSize.height);
drawChars(x, y, buf, style, gfx);
gfx.setClip(x * myCharSize.width,
(y - myClientScrollOrigin) * myCharSize.height,
textLength * myCharSize.width,
myCharSize.height);
gfx.setColor(getPalette().getColor(myStyleState.getForeground(style.getForegroundForRun())));
int baseLine = (y + 1 - myClientScrollOrigin) * myCharSize.height - myDescent;
if (style.hasOption(TextStyle.Option.UNDERLINED)) {
gfx.drawLine(x * myCharSize.width, baseLine + 1, (x + textLength) * myCharSize.width, baseLine + 1);
}
gfx.setClip(null);
}
/**
* Draw every char in separate terminal cell to guaranty equal width for different lines.
* Nevertheless to improve kerning we draw word characters as one block for monospaced fonts.
*/
private void drawChars(int x, int y, CharBuffer buf, TextStyle style, Graphics2D gfx) {
int newBlockLen = 1;
int offset = 0;
int drawCharsOffset = 0;
while (offset + newBlockLen <= buf.getLength()) {
Font font = getFontToDisplay(buf.charAt(offset + newBlockLen - 1), style);
while (myMonospaced && (offset + newBlockLen < buf.getLength()) && isWordCharacter(buf.charAt(offset + newBlockLen - 1))
&& (font == getFontToDisplay(buf.charAt(offset + newBlockLen - 1), style))) {
newBlockLen++;
}
gfx.setFont(font);
int descent = gfx.getFontMetrics(font).getDescent();
int baseLine = (y + 1 - myClientScrollOrigin) * myCharSize.height - descent;
int charWidth = gfx.getFontMetrics(font).charsWidth(buf.getBuf(), buf.getStart() + offset, newBlockLen);
int xCoord = (x + drawCharsOffset) * myCharSize.width;
gfx.setClip(xCoord,
(y - myClientScrollOrigin) * myCharSize.height,
charWidth,
myCharSize.height);
gfx.setColor(getPalette().getColor(myStyleState.getForeground(style.getForegroundForRun())));
gfx.drawChars(buf.getBuf(), buf.getStart() + offset, newBlockLen, xCoord, baseLine);
drawCharsOffset += CharacterUtils.getTextLength(buf.getBuf(), buf.getStart() + offset, newBlockLen);
offset += newBlockLen;
newBlockLen = 1;
}
}
protected Font getFontToDisplay(char c, TextStyle style) {
return style.hasOption(TextStyle.Option.BOLD) ? myBoldFont : myNormalFont;
}
private ColorPalette getPalette() {
return mySettingsProvider.getTerminalColorPalette();
}
private void clientScrollOriginChanged(int oldOrigin) {
int dy = myClientScrollOrigin - oldOrigin;
int dyPix = dy * myCharSize.height;
copyAndClearAreaOnScroll(dyPix, myGfx, myImage);
copyAndClearAreaOnScroll(dyPix, myGfxForSelection, myImageForSelection);
copyAndClearAreaOnScroll(dyPix, myGfxForCursor, myImageForCursor);
if (dy < 0) {
// Scrolling up; Copied down
// New area at the top to be filled in - can only be from scroll buffer
//
myBackBuffer.getScrollBuffer().processLines(myClientScrollOrigin, -dy, this);
}
else {
// Scrolling down; Copied up
// New area at the bottom to be filled - can be from both
int oldEnd = oldOrigin + myTermSize.height;
// Either its the whole amount above the back buffer + some more
// Or its the whole amount we moved
// Or we are already out of the scroll buffer
int portionInScroll = oldEnd < 0 ? Math.min(-oldEnd, dy) : 0;
int portionInBackBuffer = dy - portionInScroll;
if (portionInScroll > 0) {
myBackBuffer.getScrollBuffer().processLines(oldEnd, portionInScroll, this);
}
if (portionInBackBuffer > 0) {
myBackBuffer.processBufferRows(oldEnd + portionInScroll, portionInBackBuffer, this);
}
}
}
private void copyAndClearAreaOnScroll(int dy, Graphics2D gfx, BufferedImage image) {
if (getPixelHeight() > Math.abs(dy)) {
copyArea(gfx, image, 0, Math.max(0, dy),
getPixelWidth(), getPixelHeight() - Math.abs(dy),
0, -dy);
}
//clear rect before drawing scroll buffer on it
gfx.setColor(getBackground());
if (dy < 0) {
gfx.fillRect(0, 0, getPixelWidth(), Math.min(getPixelHeight(), Math.abs(dy)));
}
else {
gfx.fillRect(0, Math.max(getPixelHeight() - dy, 0), getPixelWidth(), Math.min(getPixelHeight(), dy));
}
}
private void copyArea(Graphics2D gfx, BufferedImage image, int x, int y, int width, int height, int dx, int dy) {
if (isRetina()) {
Pair<BufferedImage, Graphics2D> pair = createAndInitImage(x + width, y + height);
drawImage(pair.second, image,
x, y, x + width, y + height
);
drawImage(gfx, pair.first,
x + dx, y + dy, x + dx + width, y + dy + height, //destination
x, y, x + width, y + height //source
);
}
else {
gfx.copyArea(x, y, width, height, dx, dy);
}
}
int myNoDamage = 0;
int myFramesSkipped = 0;
public void redraw() {
if (tryRedrawDamagedPartFromBuffer() || myCursor.needsRepaint()) {
repaint();
}
}
/**
* This method tries to get a lock for back buffer. If it fails it increments skippedFrames counter and tries next time.
* After 5 attempts it locks buffer anyway.
*
* @return true if was successfully redrawn and there is anything to repaint
*/
private boolean tryRedrawDamagedPartFromBuffer() {
final int newOrigin = newClientScrollOrigin;
if (!myBackBuffer.tryLock()) {
if (myFramesSkipped >= 5) {
myBackBuffer.lock();
}
else {
myFramesSkipped++;
return false;
}
}
try {
myFramesSkipped = 0;
boolean serverScroll = pendingScrolls.enact(myGfx, myImage, getPixelWidth(), myCharSize.height);
boolean clientScroll = myClientScrollOrigin != newOrigin;
if (clientScroll) {
final int oldOrigin = myClientScrollOrigin;
myClientScrollOrigin = newOrigin;
clientScrollOriginChanged(oldOrigin);
}
boolean hasDamage = myBackBuffer.hasDamage();
if (hasDamage) {
myNoDamage = 0;
myBackBuffer.processDamagedCells(this);
myBackBuffer.resetDamage();
}
else {
myNoDamage++;
}
return serverScroll || clientScroll || hasDamage;
}
finally {
myBackBuffer.unlock();
}
}
private void drawMargins(Graphics2D gfx, int width, int height) {
gfx.setColor(getBackground());
gfx.fillRect(0, height, getWidth(), getHeight() - height);
gfx.fillRect(width, 0, getWidth() - width, getHeight());
}
public void scrollArea(final int scrollRegionTop, final int scrollRegionSize, int dy) {
if (dy < 0) {
//Moving lines off the top of the screen
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateScrolling();
}
});
}
mySelection = null;
pendingScrolls.add(scrollRegionTop, scrollRegionSize, dy);
}
private void updateScrolling() {
if (myScrollingEnabled) {
myBoundedRangeModel
.setRangeProperties(0, myTermSize.height, -myBackBuffer.getScrollBuffer().getLineCount(), myTermSize.height, false);
}
else {
myBoundedRangeModel.setRangeProperties(0, myTermSize.height, 0, myTermSize.height, false);
}
}
private class PendingScrolls {
int[] ys = new int[10];
int[] hs = new int[10];
int[] dys = new int[10];
int scrollCount = -1;
void ensureArrays(int index) {
int curLen = ys.length;
if (index >= curLen) {
ys = Util.copyOf(ys, curLen * 2);
hs = Util.copyOf(hs, curLen * 2);
dys = Util.copyOf(dys, curLen * 2);
}
}
void add(int y, int h, int dy) {
if (dy == 0) return;
if (scrollCount >= 0 &&
y == ys[scrollCount] &&
h == hs[scrollCount]) {
dys[scrollCount] += dy;
}
else {
scrollCount++;
ensureArrays(scrollCount);
ys[scrollCount] = y;
hs[scrollCount] = h;
dys[scrollCount] = dy;
}
}
boolean enact(Graphics2D gfx, BufferedImage image, int width, int charHeight) {
if (scrollCount < 0) return false;
for (int i = 0; i <= scrollCount; i++) {
if (dys[i] == 0 || Math.abs(dys[i]) >= hs[i]) { // nothing to do
continue;
}
if (dys[i] > 0) {
copyArea(gfx, image, 0, (ys[i] - 1) * charHeight, width, (hs[i] - dys[i]) * charHeight, 0, dys[i] * charHeight);
}
else {
copyArea(gfx, image, 0, (ys[i] - dys[i] - 1) * charHeight, width, (hs[i] + dys[i]) * charHeight, 0, dys[i] * charHeight);
}
}
scrollCount = -1;
return true;
}
}
final PendingScrolls pendingScrolls = new PendingScrolls();
public void setCursor(final int x, final int y) {
myCursor.setX(x);
myCursor.setY(y);
}
public void beep() {
if (mySettingsProvider.audibleBell()) {
Toolkit.getDefaultToolkit().beep();
}
}
public BoundedRangeModel getBoundedRangeModel() {
return myBoundedRangeModel;
}
public BackBuffer getBackBuffer() {
return myBackBuffer;
}
public TerminalSelection getSelection() {
return mySelection;
}
public LinesBuffer getScrollBuffer() {
return myBackBuffer.getScrollBuffer();
}
public void lock() {
myBackBuffer.lock();
}
public void unlock() {
myBackBuffer.unlock();
}
@Override
public void setCursorVisible(boolean shouldDrawCursor) {
myCursor.setShouldDrawCursor(shouldDrawCursor);
}
protected JPopupMenu createPopupMenu() {
JPopupMenu popup = new JPopupMenu();
TerminalAction.addToMenu(popup, this);
return popup;
}
public void setScrollingEnabled(boolean scrollingEnabled) {
myScrollingEnabled = scrollingEnabled;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateScrolling();
}
});
}
@Override
public void setBlinkingCursor(boolean enabled) {
myCursor.setBlinking(enabled);
}
public TerminalCursor getTerminalCursor() {
return myCursor;
}
public TerminalOutputStream getTerminalOutputStream() {
return myTerminalStarter;
}
@Override
public void setWindowTitle(String name) {
myWindowTitle = name;
if (myTerminalPanelListener != null) {
myTerminalPanelListener.onTitleChanged(myWindowTitle);
}
}
@Override
public List<TerminalAction> getActions() {
return Lists.newArrayList(
new TerminalAction("Copy", mySettingsProvider.getCopyKeyStrokes(), new Predicate<KeyEvent>() {
@Override
public boolean apply(KeyEvent input) {
return handleCopy(true);
}
}).withMnemonicKey(KeyEvent.VK_C).withEnabledSupplier(new Supplier<Boolean>() {
@Override
public Boolean get() {
return mySelection != null;
}
}),
new TerminalAction("Paste", mySettingsProvider.getPasteKeyStrokes(), new Predicate<KeyEvent>() {
@Override
public boolean apply(KeyEvent input) {
handlePaste();
return true;
}
}).withMnemonicKey(KeyEvent.VK_P).withEnabledSupplier(new Supplier<Boolean>() {
@Override
public Boolean get() {
return getClipboardString() != null;
}
}));
}
@Override
public TerminalActionProvider getNextProvider() {
return myNextActionProvider;
}
@Override
public void setNextProvider(TerminalActionProvider provider) {
myNextActionProvider = provider;
}
private void processTerminalKeyPressed(KeyEvent e) {
try {
final int keycode = e.getKeyCode();
final char keychar = e.getKeyChar();
// numLock does not change the code sent by keypad VK_DELETE
// although it send the char '.'
if (keycode == KeyEvent.VK_DELETE && keychar == '.') {
myTerminalStarter.sendBytes(new byte[]{'.'});
return;
}
// CTRL + Space is not handled in KeyEvent; handle it manually
else if (keychar == ' ' && (e.getModifiers() & KeyEvent.CTRL_MASK) != 0) {
myTerminalStarter.sendBytes(new byte[]{Ascii.NUL});
return;
}
final byte[] code = myTerminalStarter.getCode(keycode);
if (code != null) {
myTerminalStarter.sendBytes(code);
}
else if ((keychar & 0xff00) == 0) {
final byte[] obuffer = new byte[1];
obuffer[0] = (byte)keychar;
myTerminalStarter.sendBytes(obuffer);
if (mySettingsProvider.scrollToBottomOnTyping()) {
scrollToBottom();
}
}
}
catch (final Exception ex) {
LOG.error("Error sending key to emulator", ex);
}
}
private void processTerminalKeyTyped(KeyEvent e) {
final char keychar = e.getKeyChar();
if ((keychar & 0xff00) != 0) {
final char[] foo = new char[1];
foo[0] = keychar;
try {
myTerminalStarter.sendString(new String(foo));
if (mySettingsProvider.scrollToBottomOnTyping()) {
scrollToBottom();
}
}
catch (final RuntimeException ex) {
LOG.error("Error sending key to emulator", ex);
}
}
}
public class TerminalKeyHandler implements KeyListener {
public TerminalKeyHandler() {
}
public void keyPressed(final KeyEvent e) {
if (!TerminalAction.processEvent(TerminalPanel.this, e)) {
processTerminalKeyPressed(e);
}
}
public void keyTyped(final KeyEvent e) {
processTerminalKeyTyped(e);
}
//Ignore releases
public void keyReleased(KeyEvent e) {
}
}
private void handlePaste() {
pasteSelection();
}
// "unselect" is needed to handle Ctrl+C copy shortcut collision with ^C signal shortcut
private boolean handleCopy(boolean unselect) {
if (mySelection != null) {
Pair<Point, Point> points = mySelection.pointsForRun(myTermSize.width);
copySelection(points.first, points.second);
if (unselect) {
mySelection = null;
repaint();
}
return true;
}
return false;
}
/**
* InputMethod implementation
* For details read http://docs.oracle.com/javase/7/docs/technotes/guides/imf/api-tutorial.html
*/
@Override
protected void processInputMethodEvent(InputMethodEvent e) {
int commitCount = e.getCommittedCharacterCount();
if (commitCount > 0) {
myInputMethodUncommitedChars = null;
AttributedCharacterIterator text = e.getText();
if (text != null) {
//noinspection ForLoopThatDoesntUseLoopVariable
for (char c = text.first(); commitCount > 0; c = text.next(), commitCount--) {
if (c >= 0x20 && c != 0x7F) { // Hack just like in javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction
int id = (c & 0xff00) == 0 ? KeyEvent.KEY_PRESSED : KeyEvent.KEY_TYPED;
handleKeyEvent(new KeyEvent(this, id, e.getWhen(), 0, 0, c));
}
}
}
}
else {
myInputMethodUncommitedChars = uncommitedChars(e.getText());
}
}
private static String uncommitedChars(AttributedCharacterIterator text) {
StringBuilder sb = new StringBuilder();
for (char c = text.first(); c != CharacterIterator.DONE; c = text.next()) {
if (c >= 0x20 && c != 0x7F) { // Hack just like in javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction
sb.append(c);
}
}
return sb.toString();
}
@Override
public InputMethodRequests getInputMethodRequests() {
return new MyInputMethodRequests();
}
private class MyInputMethodRequests implements InputMethodRequests {
@Override
public Rectangle getTextLocation(TextHitInfo offset) {
Rectangle r = new Rectangle(myCursor.getCoordX() * myCharSize.width, (myCursor.getCoordY() + 1) * myCharSize.height,
0, 0);
Point p = TerminalPanel.this.getLocationOnScreen();
r.translate(p.x, p.y);
return r;
}
@Nullable
@Override
public TextHitInfo getLocationOffset(int x, int y) {
return null;
}
@Override
public int getInsertPositionOffset() {
return 0;
}
@Override
public AttributedCharacterIterator getCommittedText(int beginIndex, int endIndex, AttributedCharacterIterator.Attribute[] attributes) {
return null;
}
@Override
public int getCommittedTextLength() {
return 0;
}
@Nullable
@Override
public AttributedCharacterIterator cancelLatestCommittedText(AttributedCharacterIterator.Attribute[] attributes) {
return null;
}
@Nullable
@Override
public AttributedCharacterIterator getSelectedText(AttributedCharacterIterator.Attribute[] attributes) {
return null;
}
}
}
|
Clear background for input method uncommited chars.
|
src-terminal/com/jediterm/terminal/ui/TerminalPanel.java
|
Clear background for input method uncommited chars.
|
|
Java
|
apache-2.0
|
29145f8c7cf441e749c331070eb29a4cfe5f2e87
| 0
|
nengxu/OrientDB,vivosys/orientdb,vivosys/orientdb,nengxu/OrientDB,nengxu/OrientDB,vivosys/orientdb,vivosys/orientdb,nengxu/OrientDB
|
/*
* Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.serialization.serializer.record.string;
import java.io.IOException;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.orientechnologies.common.parser.OStringParser;
import com.orientechnologies.orient.core.db.OUserObject2RecordHandler;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.exception.OSerializationException;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecordFactory;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.ORecordSchemaAware;
import com.orientechnologies.orient.core.record.ORecordStringable;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ORecordBytes;
import com.orientechnologies.orient.core.record.impl.ORecordColumn;
import com.orientechnologies.orient.core.serialization.OBase64Utils;
import com.orientechnologies.orient.core.serialization.serializer.OJSONWriter;
import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
public class ORecordSerializerJSON extends ORecordSerializerStringAbstract {
public static final String NAME = "json";
public static final ORecordSerializerJSON INSTANCE = new ORecordSerializerJSON();
public static final String ATTRIBUTE_ID = "@rid";
public static final String ATTRIBUTE_VERSION = "@version";
public static final String ATTRIBUTE_TYPE = "@type";
public static final String ATTRIBUTE_CLASS = "@class";
public static final String DEF_DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
private SimpleDateFormat dateFormat = new SimpleDateFormat(DEF_DATE_FORMAT);
@Override
public ORecordInternal<?> fromString(final ODatabaseRecord<?> iDatabase, final String iSource) {
return fromString(iDatabase, iSource, null);
}
@Override
public ORecordInternal<?> fromString(final ODatabaseRecord<?> iDatabase, String iSource, ORecordInternal<?> iRecord) {
iSource = iSource.trim();
if (!iSource.startsWith("{") || !iSource.endsWith("}"))
throw new OSerializationException("Error on unmarshalling JSON content: content must be embraced by { }");
if (iRecord != null) {
iRecord.reset();
iRecord.setDirty();
}
iSource = iSource.substring(1, iSource.length() - 1).trim();
String[] fields = OStringParser.getWords(iSource, ":,", true);
try {
if (fields != null && fields.length > 0) {
String fieldName;
String fieldValue;
String fieldValueAsString;
for (int i = 0; i < fields.length; i += 2) {
fieldName = fields[i];
fieldName = fieldName.substring(1, fieldName.length() - 1);
fieldValue = fields[i + 1];
fieldValueAsString = fieldValue.length() >= 2 ? fieldValue.substring(1, fieldValue.length() - 1) : fieldValue;
// RECORD ATTRIBUTES
if (fieldName.equals(ATTRIBUTE_ID))
iRecord.setIdentity(new ORecordId(fieldValueAsString));
else if (fieldName.equals(ATTRIBUTE_VERSION))
iRecord.setVersion(Integer.parseInt(fieldValue));
else if (fieldName.equals(ATTRIBUTE_TYPE)) {
if (iRecord == null || iRecord.getRecordType() != fieldValueAsString.charAt(0)) {
// CREATE THE RIGHT RECORD INSTANCE
iRecord = ORecordFactory.newInstance((byte) fieldValueAsString.charAt(0));
iRecord.setDatabase(iDatabase);
}
} else if (fieldName.equals(ATTRIBUTE_CLASS) && iRecord instanceof ODocument)
((ODocument) iRecord).setClassNameIfExists("null".equals(fieldValueAsString) ? null : fieldValueAsString);
// RECORD VALUE(S)
else if (fieldName.equals("value")) {
if (iRecord instanceof ORecordColumn) {
fieldValueAsString = fieldValueAsString.trim();
final String[] items = OStringParser.getWords(fieldValueAsString, ",");
for (String item : items) {
((ORecordColumn) iRecord).add(item);
}
} else if (iRecord instanceof ORecordBytes) {
// BYTES
iRecord.fromStream(OBase64Utils.decode(fieldValueAsString));
} else if (iRecord instanceof ORecordStringable) {
((ORecordStringable) iRecord).value(fieldValueAsString);
}
} else {
if (iRecord instanceof ODocument)
((ODocument) iRecord).field(fieldName,
getValue((ODocument) iRecord, fieldName, fieldValue, fieldValueAsString, null, null));
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw new OSerializationException("Error on unmarshalling JSON content", e);
}
return iRecord;
}
private Object getValue(final ODocument iRecord, String iFieldName, String iFieldValue, String iFieldValueAsString, OType type,
OType linkedType) {
if (iFieldValueAsString.equals("null"))
return null;
if (iFieldName != null)
if (iRecord.getSchemaClass() != null) {
final OProperty p = iRecord.getSchemaClass().getProperty(iFieldName);
if (p != null) {
type = p.getType();
linkedType = p.getLinkedType();
}
}
if (iFieldValue.startsWith("{") && iFieldValue.endsWith("}")) {
// OBJECT OR MAP. CHECK THE TYPE ATTRIBUTE TO KNOW IT
String[] fields = OStringParser.getWords(iFieldValueAsString, ":,", true);
if (fields == null || fields.length == 0)
// EMPTY, WHAT EVER IT WAS
return null;
if (fields[0].equals("\"@type\""))
// OBJECT
return fromString(iRecord.getDatabase(), iFieldValue, null);
else {
// MAP
final Map<String, Object> embeddedMap = new LinkedHashMap<String, Object>();
for (int i = 0; i < fields.length; i += 2) {
iFieldName = fields[i];
if (iFieldName.length() >= 2)
iFieldName = iFieldName.substring(1, iFieldName.length() - 1);
iFieldValue = fields[i + 1];
iFieldValueAsString = iFieldValue.length() >= 2 ? iFieldValue.substring(1, iFieldValue.length() - 1) : iFieldValue;
embeddedMap.put(iFieldName, getValue(iRecord, null, iFieldValue, iFieldValueAsString, linkedType, null));
}
return embeddedMap;
}
} else if (iFieldValue.startsWith("[") && iFieldValue.endsWith("]")) {
// EMBEDDED VALUES
final Collection<Object> embeddedCollection;
if (type == OType.LINKSET || type == OType.EMBEDDEDSET)
embeddedCollection = new HashSet<Object>();
else
embeddedCollection = new ArrayList<Object>();
iFieldValue = iFieldValue.substring(1, iFieldValue.length() - 1);
if (iFieldValue.length() > 0) {
// EMBEDDED VALUES
List<String> items = OStringSerializerHelper.smartSplit(iFieldValue, ',');
for (String item : items) {
iFieldValue = item.trim();
iFieldValueAsString = iFieldValue.length() >= 2 ? iFieldValue.substring(1, iFieldValue.length() - 1) : iFieldValue;
embeddedCollection.add(getValue(iRecord, null, iFieldValue, iFieldValueAsString, linkedType, null));
}
}
return embeddedCollection;
}
if (type == null)
// TRY TO DETERMINE THE CONTAINED TYPE from THE FIRST VALUE
if (iFieldValue.charAt(0) != '\"') {
if (iFieldValue.equalsIgnoreCase("false") || iFieldValue.equalsIgnoreCase("true"))
type = OType.BOOLEAN;
else if (OStringSerializerHelper.contains(iFieldValue, '.'))
type = OType.DOUBLE;
else
type = OType.LONG;
} else if (iFieldValueAsString.length() >= 4 && iFieldValueAsString.charAt(0) == '#')
type = OType.LINK;
else if (iFieldValueAsString.startsWith("{") && iFieldValueAsString.endsWith("}"))
type = OType.EMBEDDED;
else {
if (iFieldValueAsString.length() == DEF_DATE_FORMAT.length())
// TRY TO PARSE AS DATE
try {
return dateFormat.parseObject(iFieldValueAsString);
} catch (Exception e) {
}
type = OType.STRING;
}
if (type != null)
switch (type) {
case STRING:
return iFieldValueAsString;
case LINK:
final int pos = iFieldValueAsString.indexOf("@");
if (pos > -1)
// CREATE DOCUMENT
return new ODocument(iRecord.getDatabase(), iFieldValueAsString.substring(1, pos), new ORecordId(
iFieldValueAsString.substring(pos + 1)));
else
// CREATE SIMPLE RID
return new ORecordId(iFieldValueAsString.substring(1));
case EMBEDDED:
return fromString(iRecord.getDatabase(), iFieldValueAsString);
case DATE:
// TRY TO PARSE AS DATE
try {
return dateFormat.parseObject(iFieldValueAsString);
} catch (ParseException e) {
throw new OSerializationException("Unable to unmarshall date: " + iFieldValueAsString, e);
}
default:
return OStringSerializerHelper.fieldTypeFromStream(type, iFieldValue);
}
return iFieldValueAsString;
}
@Override
public String toString(final ORecordInternal<?> iRecord, final String iFormat, final OUserObject2RecordHandler iObjHandler,
final Map<ORecordInternal<?>, ORecordId> iMarshalledRecords) {
try {
final StringWriter buffer = new StringWriter();
final OJSONWriter json = new OJSONWriter(buffer);
boolean includeVer;
boolean includeType;
boolean includeId;
boolean includeClazz;
boolean attribSameRow;
int indentLevel;
if (iFormat == null) {
includeType = true;
includeVer = true;
includeId = true;
includeClazz = true;
attribSameRow = true;
indentLevel = 0;
} else {
includeType = true;
includeVer = false;
includeId = false;
includeClazz = false;
attribSameRow = false;
indentLevel = 0;
String[] format = iFormat.split(",");
for (String f : format)
if (f.equals("type"))
includeType = true;
else if (f.equals("rid"))
includeId = true;
else if (f.equals("version"))
includeVer = true;
else if (f.equals("class"))
includeClazz = true;
else if (f.equals("attribSameRow"))
attribSameRow = true;
else if (f.startsWith("indent"))
indentLevel = Integer.parseInt(f.substring(f.indexOf(":") + 1));
}
json.beginObject(indentLevel);
boolean firstAttribute = true;
if (includeType) {
json.writeAttribute(firstAttribute ? indentLevel + 1 : 0, firstAttribute, ATTRIBUTE_TYPE,
"" + (char) iRecord.getRecordType());
if (attribSameRow)
firstAttribute = false;
}
if (includeId) {
json.writeAttribute(firstAttribute ? indentLevel + 1 : 0, firstAttribute, ATTRIBUTE_ID, iRecord.getIdentity().toString());
if (attribSameRow)
firstAttribute = false;
}
if (includeVer) {
json.writeAttribute(firstAttribute ? indentLevel + 1 : 0, firstAttribute, ATTRIBUTE_VERSION, iRecord.getVersion());
if (attribSameRow)
firstAttribute = false;
}
if (includeClazz && iRecord instanceof ORecordSchemaAware<?>) {
json.writeAttribute(firstAttribute ? indentLevel + 1 : 0, firstAttribute, ATTRIBUTE_CLASS,
((ORecordSchemaAware<?>) iRecord).getClassName());
if (attribSameRow)
firstAttribute = false;
}
if (iRecord instanceof ORecordSchemaAware<?>) {
// SCHEMA AWARE
final ORecordSchemaAware<?> record = (ORecordSchemaAware<?>) iRecord;
for (String fieldName : record.fieldNames()) {
json.writeAttribute(indentLevel + 1, true, fieldName, encode(record.field(fieldName)));
}
} else if (iRecord instanceof ORecordStringable) {
// STRINGABLE
final ORecordStringable record = (ORecordStringable) iRecord;
json.writeAttribute(indentLevel + 1, true, "value", record.value());
} else if (iRecord instanceof ORecordBytes) {
// BYTES
final ORecordBytes record = (ORecordBytes) iRecord;
json.writeAttribute(indentLevel + 1, true, "value", OBase64Utils.encodeBytes(record.toStream()));
} else
throw new OSerializationException("Error on marshalling record of type '" + iRecord.getClass()
+ "' to JSON. The record type can't be exported to JSON");
json.endObject(indentLevel);
return buffer.toString();
} catch (IOException e) {
throw new OSerializationException("Error on marshalling of record to JSON", e);
}
}
private Object encode(final Object iValue) {
if (iValue instanceof String) {
return convert2unicode(((String) iValue).replace('"', '\''));
} else
return iValue;
}
public static String convert2unicode(String str) {
StringBuffer ostr = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if ((ch >= 0x0020) && (ch <= 0x007e)) // Does the char need to be converted to unicode?
{
ostr.append(ch); // No.
} else // Yes.
{
ostr.append("\\u"); // standard unicode format.
String hex = Integer.toHexString(str.charAt(i) & 0xFFFF); // Get hex value of the char.
for (int j = 0; j < 4 - hex.length(); j++)
// Prepend zeros because unicode requires 4 digits
ostr.append("0");
ostr.append(hex.toLowerCase()); // standard unicode format.
// ostr.append(hex.toLowerCase(Locale.ENGLISH));
}
}
return (new String(ostr)); // Return the stringbuffer cast as a string.
}
@Override
public String toString() {
return NAME;
}
}
|
core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java
|
/*
* Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.serialization.serializer.record.string;
import java.io.IOException;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.orientechnologies.common.parser.OStringParser;
import com.orientechnologies.orient.core.db.OUserObject2RecordHandler;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.exception.OSerializationException;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecordFactory;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.ORecordSchemaAware;
import com.orientechnologies.orient.core.record.ORecordStringable;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ORecordBytes;
import com.orientechnologies.orient.core.record.impl.ORecordColumn;
import com.orientechnologies.orient.core.serialization.OBase64Utils;
import com.orientechnologies.orient.core.serialization.serializer.OJSONWriter;
import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
public class ORecordSerializerJSON extends ORecordSerializerStringAbstract {
public static final String NAME = "json";
public static final ORecordSerializerJSON INSTANCE = new ORecordSerializerJSON();
public static final String ATTRIBUTE_ID = "@rid";
public static final String ATTRIBUTE_VERSION = "@version";
public static final String ATTRIBUTE_TYPE = "@type";
public static final String ATTRIBUTE_CLASS = "@class";
public static final String DEF_DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
private SimpleDateFormat dateFormat = new SimpleDateFormat(DEF_DATE_FORMAT);
@Override
public ORecordInternal<?> fromString(final ODatabaseRecord<?> iDatabase, final String iSource) {
return fromString(iDatabase, iSource, null);
}
@Override
public ORecordInternal<?> fromString(final ODatabaseRecord<?> iDatabase, String iSource, ORecordInternal<?> iRecord) {
iSource = iSource.trim();
if (!iSource.startsWith("{") || !iSource.endsWith("}"))
throw new OSerializationException("Error on unmarshalling JSON content: content must be embraced by { }");
if (iRecord != null) {
iRecord.reset();
iRecord.setDirty();
}
iSource = iSource.substring(1, iSource.length() - 1).trim();
String[] fields = OStringParser.getWords(iSource, ":,", true);
try {
if (fields != null && fields.length > 0) {
String fieldName;
String fieldValue;
String fieldValueAsString;
for (int i = 0; i < fields.length; i += 2) {
fieldName = fields[i];
fieldName = fieldName.substring(1, fieldName.length() - 1);
fieldValue = fields[i + 1];
fieldValueAsString = fieldValue.length() >= 2 ? fieldValue.substring(1, fieldValue.length() - 1) : fieldValue;
// RECORD ATTRIBUTES
if (fieldName.equals(ATTRIBUTE_ID))
iRecord.setIdentity(new ORecordId(fieldValueAsString));
else if (fieldName.equals(ATTRIBUTE_VERSION))
iRecord.setVersion(Integer.parseInt(fieldValue));
else if (fieldName.equals(ATTRIBUTE_TYPE)) {
if (iRecord == null || iRecord.getRecordType() != fieldValueAsString.charAt(0)) {
// CREATE THE RIGHT RECORD INSTANCE
iRecord = ORecordFactory.newInstance((byte) fieldValueAsString.charAt(0));
iRecord.setDatabase(iDatabase);
}
} else if (fieldName.equals(ATTRIBUTE_CLASS) && iRecord instanceof ODocument)
((ODocument) iRecord).setClassNameIfExists("null".equals(fieldValueAsString) ? null : fieldValueAsString);
// RECORD VALUE(S)
else if (fieldName.equals("value")) {
if (iRecord instanceof ORecordColumn) {
fieldValueAsString = fieldValueAsString.trim();
final String[] items = OStringParser.getWords(fieldValueAsString, ",");
for (String item : items) {
((ORecordColumn) iRecord).add(item);
}
} else if (iRecord instanceof ORecordBytes) {
// BYTES
iRecord.fromStream(OBase64Utils.decode(fieldValueAsString));
} else if (iRecord instanceof ORecordStringable) {
((ORecordStringable) iRecord).value(fieldValueAsString);
}
} else {
if (iRecord instanceof ODocument)
((ODocument) iRecord).field(fieldName,
getValue((ODocument) iRecord, fieldName, fieldValue, fieldValueAsString, null, null));
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw new OSerializationException("Error on unmarshalling JSON content", e);
}
return iRecord;
}
private Object getValue(final ODocument iRecord, String iFieldName, String iFieldValue, String iFieldValueAsString, OType type,
OType linkedType) {
if (iFieldValueAsString.equals("null"))
return null;
if (iFieldName != null)
if (iRecord.getSchemaClass() != null) {
final OProperty p = iRecord.getSchemaClass().getProperty(iFieldName);
if (p != null) {
type = p.getType();
linkedType = p.getLinkedType();
}
}
if (iFieldValue.startsWith("{") && iFieldValue.endsWith("}")) {
// OBJECT OR MAP. CHECK THE TYPE ATTRIBUTE TO KNOW IT
String[] fields = OStringParser.getWords(iFieldValueAsString, ":,", true);
if (fields == null || fields.length == 0)
// EMPTY, WHAT EVER IT WAS
return null;
if (fields[0].equals("\"@type\""))
// OBJECT
return fromString(iRecord.getDatabase(), iFieldValue, null);
else {
// MAP
final Map<String, Object> embeddedMap = new LinkedHashMap<String, Object>();
for (int i = 0; i < fields.length; i += 2) {
iFieldName = fields[i];
if (iFieldName.length() >= 2)
iFieldName = iFieldName.substring(1, iFieldName.length() - 1);
iFieldValue = fields[i + 1];
iFieldValueAsString = iFieldValue.length() >= 2 ? iFieldValue.substring(1, iFieldValue.length() - 1) : iFieldValue;
embeddedMap.put(iFieldName, getValue(iRecord, null, iFieldValue, iFieldValueAsString, linkedType, null));
}
return embeddedMap;
}
} else if (iFieldValue.startsWith("[") && iFieldValue.endsWith("]")) {
// EMBEDDED VALUES
final Collection<Object> embeddedCollection;
if (type == OType.LINKSET || type == OType.EMBEDDEDSET)
embeddedCollection = new HashSet<Object>();
else
embeddedCollection = new ArrayList<Object>();
iFieldValue = iFieldValue.substring(1, iFieldValue.length() - 1);
if (iFieldValue.length() > 0) {
// EMBEDDED VALUES
List<String> items = OStringSerializerHelper.smartSplit(iFieldValue, ',');
for (String item : items) {
iFieldValue = item.trim();
iFieldValueAsString = iFieldValue.length() >= 2 ? iFieldValue.substring(1, iFieldValue.length() - 1) : iFieldValue;
embeddedCollection.add(getValue(iRecord, null, iFieldValue, iFieldValueAsString, linkedType, null));
}
}
return embeddedCollection;
}
if (type == null)
// TRY TO DETERMINE THE CONTAINED TYPE from THE FIRST VALUE
if (iFieldValue.charAt(0) != '\"') {
if (iFieldValue.equalsIgnoreCase("false") || iFieldValue.equalsIgnoreCase("true"))
type = OType.BOOLEAN;
else if (OStringSerializerHelper.contains(iFieldValue, '.'))
type = OType.DOUBLE;
else
type = OType.LONG;
} else if (iFieldValueAsString.length() >= 4 && iFieldValueAsString.charAt(0) == '#')
type = OType.LINK;
else if (iFieldValueAsString.startsWith("{") && iFieldValueAsString.endsWith("}"))
type = OType.EMBEDDED;
else {
if (iFieldValueAsString.length() == DEF_DATE_FORMAT.length())
// TRY TO PARSE AS DATE
try {
return dateFormat.parseObject(iFieldValueAsString);
} catch (Exception e) {
}
type = OType.STRING;
}
if (type != null)
switch (type) {
case STRING:
return iFieldValueAsString;
case LINK:
final int pos = iFieldValueAsString.indexOf("@");
if (pos > -1)
// CREATE DOCUMENT
return new ODocument(iRecord.getDatabase(), iFieldValueAsString.substring(1, pos), new ORecordId(
iFieldValueAsString.substring(pos + 1)));
else
// CREATE SIMPLE RID
return new ORecordId(iFieldValueAsString.substring(1));
case EMBEDDED:
return fromString(iRecord.getDatabase(), iFieldValueAsString);
case DATE:
// TRY TO PARSE AS DATE
try {
return dateFormat.parseObject(iFieldValueAsString);
} catch (ParseException e) {
throw new OSerializationException("Unable to unmarshall date: " + iFieldValueAsString, e);
}
default:
return OStringSerializerHelper.fieldTypeFromStream(type, iFieldValue);
}
return iFieldValueAsString;
}
@Override
public String toString(final ORecordInternal<?> iRecord, final String iFormat, final OUserObject2RecordHandler iObjHandler,
final Map<ORecordInternal<?>, ORecordId> iMarshalledRecords) {
try {
final StringWriter buffer = new StringWriter();
final OJSONWriter json = new OJSONWriter(buffer);
boolean includeVer;
boolean includeType;
boolean includeId;
boolean includeClazz;
boolean attribSameRow;
int indentLevel;
if (iFormat == null) {
includeType = true;
includeVer = true;
includeId = true;
includeClazz = true;
attribSameRow = true;
indentLevel = 0;
} else {
includeType = true;
includeVer = false;
includeId = false;
includeClazz = false;
attribSameRow = false;
indentLevel = 0;
String[] format = iFormat.split(",");
for (String f : format)
if (f.equals("type"))
includeType = true;
else if (f.equals("rid"))
includeId = true;
else if (f.equals("version"))
includeVer = true;
else if (f.equals("class"))
includeClazz = true;
else if (f.equals("attribSameRow"))
attribSameRow = true;
else if (f.startsWith("indent"))
indentLevel = Integer.parseInt(f.substring(f.indexOf(":") + 1));
}
json.beginObject(indentLevel);
boolean firstAttribute = true;
if (includeType) {
json.writeAttribute(firstAttribute ? indentLevel + 1 : 0, firstAttribute, ATTRIBUTE_TYPE,
"" + (char) iRecord.getRecordType());
if (attribSameRow)
firstAttribute = false;
}
if (includeId) {
json.writeAttribute(firstAttribute ? indentLevel + 1 : 0, firstAttribute, ATTRIBUTE_ID, iRecord.getIdentity().toString());
if (attribSameRow)
firstAttribute = false;
}
if (includeVer) {
json.writeAttribute(firstAttribute ? indentLevel + 1 : 0, firstAttribute, ATTRIBUTE_VERSION, iRecord.getVersion());
if (attribSameRow)
firstAttribute = false;
}
if (includeClazz && iRecord instanceof ORecordSchemaAware<?>) {
json.writeAttribute(firstAttribute ? indentLevel + 1 : 0, firstAttribute, ATTRIBUTE_CLASS,
((ORecordSchemaAware<?>) iRecord).getClassName());
if (attribSameRow)
firstAttribute = false;
}
if (iRecord instanceof ORecordSchemaAware<?>) {
// SCHEMA AWARE
final ORecordSchemaAware<?> record = (ORecordSchemaAware<?>) iRecord;
for (String fieldName : record.fieldNames()) {
json.writeAttribute(indentLevel + 1, true, fieldName, encode(record.field(fieldName)));
}
} else if (iRecord instanceof ORecordStringable) {
// STRINGABLE
final ORecordStringable record = (ORecordStringable) iRecord;
json.writeAttribute(indentLevel + 1, true, "value", record.value());
} else if (iRecord instanceof ORecordBytes) {
// BYTES
final ORecordBytes record = (ORecordBytes) iRecord;
json.writeAttribute(indentLevel + 1, true, "value", OBase64Utils.encodeBytes(record.toStream()));
} else
throw new OSerializationException("Error on marshalling record of type '" + iRecord.getClass()
+ "' to JSON. The record type can't be exported to JSON");
json.endObject(indentLevel);
return buffer.toString();
} catch (IOException e) {
throw new OSerializationException("Error on marshalling of record to JSON", e);
}
}
private Object encode(final Object iValue) {
if (iValue instanceof String) {
final String encoded = ((String) iValue).replace('"', '\'');
return encoded;
} else
return iValue;
}
@Override
public String toString() {
return NAME;
}
}
|
Support for Unicode in JSON output
git-svn-id: 9ddf022f45b579842a47abc018ed2b18cdc52108@1463 3625ad7b-9c83-922f-a72b-73d79161f2ea
|
core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java
|
Support for Unicode in JSON output
|
|
Java
|
apache-2.0
|
5ca01d4614dd7dd3d697554a81d38582814c5682
| 0
|
sherbold/CrossPare
|
// Copyright 2015 Georg-August-Universität Göttingen, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package de.ugoe.cs.cpdp.eval;
import java.io.PrintStream;
import java.util.Random;
import org.apache.commons.io.output.NullOutputStream;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.core.Instances;
/**
* Implements the {@link AbstractWekaEvaluation} for 10-fold cross validation.
*
* @author Steffen Herbold
*/
public class CVWekaEvaluation extends AbstractWekaEvaluation {
/*
* @see de.ugoe.cs.cpdp.eval.AbstractWekaEvaluation#createEvaluator(weka.core.Instances,
* weka.classifiers.Classifier)
*/
@Override
protected Evaluation createEvaluator(Instances testdata, Classifier classifier) {
PrintStream errStr = System.err;
try(PrintStream nullStream = new PrintStream(new NullOutputStream());) {
System.setErr(nullStream);
try {
final Evaluation eval = new Evaluation(testdata);
eval.crossValidateModel(classifier, testdata, 10, new Random());
return eval;
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
System.setErr(errStr);
}
}
}
}
|
CrossPare/src/main/java/de/ugoe/cs/cpdp/eval/CVWekaEvaluation.java
|
// Copyright 2015 Georg-August-Universität Göttingen, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package de.ugoe.cs.cpdp.eval;
import java.io.PrintStream;
import java.util.Random;
import org.apache.commons.io.output.NullOutputStream;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.core.Instances;
/**
* Implements the {@link AbstractWekaEvaluation} for 10-fold cross validation.
*
* @author Steffen Herbold
*/
public class CVWekaEvaluation extends AbstractWekaEvaluation {
/*
* @see de.ugoe.cs.cpdp.eval.AbstractWekaEvaluation#createEvaluator(weka.core.Instances,
* weka.classifiers.Classifier)
*/
@Override
protected Evaluation createEvaluator(Instances testdata, Classifier classifier) {
PrintStream errStr = System.err;
try(PrintStream nullStream = new PrintStream(new NullOutputStream());) {
System.setErr(nullStream);
try {
final Evaluation eval = new Evaluation(testdata);
eval.crossValidateModel(classifier, testdata, 10, new Random(1));
return eval;
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
System.setErr(errStr);
}
}
}
}
|
Removed fixed seed from CV
|
CrossPare/src/main/java/de/ugoe/cs/cpdp/eval/CVWekaEvaluation.java
|
Removed fixed seed from CV
|
|
Java
|
apache-2.0
|
0408dc959ed8b8bc0ecd8eca66c1b13a1b645d77
| 0
|
wuan/bo-android,d3xter/bo-android,d3xter/bo-android
|
package org.blitzortung.android.app.view;
import java.util.GregorianCalendar;
import org.blitzortung.android.alarm.AlarmManager;
import org.blitzortung.android.alarm.AlarmSector;
import org.blitzortung.android.alarm.AlarmStatus;
import org.blitzortung.android.app.R;
import org.blitzortung.android.map.overlay.color.ColorHandler;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class AlarmView extends View implements AlarmManager.AlarmListener {
public AlarmView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AlarmView(Context context) {
this(context, null, 0);
}
public AlarmView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Log.v("AlarmView", "created");
}
private AlarmManager alarmManager;
private AlarmStatus alarmStatus;
private ColorHandler colorHandler;
private int minutesPerColor;
public void setAlarmManager(AlarmManager alarmManager) {
// Log.v("AlarmView", "setAlarmManager " + alarmManager);
this.alarmManager = alarmManager;
this.alarmStatus = alarmManager.getAlarmStatus();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
// Log.v("AlarmView", String.format("onMeasure() width: %d, height: %d",
// parentWidth, parentHeight));
int size = Math.min(parentWidth, parentHeight);
super.onMeasure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY));
}
@Override
protected void onAttachedToWindow() {
alarmManager.addAlarmListener(this);
// Log.v("AlarmView", "attached");
}
@Override
protected void onDetachedFromWindow() {
alarmManager.removeAlarmListener(this);
// Log.v("AlarmView", "detached");
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int size = Math.max(getWidth(), getHeight());
int pad = 4;
float center = size / 2.0f;
float radius = center - pad;
// Log.v("AlarmView", String.format("onDraw() size: %d", size));
RectF area = new RectF(pad, pad, size - pad, size - pad);
Paint background = new Paint();
background.setColor(0xffc0c0c0);
Paint lines = new Paint();
lines.setColor(0xff404040);
lines.setStyle(Style.STROKE);
lines.setStrokeWidth(2);
lines.setAntiAlias(true);
Paint textStyle = new Paint();
textStyle.setColor(0xff404040);
textStyle.setTextAlign(Align.CENTER);
canvas.drawArc(area, 0, 360, true, background);
if (alarmStatus != null) {
long now = new GregorianCalendar().getTime().getTime();
float sectorSize = alarmStatus.getSectorSize();
float halfSectorSize = sectorSize / 2.0f;
float radiusIncrement = radius / AlarmSector.getDistanceLimitCount();
for (int sectorIndex = 0; sectorIndex < alarmStatus.getSectorCount(); sectorIndex++) {
float bearing = alarmStatus.getSectorBearing(sectorIndex) + 90 + 180;
AlarmSector sector = alarmStatus.getSector(sectorIndex);
// Log.v("AlarmView", String.format("sector %d, bearing %.0f",
// sectorIndex, bearing));
int counts[] = sector.getEventCounts();
long latestTimes[] = sector.getLatestTimes();
for (int distanceIndex = AlarmSector.getDistanceLimitCount() - 1; distanceIndex >= 0; distanceIndex--) {
Paint sectorPaint = new Paint();
float sectorRadius = (distanceIndex + 1) * radiusIncrement;
float leftTop = center - sectorRadius;
float bottomRight = center + sectorRadius;
float startAngle = bearing - halfSectorSize;
if (counts[distanceIndex] > 0) {
sectorPaint.setColor(colorHandler.getColor(now, latestTimes[distanceIndex], minutesPerColor));
// Log.v("AlarmView",
// String.format("segment %d, count %d, alarm: %.1f, %.1f",
// distanceIndex, counts[distanceIndex], startAngle,
// leftTop, bottomRight));
} else {
sectorPaint = background;
}
canvas.drawArc(new RectF(leftTop, leftTop, bottomRight, bottomRight), startAngle, halfSectorSize * 2.0f, true,
sectorPaint);
}
}
for (int sectorIndex = 0; sectorIndex < alarmStatus.getSectorCount(); sectorIndex++) {
double bearing = alarmStatus.getSectorBearing(sectorIndex);
canvas.drawLine(center, center, center + (float) (radius * Math.sin((bearing + halfSectorSize) / 180.0 * Math.PI)), center
+ (float) (radius * -Math.cos((bearing + halfSectorSize) / 180.0 * Math.PI)), lines);
String text = alarmStatus.getSectorLabel(sectorIndex);
if (!text.equals("O")) {
float textRadius = (AlarmSector.getDistanceLimitCount() - 0.5f) * radiusIncrement;
canvas.drawText(text, center
+ (float) (textRadius * Math.sin(bearing / 180.0 * Math.PI)), center
+ (float) (textRadius * -Math.cos(bearing / 180.0 * Math.PI)) + textStyle.getFontMetrics(null) / 3f, textStyle);
}
}
textStyle.setTextAlign(Align.RIGHT);
for (int distanceIndex = 0; distanceIndex < AlarmSector.getDistanceLimitCount(); distanceIndex++) {
float leftTop = center - (distanceIndex + 1) * radiusIncrement;
float bottomRight = center + (distanceIndex + 1) * radiusIncrement;
canvas.drawArc(new RectF(leftTop, leftTop, bottomRight, bottomRight), 0, 360, false, lines);
String text = String.format("%.0f", AlarmSector.getDistanceLimits()[distanceIndex] / 1000);
canvas.drawText(text, center + (float) (distanceIndex + 0.95f) * radiusIncrement, center
+ textStyle.getFontMetrics(null) / 3f, textStyle);
}
} else {
Log.v("AlarmView", "onDraw() alarmStatus is not set");
Paint warnText = new Paint();
warnText.setColor(0xffa00000);
warnText.setTextAlign(Align.CENTER);
warnText.setTextSize(20);
warnText.setAntiAlias(true);
String text = getContext().getString(R.string.alarms_not_available);
String textLines[] = text.split("\n");
for (int line=0; line < textLines.length; line++) {
canvas.drawText(textLines[line], center, center + (line - 1) * warnText.getFontMetrics(null), warnText);
}
}
}
@Override
public void onAlarmResult(AlarmStatus alarmStatus) {
this.alarmStatus = alarmStatus;
invalidate();
}
@Override
public void onAlarmClear() {
alarmStatus = null;
}
public void setColorHandler(ColorHandler colorHandler, int minutesPerColor) {
this.colorHandler = colorHandler;
this.minutesPerColor = minutesPerColor;
}
}
|
src/org/blitzortung/android/app/view/AlarmView.java
|
package org.blitzortung.android.app.view;
import java.util.GregorianCalendar;
import org.blitzortung.android.alarm.AlarmManager;
import org.blitzortung.android.alarm.AlarmSector;
import org.blitzortung.android.alarm.AlarmStatus;
import org.blitzortung.android.app.R;
import org.blitzortung.android.map.overlay.color.ColorHandler;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class AlarmView extends View implements AlarmManager.AlarmListener {
public AlarmView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AlarmView(Context context) {
this(context, null, 0);
}
public AlarmView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Log.v("AlarmView", "created");
}
private AlarmManager alarmManager;
private AlarmStatus alarmStatus;
private ColorHandler colorHandler;
private int minutesPerColor;
public void setAlarmManager(AlarmManager alarmManager) {
// Log.v("AlarmView", "setAlarmManager " + alarmManager);
this.alarmManager = alarmManager;
this.alarmStatus = alarmManager.getAlarmStatus();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
// Log.v("AlarmView", String.format("onMeasure() width: %d, height: %d",
// parentWidth, parentHeight));
int size = Math.min(parentWidth, parentHeight);
super.onMeasure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY));
}
@Override
protected void onAttachedToWindow() {
alarmManager.addAlarmListener(this);
// Log.v("AlarmView", "attached");
}
@Override
protected void onDetachedFromWindow() {
alarmManager.removeAlarmListener(this);
// Log.v("AlarmView", "detached");
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int size = Math.max(getWidth(), getHeight());
int pad = 4;
float center = size / 2.0f;
float radius = center - pad;
// Log.v("AlarmView", String.format("onDraw() size: %d", size));
RectF area = new RectF(pad, pad, size - pad, size - pad);
Paint background = new Paint();
background.setColor(0xffaaaaaa);
Paint lines = new Paint();
lines.setColor(0xff555555);
lines.setStyle(Style.STROKE);
lines.setStrokeWidth(2);
lines.setAntiAlias(true);
Paint textStyle = new Paint();
textStyle.setColor(0xff555555);
canvas.drawArc(area, 0, 360, true, background);
if (alarmStatus != null) {
long now = new GregorianCalendar().getTime().getTime();
float sectorSize = alarmStatus.getSectorSize();
float halfSectorSize = sectorSize / 2.0f;
float radiusIncrement = radius / AlarmSector.getDistanceLimitCount();
for (int sectorIndex = 0; sectorIndex < alarmStatus.getSectorCount(); sectorIndex++) {
float bearing = alarmStatus.getSectorBearing(sectorIndex) + 90 + 180;
AlarmSector sector = alarmStatus.getSector(sectorIndex);
// Log.v("AlarmView", String.format("sector %d, bearing %.0f",
// sectorIndex, bearing));
int counts[] = sector.getEventCounts();
long latestTimes[] = sector.getLatestTimes();
for (int distanceIndex = AlarmSector.getDistanceLimitCount() - 1; distanceIndex >= 0; distanceIndex--) {
Paint sectorPaint = new Paint();
float sectorRadius = (distanceIndex + 1) * radiusIncrement;
float leftTop = center - sectorRadius;
float bottomRight = center + sectorRadius;
float startAngle = bearing - halfSectorSize;
if (counts[distanceIndex] > 0) {
sectorPaint.setColor(colorHandler.getColor(now, latestTimes[distanceIndex], minutesPerColor));
// Log.v("AlarmView",
// String.format("segment %d, count %d, alarm: %.1f, %.1f",
// distanceIndex, counts[distanceIndex], startAngle,
// leftTop, bottomRight));
} else {
sectorPaint = background;
}
canvas.drawArc(new RectF(leftTop, leftTop, bottomRight, bottomRight), startAngle, halfSectorSize * 2.0f, true,
sectorPaint);
}
}
for (int sectorIndex = 0; sectorIndex < alarmStatus.getSectorCount(); sectorIndex++) {
double bearing = alarmStatus.getSectorBearing(sectorIndex);
canvas.drawLine(center, center, center + (float) (radius * Math.sin((bearing + halfSectorSize) / 180.0 * Math.PI)), center
+ (float) (radius * -Math.cos((bearing + halfSectorSize) / 180.0 * Math.PI)), lines);
String text = alarmStatus.getSectorLabel(sectorIndex);
if (!text.equals("O")) {
float textRadius = (AlarmSector.getDistanceLimitCount() - 0.5f) * radiusIncrement;
canvas.drawText(text, center
+ (float) (textRadius * Math.sin(bearing / 180.0 * Math.PI) - lines.measureText(text) / 2.0f), center
+ (float) (textRadius * -Math.cos(bearing / 180.0 * Math.PI)) + lines.getFontMetrics(null) / 2.5f, textStyle);
}
}
for (int distanceIndex = 0; distanceIndex < AlarmSector.getDistanceLimitCount(); distanceIndex++) {
float leftTop = center - (distanceIndex + 1) * radiusIncrement;
float bottomRight = center + (distanceIndex + 1) * radiusIncrement;
canvas.drawArc(new RectF(leftTop, leftTop, bottomRight, bottomRight), 0, 360, false, lines);
String text = String.format("%.0f", AlarmSector.getDistanceLimits()[distanceIndex] / 1000);
canvas.drawText(text, center + (float) (distanceIndex + 0.5f) * radiusIncrement - lines.measureText(text) / 2.0f, center
+ lines.getFontMetrics(null) / 2.5f, textStyle);
}
} else {
Log.v("AlarmView", "onDraw() alarmStatus is not set");
Paint warnText = new Paint();
warnText.setColor(0xffa00000);
warnText.setTextAlign(Align.CENTER);
warnText.setTextSize(20);
warnText.setAntiAlias(true);
String text = getContext().getString(R.string.alarms_not_available);
String textLines[] = text.split("\n");
for (int line=0; line < textLines.length; line++) {
canvas.drawText(textLines[line], center, center + (line - 1) * warnText.getFontMetrics(null), warnText);
}
}
}
@Override
public void onAlarmResult(AlarmStatus alarmStatus) {
this.alarmStatus = alarmStatus;
invalidate();
}
@Override
public void onAlarmClear() {
alarmStatus = null;
}
public void setColorHandler(ColorHandler colorHandler, int minutesPerColor) {
this.colorHandler = colorHandler;
this.minutesPerColor = minutesPerColor;
}
}
|
improved alarmview styling
|
src/org/blitzortung/android/app/view/AlarmView.java
|
improved alarmview styling
|
|
Java
|
apache-2.0
|
0b7220364cf6b5fb7c8d365558c1b6c52b1a82c4
| 0
|
robinverduijn/gradle,robinverduijn/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,blindpirate/gradle,robinverduijn/gradle,lsmaira/gradle,gstevey/gradle,gstevey/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,lsmaira/gradle,gstevey/gradle,blindpirate/gradle,gradle/gradle,gstevey/gradle,robinverduijn/gradle,robinverduijn/gradle,lsmaira/gradle,gradle/gradle,gstevey/gradle,lsmaira/gradle,gradle/gradle,robinverduijn/gradle,gradle/gradle,gradle/gradle,lsmaira/gradle,gstevey/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,gradle/gradle,lsmaira/gradle,gstevey/gradle,lsmaira/gradle,gstevey/gradle,gradle/gradle,gstevey/gradle,lsmaira/gradle,lsmaira/gradle,gradle/gradle,blindpirate/gradle,robinverduijn/gradle
|
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.tasks.compile.incremental.jar;
import org.gradle.api.internal.tasks.compile.incremental.DummySerializer;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class LocalJarSnapshotCache {
//TODO SF this cache should use File -> hash map and retrieve the snapshot from the global cache.
//TODO SF use task-scoped standard caching
private File storage;
private Map<File, JarSnapshot> snapshots;
public LocalJarSnapshotCache(File storage) {
this.storage = storage;
}
public JarSnapshot getSnapshot(File jar) {
init();
return snapshots.get(jar);
}
public void putSnapshots(Map<File, JarSnapshot> newSnapshots) {
init();
this.snapshots.putAll(newSnapshots);
DummySerializer.writeTargetTo(storage, this.snapshots);
}
private void init() {
if (snapshots == null) {
if (storage.isFile()) {
snapshots = (Map) DummySerializer.readFrom(storage);
} else {
snapshots = new HashMap<File, JarSnapshot>();
}
}
}
}
|
subprojects/plugins/src/main/groovy/org/gradle/api/internal/tasks/compile/incremental/jar/LocalJarSnapshotCache.java
|
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.tasks.compile.incremental.jar;
import org.gradle.api.internal.tasks.compile.incremental.DummySerializer;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class LocalJarSnapshotCache {
//TODO SF this cache should no longer be needed
private File storage;
private Map<File, JarSnapshot> snapshots;
public LocalJarSnapshotCache(File storage) {
this.storage = storage;
}
public JarSnapshot getSnapshot(File jar) {
init();
return snapshots.get(jar);
}
public void putSnapshots(Map<File, JarSnapshot> newSnapshots) {
init();
this.snapshots.putAll(newSnapshots);
DummySerializer.writeTargetTo(storage, this.snapshots);
}
private void init() {
if (snapshots == null) {
if (storage.isFile()) {
snapshots = (Map) DummySerializer.readFrom(storage);
} else {
snapshots = new HashMap<File, JarSnapshot>();
}
}
}
}
|
Documented the TODO better.
|
subprojects/plugins/src/main/groovy/org/gradle/api/internal/tasks/compile/incremental/jar/LocalJarSnapshotCache.java
|
Documented the TODO better.
|
|
Java
|
apache-2.0
|
2eb072e03a97967ac5bb8f6aa5cf6f220c48a327
| 0
|
troter/user-httpsession
|
package jp.troter.servlet.httpsession.spi.impl;
import java.io.Serializable;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import jp.troter.servlet.httpsession.spi.SessionStateManager;
import jp.troter.servlet.httpsession.spi.SessionValueSerializer;
import jp.troter.servlet.httpsession.spi.SpyMemcachedInitializer;
import jp.troter.servlet.httpsession.state.DefaultSessionState;
import jp.troter.servlet.httpsession.state.SessionState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SpyMemcachedSessionStateManager extends SessionStateManager {
private static Logger log = LoggerFactory.getLogger(SpyMemcachedSessionStateManager.class);
private static final String KEY_PREFIX = "httpsession";
protected SpyMemcachedInitializer initializer;
protected SessionValueSerializer serializer;
@Override
public SessionState loadState(String sessionId) {
Map<String, Object> attributes = new HashMap<String, Object>();
long lastAccessedTime = new Date().getTime();
try {
Object obj = getSpyMemcachedInitializer().getMemcachedClient().get(key(sessionId));
if (obj == null) { return new DefaultSessionState(attributes, lastAccessedTime); }
Cell cell = (Cell) obj;
attributes.putAll(cell.getAttributes());
lastAccessedTime = cell.getLastAccessedTime();
} catch (RuntimeException e) {
log.warn("Memcached exception occurred at get method. session_id=" + sessionId, e);
removeState(sessionId);
}
return new DefaultSessionState(attributes, lastAccessedTime);
}
@Override
public void saveState(String sessionId, SessionState sessionState) {
Map<String, Object> attributes = new HashMap<String, Object>();
for (Enumeration<?> e = sessionState.getAttributeNames(); e.hasMoreElements();) {
String name = (String)e.nextElement();
Object value = sessionState.getAttribute(name);
if (value == null) { continue; }
attributes.put(name, value);
}
Cell cell = new Cell(attributes, sessionState.getCreationTime());
try {
getSpyMemcachedInitializer().getMemcachedClient().set(key(sessionId), getTimeoutSecond(), cell);
} catch (RuntimeException e) {
log.warn("Memcached exception occurred at set method. session_id=" + sessionId, e);
}
}
@Override
public void removeState(String sessionId) {
try {
getSpyMemcachedInitializer().getMemcachedClient().delete(key(sessionId));
} catch (RuntimeException e) {
log.warn("Memcached exception occurred at delete method. session_id=" + sessionId, e);
}
}
@Override
public int getTimeoutSecond() {
return getSpyMemcachedInitializer().getSessionTimeout();
}
protected String key(String sessionId) {
return KEY_PREFIX + "/" + sessionId;
}
protected SpyMemcachedInitializer getSpyMemcachedInitializer() {
if (initializer == null) {
initializer = SpyMemcachedInitializer.newInstance();
}
return initializer;
}
protected SessionValueSerializer getSessionValueSerializer() {
if (serializer == null) {
serializer = SessionValueSerializer.newInstance();
}
return serializer;
}
protected static class Cell implements Serializable {
private static final long serialVersionUID = 1L;
Map<String, Object> attributes;
long lastAccessedTime;
public Cell(Map<String, Object> attributes, long lastAccessedTime) {
this.attributes = attributes;
this.lastAccessedTime = lastAccessedTime;
}
public Map<String, Object> getAttributes() {
return attributes;
}
public long getLastAccessedTime() {
return lastAccessedTime;
}
}
}
|
user-httpsession-memcached/src/main/java/jp/troter/servlet/httpsession/spi/impl/SpyMemcachedSessionStateManager.java
|
package jp.troter.servlet.httpsession.spi.impl;
import java.io.Serializable;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import jp.troter.servlet.httpsession.spi.SessionStateManager;
import jp.troter.servlet.httpsession.spi.SessionValueSerializer;
import jp.troter.servlet.httpsession.spi.SpyMemcachedInitializer;
import jp.troter.servlet.httpsession.state.DefaultSessionState;
import jp.troter.servlet.httpsession.state.SessionState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SpyMemcachedSessionStateManager extends SessionStateManager {
private static Logger log = LoggerFactory.getLogger(SpyMemcachedSessionStateManager.class);
private static final String KEY_PREFIX = "httpsession";
protected SpyMemcachedInitializer initializer;
protected SessionValueSerializer serializer;
@Override
public SessionState loadState(String sessionId) {
Map<String, Object> attributes = new HashMap<String, Object>();
long lastAccessedTime = new Date().getTime();
try {
Object obj = getSpyMemcachedInitializer().getMemcachedClient().get(key(sessionId));
if (obj == null) { return new DefaultSessionState(attributes); }
Cell cell = (Cell) obj;
attributes.putAll(cell.getAttributes());
lastAccessedTime = cell.getLastAccessedTime();
} catch (RuntimeException e) {
log.warn("Memcached exception occurred at get method. session_id=" + sessionId, e);
removeState(sessionId);
}
return new DefaultSessionState(attributes, lastAccessedTime);
}
@Override
public void saveState(String sessionId, SessionState sessionState) {
Map<String, Object> attributes = new HashMap<String, Object>();
for (Enumeration<?> e = sessionState.getAttributeNames(); e.hasMoreElements();) {
String name = (String)e.nextElement();
Object value = sessionState.getAttribute(name);
if (value == null) { continue; }
attributes.put(name, value);
}
Cell cell = new Cell(attributes, sessionState.getCreationTime());
try {
getSpyMemcachedInitializer().getMemcachedClient().set(key(sessionId), getTimeoutSecond(), cell);
} catch (RuntimeException e) {
log.warn("Memcached exception occurred at set method. session_id=" + sessionId, e);
}
}
@Override
public void removeState(String sessionId) {
try {
getSpyMemcachedInitializer().getMemcachedClient().delete(key(sessionId));
} catch (RuntimeException e) {
log.warn("Memcached exception occurred at delete method. session_id=" + sessionId, e);
}
}
@Override
public int getTimeoutSecond() {
return getSpyMemcachedInitializer().getSessionTimeout();
}
protected String key(String sessionId) {
return KEY_PREFIX + "/" + sessionId;
}
protected SpyMemcachedInitializer getSpyMemcachedInitializer() {
if (initializer == null) {
initializer = SpyMemcachedInitializer.newInstance();
}
return initializer;
}
protected SessionValueSerializer getSessionValueSerializer() {
if (serializer == null) {
serializer = SessionValueSerializer.newInstance();
}
return serializer;
}
protected static class Cell implements Serializable {
private static final long serialVersionUID = 1L;
Map<String, Object> attributes;
long lastAccessedTime;
public Cell(Map<String, Object> attributes, long lastAccessedTime) {
this.attributes = attributes;
this.lastAccessedTime = lastAccessedTime;
}
public Map<String, Object> getAttributes() {
return attributes;
}
public long getLastAccessedTime() {
return lastAccessedTime;
}
}
}
|
lastAccessedTime
|
user-httpsession-memcached/src/main/java/jp/troter/servlet/httpsession/spi/impl/SpyMemcachedSessionStateManager.java
|
lastAccessedTime
|
|
Java
|
apache-2.0
|
5e4a3262e83c86898fa0b84380f8946aa1119448
| 0
|
eevans/twissandra-j
|
package org.opennms.twissandra.persistence.cassandra.internal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.opennms.twissandra.api.Tweet;
import org.opennms.twissandra.api.TweetRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.utils.UUIDs;
public class CassandraTweetRepository implements TweetRepository {
private static final String PUBLIC_USERLINE_KEY = "!PUBLIC!";
private static final Logger LOG = LoggerFactory.getLogger(CassandraTweetRepository.class);
private final String m_cassandraHost;
private final int m_cassandraPort;
private final String m_keyspaceName;
private final Cluster cluster;
private final Session session;
public CassandraTweetRepository(String cassandraHost, int cassandraPort, String keyspaceName) {
m_cassandraHost = cassandraHost;
m_cassandraPort = cassandraPort;
m_keyspaceName = keyspaceName;
LOG.info("Connecting to {}:{}...", cassandraHost, cassandraPort);
cluster = Cluster.builder().withPort(m_cassandraPort).addContactPoint(m_cassandraHost).build();
session = cluster.connect(m_keyspaceName);
LOG.info("Connected.");
}
public String getPassword(String username) {
ResultSet queryResult = execute("SELECT password FROM users WHERE username = '%s'", username);
Row row = getOneRow(queryResult);
return row != null ? row.getString("password") : null;
}
public List<String> getFriends(String username) {
ResultSet queryResult = execute("SELECT followed FROM following WHERE username = '%s'", username);
List<String> friends = new ArrayList<String>();
for (Row row : queryResult)
friends.add(row.getString("followed"));
return friends;
}
public List<String> getFollowers(String username) {
ResultSet queryResult = execute("SELECT following FROM followers WHERE username = '%s'", username);
List<String> followers = new ArrayList<String>();
for (Row row : queryResult)
followers.add(row.getString("following"));
return followers;
}
/** {@inheritDoc} */
public List<Tweet> getUserline(String username, Date start, int limit) {
ResultSet queryResult = execute(
"SELECT posted_at, body FROM userline WHERE username = '%s' AND posted_at < maxTimeuuid('%d') ORDER BY posted_at DESC LIMIT %d",
username,
start.getTime(),
limit);
List<Tweet> tweets = new ArrayList<Tweet>();
for (Row row : queryResult) {
UUID id = row.getUUID("posted_at");
tweets.add(new Tweet(username, row.getString("body"), id, fromUUID1(id)));
}
return tweets;
}
/** {@inheritDoc} */
public List<Tweet> getTimeline(String username, Date start, int limit) {
ResultSet queryResult = execute(
"SELECT posted_at, posted_by, body FROM timeline WHERE username = '%s' AND posted_at < maxTimeuuid('%d') ORDER BY posted_at DESC LIMIT %d",
username,
start.getTime(),
limit);
List<Tweet> tweets = new ArrayList<Tweet>();
for (Row row : queryResult) {
UUID id = row.getUUID("posted_at");
tweets.add(new Tweet(row.getString("posted_by"), row.getString("body"), id, fromUUID1(id)));
}
return tweets;
}
public List<Tweet> getTweets(Date start, int limit) {
return getTimeline(PUBLIC_USERLINE_KEY, start, limit);
}
public Tweet getTweet(UUID id) {
Row row = getOneRow(execute("SELECT username, body FROM tweets WHERE id = %s", id.toString()));
return row != null ? new Tweet(row.getString("username"), row.getString("body"), id, fromUUID1(id)) : null;
}
public void saveUser(String username, String password) {
execute("INSERT INTO users (username, password) VALUES ('%s', '%s')", username , password);
}
public Tweet saveTweet(String username, String body) {
UUID id = UUIDs.timeBased();
// Create the tweet in the tweets cf
execute("INSERT INTO tweets (id, username, body) VALUES (%s, '%s', '%s')",
id.toString(),
username,
body);
// Store the tweet in this users userline
execute("INSERT INTO userline (username, posted_at, body) VALUES ('%s', %s, '%s')",
username,
id.toString(),
body);
// Store the tweet in this users timeline
execute("INSERT INTO timeline (username, posted_at, posted_by, body) VALUES ('%s', %s, '%s', '%s')",
username,
id.toString(),
username,
body);
// Store the tweet in the public timeline
execute("INSERT INTO timeline (username, posted_at, posted_by, body) VALUES ('%s', %s, '%s', '%s')",
PUBLIC_USERLINE_KEY,
id.toString(),
username,
body);
// Insert the tweet into follower timelines
for (String follower : getFollowers(username)) {
execute("INSERT INTO timeline (username, posted_at, posted_by, body) VALUES ('%s', %s, '%s', '%s')",
follower,
id.toString(),
username,
body);
}
return new Tweet(username, body, id, fromUUID1(id));
}
public void addFriend(String username, String friend) {
if (username.equals(friend)) {
LOG.warn("Attempted to self-friend {} (no self-loving here, please).", username);
return;
}
execute("INSERT INTO following (username, followed) VALUES ('%s', '%s')", username, friend);
execute("INSERT INTO followers (username, following) VALUES ('%s', '%s')", friend, username);
}
public void removeFriend(String username, String friend) {
execute("DELETE FROM following WHERE username = '%s' AND followed = '%s'", username, friend);
execute("DELETE FROM followers WHERE username = '%s' AND following = '%s'", friend, username);
}
private Row getOneRow(ResultSet result) {
Row row = result.one();
if (!result.isExhausted())
throw new RuntimeException("ResultSet instance contained more than one row!");
return row;
}
private ResultSet execute(String query, Object...parms) {
String cql = String.format(query, parms);
LOG.debug("Executing CQL: {}", cql);
return session.execute(cql);
}
private Date fromUUID1(UUID uuid) {
assert uuid.version() == 1;
return new Date((uuid.timestamp() / 10000) + -12219292800000L); // -12219292800000L is the start epoch
}
}
|
persistence-cassandra/src/main/java/org/opennms/twissandra/persistence/cassandra/internal/CassandraTweetRepository.java
|
package org.opennms.twissandra.persistence.cassandra.internal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.opennms.twissandra.api.Tweet;
import org.opennms.twissandra.api.TweetRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.utils.UUIDs;
public class CassandraTweetRepository implements TweetRepository {
private static final String PUBLIC_USERLINE_KEY = "!PUBLIC!";
private static final Logger LOG = LoggerFactory.getLogger(CassandraTweetRepository.class);
private final String m_cassandraHost;
private final int m_cassandraPort;
private final String m_keyspaceName;
private final Cluster cluster;
private final Session session;
public CassandraTweetRepository(String cassandraHost, int cassandraPort, String keyspaceName) {
m_cassandraHost = cassandraHost;
m_cassandraPort = cassandraPort;
m_keyspaceName = keyspaceName;
LOG.info("Connecting to {}:{}...", cassandraHost, cassandraPort);
cluster = Cluster.builder().withPort(m_cassandraPort).addContactPoint(m_cassandraHost).build();
session = cluster.connect(m_keyspaceName);
LOG.info("Connected.");
}
public String getPassword(String username) {
ResultSet queryResult = execute("SELECT password FROM users WHERE username = '%s'", username);
Row row = getOneRow(queryResult);
return row != null ? row.getString("password") : null;
}
public List<String> getFriends(String username) {
ResultSet queryResult = execute("SELECT followed FROM following WHERE username = '%s'", username);
List<String> friends = new ArrayList<String>();
for (Row row : queryResult)
friends.add(row.getString("followed"));
return friends;
}
public List<String> getFollowers(String username) {
ResultSet queryResult = execute("SELECT following FROM followers WHERE username = '%s'", username);
List<String> followers = new ArrayList<String>();
for (Row row : queryResult)
followers.add(row.getString("following"));
return followers;
}
/** {@inheritDoc} */
public List<Tweet> getUserline(String username, Date start, int limit) {
ResultSet queryResult = execute(
"SELECT posted_at, body FROM userline WHERE username = '%s' AND posted_at < maxTimeuuid('%s') ORDER BY posted_at DESC LIMIT %d",
username,
formatDate(start),
limit);
List<Tweet> tweets = new ArrayList<Tweet>();
for (Row row : queryResult) {
UUID id = row.getUUID("posted_at");
tweets.add(new Tweet(username, row.getString("body"), id, fromUUID1(id)));
}
return tweets;
}
/** {@inheritDoc} */
public List<Tweet> getTimeline(String username, Date start, int limit) {
ResultSet queryResult = execute(
"SELECT posted_at, posted_by, body FROM timeline WHERE username = '%s' AND posted_at < maxTimeuuid('%s') ORDER BY posted_at DESC LIMIT %d",
username,
formatDate(start),
limit);
List<Tweet> tweets = new ArrayList<Tweet>();
for (Row row : queryResult) {
UUID id = row.getUUID("posted_at");
tweets.add(new Tweet(row.getString("posted_by"), row.getString("body"), id, fromUUID1(id)));
}
return tweets;
}
public List<Tweet> getTweets(Date start, int limit) {
return getTimeline(PUBLIC_USERLINE_KEY, start, limit);
}
public Tweet getTweet(UUID id) {
Row row = getOneRow(execute("SELECT username, body FROM tweets WHERE id = %s", id.toString()));
return row != null ? new Tweet(row.getString("username"), row.getString("body"), id, fromUUID1(id)) : null;
}
public void saveUser(String username, String password) {
execute("INSERT INTO users (username, password) VALUES ('%s', '%s')", username , password);
}
public Tweet saveTweet(String username, String body) {
UUID id = UUIDs.timeBased();
// Create the tweet in the tweets cf
execute("INSERT INTO tweets (id, username, body) VALUES (%s, '%s', '%s')",
id.toString(),
username,
body);
// Store the tweet in this users userline
execute("INSERT INTO userline (username, posted_at, body) VALUES ('%s', %s, '%s')",
username,
id.toString(),
body);
// Store the tweet in this users timeline
execute("INSERT INTO timeline (username, posted_at, posted_by, body) VALUES ('%s', %s, '%s', '%s')",
username,
id.toString(),
username,
body);
// Store the tweet in the public timeline
execute("INSERT INTO timeline (username, posted_at, posted_by, body) VALUES ('%s', %s, '%s', '%s')",
PUBLIC_USERLINE_KEY,
id.toString(),
username,
body);
// Insert the tweet into follower timelines
for (String follower : getFollowers(username)) {
execute("INSERT INTO timeline (username, posted_at, posted_by, body) VALUES ('%s', %s, '%s', '%s')",
follower,
id.toString(),
username,
body);
}
return new Tweet(username, body, id, fromUUID1(id));
}
public void addFriend(String username, String friend) {
if (username.equals(friend)) {
LOG.warn("Attempted to self-friend {} (no self-loving here, please).", username);
return;
}
execute("INSERT INTO following (username, followed) VALUES ('%s', '%s')", username, friend);
execute("INSERT INTO followers (username, following) VALUES ('%s', '%s')", friend, username);
}
public void removeFriend(String username, String friend) {
execute("DELETE FROM following WHERE username = '%s' AND followed = '%s'", username, friend);
execute("DELETE FROM followers WHERE username = '%s' AND following = '%s'", friend, username);
}
private Row getOneRow(ResultSet result) {
Row row = result.one();
if (!result.isExhausted())
throw new RuntimeException("ResultSet instance contained more than one row!");
return row;
}
private ResultSet execute(String query, Object...parms) {
String cql = String.format(query, parms);
LOG.debug("Executing CQL: {}", cql);
return session.execute(cql);
}
private String formatDate(Date date) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
}
private Date fromUUID1(UUID uuid) {
assert uuid.version() == 1;
return new Date((uuid.timestamp() / 10000) + -12219292800000L); // -12219292800000L is the start epoch
}
}
|
use higher resolution date predicate
|
persistence-cassandra/src/main/java/org/opennms/twissandra/persistence/cassandra/internal/CassandraTweetRepository.java
|
use higher resolution date predicate
|
|
Java
|
apache-2.0
|
8c5e6e6ff7d770660bfc06092663f45e136642ca
| 0
|
bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm
|
src/main/java/build/buildfarm/worker/CacheNotFoundException.java
|
// Copyright 2017 The Bazel Authors. 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 build.buildfarm.worker;
import com.google.devtools.remoteexecution.v1test.Digest;
/**
* An exception to indicate cache misses.
*/
public final class CacheNotFoundException extends Exception {
private static final long serialVersionUID = 1;
private final Digest missingDigest;
CacheNotFoundException(Digest missingDigest) {
this.missingDigest = missingDigest;
}
public Digest getMissingDigest() {
return missingDigest;
}
@Override
public String toString() {
return "Missing digest: " + missingDigest;
}
}
|
Remove unused CacheNotFoundException (#125)
This has not been in use since the worker pipeline change.
|
src/main/java/build/buildfarm/worker/CacheNotFoundException.java
|
Remove unused CacheNotFoundException (#125)
|
||
Java
|
apache-2.0
|
1eda00fd3216fc8ecdb811ec69f05f2053a940f8
| 0
|
k000kc/java-a-to-z,k000kc/java-a-to-z,k000kc/java-a-to-z
|
package ru.apetrov;
import org.junit.Test;
import ru.apetrov.Palindrom.Palindrom;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Created by Andrey on 22.11.2016.
*/
public class PalindromTest {
/**
* Тест на метод isPalindrom.
* @throws IOException IOExeption
*/
@Test
public void whenInputWordThenCheckIsPolindrom() {
Palindrom palindrom = new Palindrom();
boolean result = true;
try(InputStream inputStream = new ByteArrayInputStream("КоМок".getBytes());) {
assertThat(palindrom.isPalindrom(inputStream), is(result));
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
Chapter_3/Lesson-1/src/test/java/ru/apetrov/PalindromTest.java
|
package ru.apetrov;
import org.junit.Test;
import ru.apetrov.Palindrom.Palindrom;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Created by Andrey on 22.11.2016.
*/
public class PalindromTest {
/**
* Тест на метод isPalindrom.
* @throws IOException IOExeption
*/
@Test
public void whenInputWordThenCheckIsPolindrom() throws IOException {
Palindrom palindrom = new Palindrom();
InputStream inputStream = new ByteArrayInputStream("КоМок".getBytes());
boolean result = true;
assertThat(palindrom.isPalindrom(inputStream), is(result));
}
}
|
update palindromtest (try resources)
|
Chapter_3/Lesson-1/src/test/java/ru/apetrov/PalindromTest.java
|
update palindromtest (try resources)
|
|
Java
|
apache-2.0
|
b582ca568f9446c8bade41aa841201af4fcb152e
| 0
|
dongjiaqiang/mina,weijiangzhu/mina,yangzhongj/mina,dongjiaqiang/mina,Vicky01200059/mina,Vicky01200059/mina,apache/mina,yangzhongj/mina,mway08/mina,jeffmaury/mina,universsky/mina,apache/mina,weijiangzhu/mina,mway08/mina,universsky/mina
|
/*
* 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.mina.filter.codec;
import java.net.SocketAddress;
import java.util.Queue;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.file.FileRegion;
import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.filterchain.IoFilterChain;
import org.apache.mina.core.future.DefaultWriteFuture;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.DefaultWriteRequest;
import org.apache.mina.core.write.NothingWrittenException;
import org.apache.mina.core.write.WriteRequest;
import org.apache.mina.core.write.WriteRequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An {@link IoFilter} which translates binary or protocol specific data into
* message object and vice versa using {@link ProtocolCodecFactory},
* {@link ProtocolEncoder}, or {@link ProtocolDecoder}.
*
* @author The Apache MINA Project (dev@mina.apache.org)
* @version $Rev$, $Date$
* @org.apache.xbean.XBean
*/
public class ProtocolCodecFilter extends IoFilterAdapter {
private static final Class<?>[] EMPTY_PARAMS = new Class[0];
private static final IoBuffer EMPTY_BUFFER = IoBuffer.wrap(new byte[0]);
private final AttributeKey ENCODER = new AttributeKey(getClass(), "encoder");
private final AttributeKey DECODER = new AttributeKey(getClass(), "decoder");
private final AttributeKey DECODER_OUT = new AttributeKey(getClass(), "decoderOut");
private final AttributeKey ENCODER_OUT = new AttributeKey(getClass(), "encoderOut");
/** The factory responsible for creating the encoder and decoder */
private final ProtocolCodecFactory factory;
private final Logger logger = LoggerFactory.getLogger(getClass());
/**
*
* Creates a new instance of ProtocolCodecFilter, associating a factory
* for the creation of the encoder and decoder.
*
* @param factory The associated factory
*/
public ProtocolCodecFilter(ProtocolCodecFactory factory) {
if (factory == null) {
throw new NullPointerException("factory");
}
this.factory = factory;
}
/**
* Creates a new instance of ProtocolCodecFilter, without any factory.
* The encoder/decoder factory will be created as an inner class, using
* the two parameters (encoder and decoder).
*
* @param encoder The class responsible for encoding the message
* @param decoder The class responsible for decoding the message
*/
public ProtocolCodecFilter(final ProtocolEncoder encoder,
final ProtocolDecoder decoder) {
if (encoder == null) {
throw new NullPointerException("encoder");
}
if (decoder == null) {
throw new NullPointerException("decoder");
}
// Create the inner Factory based on the two parameters
this.factory = new ProtocolCodecFactory() {
public ProtocolEncoder getEncoder(IoSession session) {
return encoder;
}
public ProtocolDecoder getDecoder(IoSession session) {
return decoder;
}
};
}
/**
* Creates a new instance of ProtocolCodecFilter, without any factory.
* The encoder/decoder factory will be created as an inner class, using
* the two parameters (encoder and decoder), which are class names. Instances
* for those classes will be created in this constructor.
*
* @param encoder The class responsible for encoding the message
* @param decoder The class responsible for decoding the message
*/
public ProtocolCodecFilter(
final Class<? extends ProtocolEncoder> encoderClass,
final Class<? extends ProtocolDecoder> decoderClass) {
if (encoderClass == null) {
throw new NullPointerException("encoderClass");
}
if (decoderClass == null) {
throw new NullPointerException("decoderClass");
}
if (!ProtocolEncoder.class.isAssignableFrom(encoderClass)) {
throw new IllegalArgumentException("encoderClass: "
+ encoderClass.getName());
}
if (!ProtocolDecoder.class.isAssignableFrom(decoderClass)) {
throw new IllegalArgumentException("decoderClass: "
+ decoderClass.getName());
}
try {
encoderClass.getConstructor(EMPTY_PARAMS);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(
"encoderClass doesn't have a public default constructor.");
}
try {
decoderClass.getConstructor(EMPTY_PARAMS);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(
"decoderClass doesn't have a public default constructor.");
}
// Create the inner Factory based on the two parameters. We instanciate
// the encoder and decoder locally.
this.factory = new ProtocolCodecFactory() {
public ProtocolEncoder getEncoder(IoSession session) throws Exception {
return encoderClass.newInstance();
}
public ProtocolDecoder getDecoder(IoSession session) throws Exception {
return decoderClass.newInstance();
}
};
}
/**
* Get the encoder instance from a given session.
*
* @param session The associated session we will get the encoder from
* @return The encoder instance, if any
*/
public ProtocolEncoder getEncoder(IoSession session) {
return (ProtocolEncoder) session.getAttribute(ENCODER);
}
@Override
public void onPreAdd(IoFilterChain parent, String name,
NextFilter nextFilter) throws Exception {
if (parent.contains(this)) {
throw new IllegalArgumentException(
"You can't add the same filter instance more than once. Create another instance and add it.");
}
// Initialize the encoder and decoder
initCodec(parent.getSession());
}
@Override
public void onPostRemove(IoFilterChain parent, String name,
NextFilter nextFilter) throws Exception {
// Clean everything
disposeCodec(parent.getSession());
}
/**
* Process the incoming message, calling the session decoder. As the incoming
* buffer might contains more than one messages, we have to loop until the decoder
* throws an exception.
*
* while ( buffer not empty )
* try
* decode ( buffer )
* catch
* break;
*
*/
@Override
public void messageReceived(NextFilter nextFilter, IoSession session,
Object message) throws Exception {
if (!(message instanceof IoBuffer)) {
nextFilter.messageReceived(session, message);
return;
}
IoBuffer in = (IoBuffer) message;
ProtocolDecoder decoder = getDecoder(session);
ProtocolDecoderOutput decoderOut = getDecoderOut(session, nextFilter);
// Loop until we don't have anymore byte in the buffer,
// or until the decoder throws an unrecoverable exception or
// can't decoder a message, because there are not enough
// data in the buffer
while (in.hasRemaining()) {
int oldPos = in.position();
try {
synchronized (decoderOut) {
// Call the decoder with the read bytes
decoder.decode(session, in, decoderOut);
}
// Finish decoding if no exception was thrown.
decoderOut.flush(nextFilter, session);
} catch (Throwable t) {
ProtocolDecoderException pde;
if (t instanceof ProtocolDecoderException) {
pde = (ProtocolDecoderException) t;
} else {
pde = new ProtocolDecoderException(t);
}
if (pde.getHexdump() == null) {
// Generate a message hex dump
int curPos = in.position();
in.position(oldPos);
pde.setHexdump(in.getHexDump());
in.position(curPos);
}
// Fire the exceptionCaught event.
decoderOut.flush(nextFilter, session);
nextFilter.exceptionCaught(session, pde);
// Retry only if the type of the caught exception is
// recoverable and the buffer position has changed.
// We check buffer position additionally to prevent an
// infinite loop.
if (!(t instanceof RecoverableProtocolDecoderException) ||
(in.position() == oldPos)) {
break;
}
}
}
}
@Override
public void messageSent(NextFilter nextFilter, IoSession session,
WriteRequest writeRequest) throws Exception {
if (writeRequest instanceof EncodedWriteRequest) {
return;
}
if (!(writeRequest instanceof MessageWriteRequest)) {
nextFilter.messageSent(session, writeRequest);
return;
}
MessageWriteRequest wrappedRequest = (MessageWriteRequest) writeRequest;
nextFilter.messageSent(session, wrappedRequest.getParentRequest());
}
@Override
public void filterWrite(NextFilter nextFilter, IoSession session,
WriteRequest writeRequest) throws Exception {
Object message = writeRequest.getMessage();
// Bypass the encoding if the message is contained in a ByteBuffer,
// as it has already been encoded before
if (message instanceof IoBuffer || message instanceof FileRegion) {
nextFilter.filterWrite(session, writeRequest);
return;
}
// Get the encoder in the session
ProtocolEncoder encoder = getEncoder(session);
ProtocolEncoderOutput encoderOut = getEncoderOut(session,
nextFilter, writeRequest);
try {
// Now we can try to encode the response
encoder.encode(session, message, encoderOut);
// Send it directly
((ProtocolEncoderOutputImpl)encoderOut).flushWithoutFuture();
// Call the next filter
nextFilter.filterWrite(session, new MessageWriteRequest(
writeRequest));
} catch (Throwable t) {
ProtocolEncoderException pee;
// Generate the correct exception
if (t instanceof ProtocolEncoderException) {
pee = (ProtocolEncoderException) t;
} else {
pee = new ProtocolEncoderException(t);
}
throw pee;
}
}
/**
* Associate a decoder and encoder instances to the newly created session.
* <br>
* <br>
* In order to get the encoder and decoder crea
*
* @param nextFilter The next filter to invoke when having processed the current
* method
* @param session The newly created session
* @throws Exception if we can't create instances of the decoder or encoder
*
@Override
public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception {
// Call the next filter
nextFilter.sessionCreated(session);
}*/
@Override
public void sessionClosed(NextFilter nextFilter, IoSession session)
throws Exception {
// Call finishDecode() first when a connection is closed.
ProtocolDecoder decoder = getDecoder(session);
ProtocolDecoderOutput decoderOut = getDecoderOut(session, nextFilter);
try {
decoder.finishDecode(session, decoderOut);
} catch (Throwable t) {
ProtocolDecoderException pde;
if (t instanceof ProtocolDecoderException) {
pde = (ProtocolDecoderException) t;
} else {
pde = new ProtocolDecoderException(t);
}
throw pde;
} finally {
// Dispose everything
disposeCodec(session);
decoderOut.flush(nextFilter, session);
}
// Call the next filter
nextFilter.sessionClosed(session);
}
private static class EncodedWriteRequest extends DefaultWriteRequest {
private EncodedWriteRequest(Object encodedMessage,
WriteFuture future, SocketAddress destination) {
super(encodedMessage, future, destination);
}
}
private static class MessageWriteRequest extends WriteRequestWrapper {
private MessageWriteRequest(WriteRequest writeRequest) {
super(writeRequest);
}
@Override
public Object getMessage() {
return EMPTY_BUFFER;
}
}
private static class ProtocolDecoderOutputImpl extends
AbstractProtocolDecoderOutput {
public ProtocolDecoderOutputImpl() {
}
public void flush(NextFilter nextFilter, IoSession session) {
Queue<Object> messageQueue = getMessageQueue();
while (!messageQueue.isEmpty()) {
nextFilter.messageReceived(session, messageQueue.poll());
}
}
}
private static class ProtocolEncoderOutputImpl extends
AbstractProtocolEncoderOutput {
private final IoSession session;
private final NextFilter nextFilter;
private final WriteRequest writeRequest;
public ProtocolEncoderOutputImpl(IoSession session,
NextFilter nextFilter, WriteRequest writeRequest) {
this.session = session;
this.nextFilter = nextFilter;
this.writeRequest = writeRequest;
}
public WriteFuture flush() {
Queue<Object> bufferQueue = getMessageQueue();
WriteFuture future = null;
for (;;) {
Object encodedMessage = bufferQueue.poll();
if (encodedMessage == null) {
break;
}
// Flush only when the buffer has remaining.
if (!(encodedMessage instanceof IoBuffer) ||
((IoBuffer) encodedMessage).hasRemaining()) {
future = new DefaultWriteFuture(session);
nextFilter.filterWrite(session, new EncodedWriteRequest(encodedMessage,
future, writeRequest.getDestination()));
}
}
if (future == null) {
future = DefaultWriteFuture.newNotWrittenFuture(
session, new NothingWrittenException(writeRequest));
}
return future;
}
public void flushWithoutFuture() {
Queue<Object> bufferQueue = getMessageQueue();
for (;;) {
Object encodedMessage = bufferQueue.poll();
if (encodedMessage == null) {
break;
}
// Flush only when the buffer has remaining.
if (!(encodedMessage instanceof IoBuffer) ||
((IoBuffer) encodedMessage).hasRemaining()) {
SocketAddress destination = writeRequest.getDestination();
WriteRequest writeRequest = new EncodedWriteRequest(
encodedMessage, null, destination);
nextFilter.filterWrite(session, writeRequest);
}
}
}
}
//----------- Helper methods ---------------------------------------------
/**
* Initialize the encoder and the decoder, storing them in the
* session attributes.
*/
private void initCodec(IoSession session) throws Exception {
// Creates the decoder and stores it into the newly created session
ProtocolDecoder decoder = factory.getDecoder(session);
session.setAttribute(DECODER, decoder);
// Creates the encoder and stores it into the newly created session
ProtocolEncoder encoder = factory.getEncoder(session);
session.setAttribute(ENCODER, encoder);
}
/**
* Dispose the encoder, decoder, and the callback for the decoded
* messages.
*/
private void disposeCodec(IoSession session) {
// We just remove the two instances of encoder/decoder to release resources
// from the session
disposeEncoder(session);
disposeDecoder(session);
// We also remove the callback
disposeDecoderOut(session);
}
/**
* dispose the encoder, removing its instance from the
* session's attributes, and calling the associated
* dispose method.
*/
private void disposeEncoder(IoSession session) {
ProtocolEncoder encoder = (ProtocolEncoder) session
.removeAttribute(ENCODER);
if (encoder == null) {
return;
}
try {
encoder.dispose(session);
} catch (Throwable t) {
logger.warn(
"Failed to dispose: " + encoder.getClass().getName() + " (" + encoder + ')');
}
}
/**
* Get the decoder instance from a given session.
*
* @param session The associated session we will get the decoder from
* @return The decoder instance
*/
private ProtocolDecoder getDecoder(IoSession session) {
return (ProtocolDecoder) session.getAttribute(DECODER);
}
/**
* dispose the decoder, removing its instance from the
* session's attributes, and calling the associated
* dispose method.
*/
private void disposeDecoder(IoSession session) {
ProtocolDecoder decoder = (ProtocolDecoder) session
.removeAttribute(DECODER);
if (decoder == null) {
return;
}
try {
decoder.dispose(session);
} catch (Throwable t) {
logger.warn(
"Falied to dispose: " + decoder.getClass().getName() + " (" + decoder + ')');
}
}
/**
* Return a reference to the decoder callback. If it's not already created
* and stored into the session, we create a new instance.
*/
private ProtocolDecoderOutput getDecoderOut(IoSession session,
NextFilter nextFilter) {
ProtocolDecoderOutput out = (ProtocolDecoderOutput) session.getAttribute(DECODER_OUT);
if (out == null) {
// Create a new instance, and stores it into the session
out = new ProtocolDecoderOutputImpl();
session.setAttribute(DECODER_OUT, out);
}
return out;
}
private ProtocolEncoderOutput getEncoderOut(IoSession session,
NextFilter nextFilter, WriteRequest writeRequest) {
ProtocolEncoderOutput out = (ProtocolEncoderOutput) session.getAttribute(ENCODER_OUT);
if (out == null) {
// Create a new instance, and stores it into the session
out = new ProtocolEncoderOutputImpl(session, nextFilter, writeRequest);
session.setAttribute(ENCODER_OUT, out);
}
return out;
}
/**
* Remove the decoder callback from the session's attributes.
*/
private void disposeDecoderOut(IoSession session) {
session.removeAttribute(DECODER_OUT);
}
}
|
core/src/main/java/org/apache/mina/filter/codec/ProtocolCodecFilter.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.mina.filter.codec;
import java.net.SocketAddress;
import java.util.Queue;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.file.FileRegion;
import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.filterchain.IoFilterChain;
import org.apache.mina.core.future.DefaultWriteFuture;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.DefaultWriteRequest;
import org.apache.mina.core.write.NothingWrittenException;
import org.apache.mina.core.write.WriteRequest;
import org.apache.mina.core.write.WriteRequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An {@link IoFilter} which translates binary or protocol specific data into
* message object and vice versa using {@link ProtocolCodecFactory},
* {@link ProtocolEncoder}, or {@link ProtocolDecoder}.
*
* @author The Apache MINA Project (dev@mina.apache.org)
* @version $Rev$, $Date$
* @org.apache.xbean.XBean
*/
public class ProtocolCodecFilter extends IoFilterAdapter {
private static final Class<?>[] EMPTY_PARAMS = new Class[0];
private static final IoBuffer EMPTY_BUFFER = IoBuffer.wrap(new byte[0]);
private final AttributeKey ENCODER = new AttributeKey(getClass(), "encoder");
private final AttributeKey DECODER = new AttributeKey(getClass(), "decoder");
private final AttributeKey DECODER_OUT = new AttributeKey(getClass(), "decoderOut");
private final AttributeKey ENCODER_OUT = new AttributeKey(getClass(), "encoderOut");
/** The factory responsible for creating the encoder and decoder */
private final ProtocolCodecFactory factory;
private final Logger logger = LoggerFactory.getLogger(getClass());
/**
*
* Creates a new instance of ProtocolCodecFilter, associating a factory
* for the creation of the encoder and decoder.
*
* @param factory The associated factory
*/
public ProtocolCodecFilter(ProtocolCodecFactory factory) {
if (factory == null) {
throw new NullPointerException("factory");
}
this.factory = factory;
}
/**
* Creates a new instance of ProtocolCodecFilter, without any factory.
* The encoder/decoder factory will be created as an inner class, using
* the two parameters (encoder and decoder).
*
* @param encoder The class responsible for encoding the message
* @param decoder The class responsible for decoding the message
*/
public ProtocolCodecFilter(final ProtocolEncoder encoder,
final ProtocolDecoder decoder) {
if (encoder == null) {
throw new NullPointerException("encoder");
}
if (decoder == null) {
throw new NullPointerException("decoder");
}
// Create the inner Factory based on the two parameters
this.factory = new ProtocolCodecFactory() {
public ProtocolEncoder getEncoder(IoSession session) {
return encoder;
}
public ProtocolDecoder getDecoder(IoSession session) {
return decoder;
}
};
}
/**
* Creates a new instance of ProtocolCodecFilter, without any factory.
* The encoder/decoder factory will be created as an inner class, using
* the two parameters (encoder and decoder), which are class names. Instances
* for those classes will be created in this constructor.
*
* @param encoder The class responsible for encoding the message
* @param decoder The class responsible for decoding the message
*/
public ProtocolCodecFilter(
final Class<? extends ProtocolEncoder> encoderClass,
final Class<? extends ProtocolDecoder> decoderClass) {
if (encoderClass == null) {
throw new NullPointerException("encoderClass");
}
if (decoderClass == null) {
throw new NullPointerException("decoderClass");
}
if (!ProtocolEncoder.class.isAssignableFrom(encoderClass)) {
throw new IllegalArgumentException("encoderClass: "
+ encoderClass.getName());
}
if (!ProtocolDecoder.class.isAssignableFrom(decoderClass)) {
throw new IllegalArgumentException("decoderClass: "
+ decoderClass.getName());
}
try {
encoderClass.getConstructor(EMPTY_PARAMS);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(
"encoderClass doesn't have a public default constructor.");
}
try {
decoderClass.getConstructor(EMPTY_PARAMS);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(
"decoderClass doesn't have a public default constructor.");
}
// Create the inner Factory based on the two parameters. We instanciate
// the encoder and decoder locally.
this.factory = new ProtocolCodecFactory() {
public ProtocolEncoder getEncoder(IoSession session) throws Exception {
return encoderClass.newInstance();
}
public ProtocolDecoder getDecoder(IoSession session) throws Exception {
return decoderClass.newInstance();
}
};
}
/**
* Get the encoder instance from a given session.
*
* @param session The associated session we will get the encoder from
* @return The encoder instance, if any
*/
public ProtocolEncoder getEncoder(IoSession session) {
return (ProtocolEncoder) session.getAttribute(ENCODER);
}
@Override
public void onPreAdd(IoFilterChain parent, String name,
NextFilter nextFilter) throws Exception {
if (parent.contains(this)) {
throw new IllegalArgumentException(
"You can't add the same filter instance more than once. Create another instance and add it.");
}
// Initialize the encoder and decoder
initCodec(parent.getSession());
}
@Override
public void onPostRemove(IoFilterChain parent, String name,
NextFilter nextFilter) throws Exception {
// Clean everything
disposeCodec(parent.getSession());
}
/**
* Process the incoming message, calling the session decoder. As the incoming
* buffer might contains more than one messages, we have to loop until the decoder
* throws an exception.
*
* while ( buffer not empty )
* try
* decode ( buffer )
* catch
* break;
*
*/
@Override
public void messageReceived(NextFilter nextFilter, IoSession session,
Object message) throws Exception {
if (!(message instanceof IoBuffer)) {
nextFilter.messageReceived(session, message);
return;
}
IoBuffer in = (IoBuffer) message;
ProtocolDecoder decoder = getDecoder(session);
ProtocolDecoderOutput decoderOut = getDecoderOut(session, nextFilter);
// Loop until we don't have anymore byte in the buffer,
// or until the decoder throws an unrecoverable exception or
// can't decoder a message, because there are not enough
// data in the buffer
while (in.hasRemaining()) {
int oldPos = in.position();
try {
synchronized (decoderOut) {
// Call the decoder with the read bytes
decoder.decode(session, in, decoderOut);
}
// Finish decoding if no exception was thrown.
decoderOut.flush(nextFilter, session);
} catch (Throwable t) {
ProtocolDecoderException pde;
if (t instanceof ProtocolDecoderException) {
pde = (ProtocolDecoderException) t;
} else {
pde = new ProtocolDecoderException(t);
}
if (pde.getHexdump() == null) {
// Generate a message hex dump
int curPos = in.position();
in.position(oldPos);
pde.setHexdump(in.getHexDump());
in.position(curPos);
}
// Fire the exceptionCaught event.
decoderOut.flush(nextFilter, session);
nextFilter.exceptionCaught(session, pde);
// Retry only if the type of the caught exception is
// recoverable and the buffer position has changed.
// We check buffer position additionally to prevent an
// infinite loop.
if (!(t instanceof RecoverableProtocolDecoderException) ||
(in.position() == oldPos)) {
break;
}
}
}
}
@Override
public void messageSent(NextFilter nextFilter, IoSession session,
WriteRequest writeRequest) throws Exception {
if (writeRequest instanceof EncodedWriteRequest) {
return;
}
if (!(writeRequest instanceof MessageWriteRequest)) {
nextFilter.messageSent(session, writeRequest);
return;
}
MessageWriteRequest wrappedRequest = (MessageWriteRequest) writeRequest;
nextFilter.messageSent(session, wrappedRequest.getParentRequest());
}
@Override
public void filterWrite(NextFilter nextFilter, IoSession session,
WriteRequest writeRequest) throws Exception {
Object message = writeRequest.getMessage();
// Bypass the encoding if the message is contained in a ByteBuffer,
// as it has already been encoded before
if (message instanceof IoBuffer || message instanceof FileRegion) {
nextFilter.filterWrite(session, writeRequest);
return;
}
// Get the encoder in the session
ProtocolEncoder encoder = getEncoder(session);
ProtocolEncoderOutput encoderOut = getEncoderOut(session,
nextFilter, writeRequest);
try {
// Now we can try to encode the response
encoder.encode(session, message, encoderOut);
// Send it directly
((ProtocolEncoderOutputImpl)encoderOut).flushWithoutFuture();
// Call the next filter
nextFilter.filterWrite(session, new MessageWriteRequest(
writeRequest));
} catch (Throwable t) {
ProtocolEncoderException pee;
// Generate the correct exception
if (t instanceof ProtocolEncoderException) {
pee = (ProtocolEncoderException) t;
} else {
pee = new ProtocolEncoderException(t);
}
throw pee;
}
}
/**
* Associate a decoder and encoder instances to the newly created session.
* <br>
* <br>
* In order to get the encoder and decoder crea
*
* @param nextFilter The next filter to invoke when having processed the current
* method
* @param session The newly created session
* @throws Exception if we can't create instances of the decoder or encoder
*/
@Override
public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception {
// Initialized the encoder and decoder
initCodec(session);
// Call the next filter
nextFilter.sessionCreated(session);
}
@Override
public void sessionClosed(NextFilter nextFilter, IoSession session)
throws Exception {
// Call finishDecode() first when a connection is closed.
ProtocolDecoder decoder = getDecoder(session);
ProtocolDecoderOutput decoderOut = getDecoderOut(session, nextFilter);
try {
decoder.finishDecode(session, decoderOut);
} catch (Throwable t) {
ProtocolDecoderException pde;
if (t instanceof ProtocolDecoderException) {
pde = (ProtocolDecoderException) t;
} else {
pde = new ProtocolDecoderException(t);
}
throw pde;
} finally {
// Dispose everything
disposeCodec(session);
decoderOut.flush(nextFilter, session);
}
// Call the next filter
nextFilter.sessionClosed(session);
}
private static class EncodedWriteRequest extends DefaultWriteRequest {
private EncodedWriteRequest(Object encodedMessage,
WriteFuture future, SocketAddress destination) {
super(encodedMessage, future, destination);
}
}
private static class MessageWriteRequest extends WriteRequestWrapper {
private MessageWriteRequest(WriteRequest writeRequest) {
super(writeRequest);
}
@Override
public Object getMessage() {
return EMPTY_BUFFER;
}
}
private static class ProtocolDecoderOutputImpl extends
AbstractProtocolDecoderOutput {
public ProtocolDecoderOutputImpl() {
}
public void flush(NextFilter nextFilter, IoSession session) {
Queue<Object> messageQueue = getMessageQueue();
while (!messageQueue.isEmpty()) {
nextFilter.messageReceived(session, messageQueue.poll());
}
}
}
private static class ProtocolEncoderOutputImpl extends
AbstractProtocolEncoderOutput {
private final IoSession session;
private final NextFilter nextFilter;
private final WriteRequest writeRequest;
public ProtocolEncoderOutputImpl(IoSession session,
NextFilter nextFilter, WriteRequest writeRequest) {
this.session = session;
this.nextFilter = nextFilter;
this.writeRequest = writeRequest;
}
public WriteFuture flush() {
Queue<Object> bufferQueue = getMessageQueue();
WriteFuture future = null;
for (;;) {
Object encodedMessage = bufferQueue.poll();
if (encodedMessage == null) {
break;
}
// Flush only when the buffer has remaining.
if (!(encodedMessage instanceof IoBuffer) ||
((IoBuffer) encodedMessage).hasRemaining()) {
future = new DefaultWriteFuture(session);
nextFilter.filterWrite(session, new EncodedWriteRequest(encodedMessage,
future, writeRequest.getDestination()));
}
}
if (future == null) {
future = DefaultWriteFuture.newNotWrittenFuture(
session, new NothingWrittenException(writeRequest));
}
return future;
}
public void flushWithoutFuture() {
Queue<Object> bufferQueue = getMessageQueue();
for (;;) {
Object encodedMessage = bufferQueue.poll();
if (encodedMessage == null) {
break;
}
// Flush only when the buffer has remaining.
if (!(encodedMessage instanceof IoBuffer) ||
((IoBuffer) encodedMessage).hasRemaining()) {
SocketAddress destination = writeRequest.getDestination();
WriteRequest writeRequest = new EncodedWriteRequest(
encodedMessage, null, destination);
nextFilter.filterWrite(session, writeRequest);
}
}
}
}
//----------- Helper methods ---------------------------------------------
/**
* Initialize the encoder and the decoder, storing them in the
* session attributes.
*/
private void initCodec(IoSession session) throws Exception {
// Creates the decoder and stores it into the newly created session
ProtocolDecoder decoder = factory.getDecoder(session);
session.setAttribute(DECODER, decoder);
// Creates the encoder and stores it into the newly created session
ProtocolEncoder encoder = factory.getEncoder(session);
session.setAttribute(ENCODER, encoder);
}
/**
* Dispose the encoder, decoder, and the callback for the decoded
* messages.
*/
private void disposeCodec(IoSession session) {
// We just remove the two instances of encoder/decoder to release resources
// from the session
disposeEncoder(session);
disposeDecoder(session);
// We also remove the callback
disposeDecoderOut(session);
}
/**
* dispose the encoder, removing its instance from the
* session's attributes, and calling the associated
* dispose method.
*/
private void disposeEncoder(IoSession session) {
ProtocolEncoder encoder = (ProtocolEncoder) session
.removeAttribute(ENCODER);
if (encoder == null) {
return;
}
try {
encoder.dispose(session);
} catch (Throwable t) {
logger.warn(
"Failed to dispose: " + encoder.getClass().getName() + " (" + encoder + ')');
}
}
/**
* Get the decoder instance from a given session.
*
* @param session The associated session we will get the decoder from
* @return The decoder instance
*/
private ProtocolDecoder getDecoder(IoSession session) {
return (ProtocolDecoder) session.getAttribute(DECODER);
}
/**
* dispose the decoder, removing its instance from the
* session's attributes, and calling the associated
* dispose method.
*/
private void disposeDecoder(IoSession session) {
ProtocolDecoder decoder = (ProtocolDecoder) session
.removeAttribute(DECODER);
if (decoder == null) {
return;
}
try {
decoder.dispose(session);
} catch (Throwable t) {
logger.warn(
"Falied to dispose: " + decoder.getClass().getName() + " (" + decoder + ')');
}
}
/**
* Return a reference to the decoder callback. If it's not already created
* and stored into the session, we create a new instance.
*/
private ProtocolDecoderOutput getDecoderOut(IoSession session,
NextFilter nextFilter) {
ProtocolDecoderOutput out = (ProtocolDecoderOutput) session.getAttribute(DECODER_OUT);
if (out == null) {
// Create a new instance, and stores it into the session
out = new ProtocolDecoderOutputImpl();
session.setAttribute(DECODER_OUT, out);
}
return out;
}
private ProtocolEncoderOutput getEncoderOut(IoSession session,
NextFilter nextFilter, WriteRequest writeRequest) {
ProtocolEncoderOutput out = (ProtocolEncoderOutput) session.getAttribute(ENCODER_OUT);
if (out == null) {
// Create a new instance, and stores it into the session
out = new ProtocolEncoderOutputImpl(session, nextFilter, writeRequest);
session.setAttribute(ENCODER_OUT, out);
}
return out;
}
/**
* Remove the decoder callback from the session's attributes.
*/
private void disposeDecoderOut(IoSession session) {
session.removeAttribute(DECODER_OUT);
}
}
|
Removed the sessionCreated() method, as the codec is now initialized in the preAdd() method. As a side effect, the codec is initialized only once now, instead of twice before...
git-svn-id: b7022df5c975f24f6cce374a8cf09e1bba3b7a2e@755166 13f79535-47bb-0310-9956-ffa450edef68
|
core/src/main/java/org/apache/mina/filter/codec/ProtocolCodecFilter.java
|
Removed the sessionCreated() method, as the codec is now initialized in the preAdd() method. As a side effect, the codec is initialized only once now, instead of twice before...
|
|
Java
|
apache-2.0
|
767259d6111e7d8a27399cbeca4483b7c6ad9107
| 0
|
ShortStickBoy/AndroidUtil
|
package com.sunzn.utils.library;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import static android.content.ContentValues.TAG;
public class FileUtils {
private FileUtils() {
throw new RuntimeException("Stub!");
}
/**
* ╔════════════════════════════════════════════════════════════════════════════════════════════
* ║ 名称:获取文件扩展名
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 参数:file
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 返回:String
* ╚════════════════════════════════════════════════════════════════════════════════════════════
*/
public static String getExtensionName(File file) {
if (file != null && file.exists()) {
String fileName = file.getName();
return fileName.substring(fileName.lastIndexOf(".") + 1);
} else {
return StringUtils.NULL;
}
}
/**
* ╔════════════════════════════════════════════════════════════════════════════════════════════
* ║ 名称:保存图片到相册
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 参数:context 上下文
* ║ 参数:bmp 位图
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 返回:void
* ╚════════════════════════════════════════════════════════════════════════════════════════════
*/
public static String saveImageToGallery(Context context, Bitmap bmp) {
return saveImageToGallery(context, "DCIM", bmp);
}
/**
* ╔════════════════════════════════════════════════════════════════════════════════════════════
* ║ 名称:保存图片到相册
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 参数:context 上下文
* ║ 参数:child 子目录
* ║ 参数:bmp 位图
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 返回:void
* ╚════════════════════════════════════════════════════════════════════════════════════════════
*/
public static String saveImageToGallery(Context context, String child, Bitmap bmp) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
String fileName = System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION, "");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.IS_PENDING, 1);
values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/Dian/");
Uri url = null;
String stringUrl = null; /* value to be returned */
ContentResolver resolver = context.getContentResolver();
try {
Uri uri = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
url = resolver.insert(uri, values);
if (url == null) {
return null;
}
ParcelFileDescriptor parcelFileDescriptor = resolver.openFileDescriptor(url, "w");
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor.getFileDescriptor());
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
values.clear();
values.put(MediaStore.Images.Media.IS_PENDING, 0);
resolver.update(url, values, null, null);
ToastUtils.success(context, "保存成功");
} catch (Exception e) {
Log.e(TAG, "Failed to insert media file", e);
if (url != null) {
resolver.delete(url, null, null);
url = null;
}
ToastUtils.failure(context, "保存失败");
}
if (url != null) {
stringUrl = url.toString();
}
return stringUrl;
} else {
// 首先保存图片
File appDir = new File(Environment.getExternalStorageDirectory(), child);
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
ToastUtils.success(context, "保存成功");
} catch (FileNotFoundException e) {
ToastUtils.failure(context, "保存失败");
e.printStackTrace();
}
// 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(appDir.getPath()))));
return file.getAbsolutePath();
}
}
/**
* ╔════════════════════════════════════════════════════════════════════════════════════════════
* ║ 名称:执行文件到文件的拷贝
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 参数:srcFile 源文件
* ║ 参数:destFile 目标文件
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 返回:boolean 成功:true 失败:false
* ╚════════════════════════════════════════════════════════════════════════════════════════════
*/
public static boolean copyFile(File srcFile, File destFile) {
boolean result;
try {
try (InputStream in = new FileInputStream(srcFile)) {
result = saveToFile(in, destFile);
}
} catch (IOException e) {
result = false;
}
return result;
}
/**
* ╔════════════════════════════════════════════════════════════════════════════════════════════
* ║ 名称:输入流输出到目标文件
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 参数:inputStream 输入流
* ║ 参数:destFile 目标文件
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 返回:boolean 成功:true 失败:false
* ╚════════════════════════════════════════════════════════════════════════════════════════════
*/
public static boolean saveToFile(InputStream inputStream, File destFile) {
try {
if (destFile.exists()) {
destFile.delete();
}
FileOutputStream out = new FileOutputStream(destFile);
try {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) >= 0) {
out.write(buffer, 0, bytesRead);
}
} finally {
out.flush();
try {
out.getFD().sync();
} catch (IOException e) {
e.printStackTrace();
}
out.close();
}
return true;
} catch (IOException e) {
return false;
}
}
}
|
Library/src/main/java/com/sunzn/utils/library/FileUtils.java
|
package com.sunzn.utils.library;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import static android.content.ContentValues.TAG;
public class FileUtils {
private FileUtils() {
throw new RuntimeException("Stub!");
}
/**
* ╔════════════════════════════════════════════════════════════════════════════════════════════
* ║ 名称:获取文件扩展名
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 参数:file
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 返回:String
* ╚════════════════════════════════════════════════════════════════════════════════════════════
*/
public static String getExtensionName(File file) {
if (file != null && file.exists()) {
String fileName = file.getName();
return fileName.substring(fileName.lastIndexOf(".") + 1);
} else {
return StringUtils.NULL;
}
}
/**
* ╔════════════════════════════════════════════════════════════════════════════════════════════
* ║ 名称:保存图片到相册
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 参数:context 上下文
* ║ 参数:bmp 位图
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 返回:void
* ╚════════════════════════════════════════════════════════════════════════════════════════════
*/
public static String saveImageToGallery(Context context, Bitmap bmp) {
return saveImageToGallery(context, "DCIM", bmp);
}
/**
* ╔════════════════════════════════════════════════════════════════════════════════════════════
* ║ 名称:保存图片到相册
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 参数:context 上下文
* ║ 参数:child 子目录
* ║ 参数:bmp 位图
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 返回:void
* ╚════════════════════════════════════════════════════════════════════════════════════════════
*/
public static String saveImageToGallery(Context context, String child, Bitmap bmp) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
String fileName = System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION, "");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.IS_PENDING, 1);
values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/Dian/");
Uri url = null;
String stringUrl = null; /* value to be returned */
ContentResolver resolver = context.getContentResolver();
try {
Uri uri = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
url = resolver.insert(uri, values);
if (url == null) {
return null;
}
ParcelFileDescriptor parcelFileDescriptor = resolver.openFileDescriptor(url, "w");
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor.getFileDescriptor());
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
values.clear();
values.put(MediaStore.Images.Media.IS_PENDING, 0);
resolver.update(url, values, null, null);
ToastUtils.success(context, "保存成功");
} catch (Exception e) {
Log.e(TAG, "Failed to insert media file", e);
if (url != null) {
resolver.delete(url, null, null);
url = null;
}
ToastUtils.failure(context, "保存失败");
}
if (url != null) {
stringUrl = url.toString();
}
return stringUrl;
} else {
// 首先保存图片
File appDir = new File(Environment.getExternalStorageDirectory(), child);
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
ToastUtils.success(context, "保存成功");
} catch (FileNotFoundException e) {
ToastUtils.failure(context, "保存失败");
e.printStackTrace();
}
// 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(appDir.getPath()))));
return file.getAbsolutePath();
}
}
}
|
Update FileUtils
|
Library/src/main/java/com/sunzn/utils/library/FileUtils.java
|
Update FileUtils
|
|
Java
|
apache-2.0
|
d379da1034b0b71eaf6589c4d75a638ad8df6ea9
| 0
|
rozza/mongo-java-driver,rozza/mongo-java-driver,jyemin/mongo-java-driver,jyemin/mongo-java-driver
|
/*
* Copyright 2008-present MongoDB, 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.mongodb.internal.session;
import com.mongodb.MongoException;
import com.mongodb.ReadPreference;
import com.mongodb.ServerApi;
import com.mongodb.connection.ServerDescription;
import com.mongodb.internal.IgnorableRequestContext;
import com.mongodb.internal.connection.Cluster;
import com.mongodb.internal.connection.ConcurrentPool;
import com.mongodb.internal.connection.ConcurrentPool.Prune;
import com.mongodb.internal.connection.Connection;
import com.mongodb.internal.connection.NoOpSessionContext;
import com.mongodb.internal.selector.ReadPreferenceServerSelector;
import com.mongodb.internal.validator.NoOpFieldNameValidator;
import com.mongodb.lang.Nullable;
import com.mongodb.session.ServerSession;
import org.bson.BsonArray;
import org.bson.BsonBinary;
import org.bson.BsonDocument;
import org.bson.BsonDocumentWriter;
import org.bson.UuidRepresentation;
import org.bson.codecs.BsonDocumentCodec;
import org.bson.codecs.EncoderContext;
import org.bson.codecs.UuidCodec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import static com.mongodb.assertions.Assertions.isTrue;
import static com.mongodb.internal.connection.ConcurrentPool.INFINITE_SIZE;
import static java.util.concurrent.TimeUnit.MINUTES;
public class ServerSessionPool {
private static final int END_SESSIONS_BATCH_SIZE = 10000;
private final ConcurrentPool<ServerSessionImpl> serverSessionPool =
new ConcurrentPool<>(INFINITE_SIZE, new ServerSessionItemFactory());
private final Cluster cluster;
private final ServerSessionPool.Clock clock;
private volatile boolean closing;
private volatile boolean closed;
private final List<BsonDocument> closedSessionIdentifiers = new ArrayList<>();
@Nullable
private final ServerApi serverApi;
interface Clock {
long millis();
}
public ServerSessionPool(final Cluster cluster, @Nullable final ServerApi serverApi) {
this(cluster, serverApi, System::currentTimeMillis);
}
public ServerSessionPool(final Cluster cluster, @Nullable final ServerApi serverApi, final Clock clock) {
this.cluster = cluster;
this.serverApi = serverApi;
this.clock = clock;
}
public ServerSession get() {
isTrue("server session pool is open", !closed);
ServerSessionImpl serverSession = serverSessionPool.get();
while (shouldPrune(serverSession)) {
serverSessionPool.release(serverSession, true);
serverSession = serverSessionPool.get();
}
return serverSession;
}
public void release(final ServerSession serverSession) {
serverSessionPool.release((ServerSessionImpl) serverSession);
serverSessionPool.prune();
}
public void close() {
try {
closing = true;
serverSessionPool.close();
List<BsonDocument> identifiers;
synchronized (this) {
identifiers = new ArrayList<>(closedSessionIdentifiers);
closedSessionIdentifiers.clear();
}
endClosedSessions(identifiers);
} finally {
closed = true;
}
}
public int getInUseCount() {
return serverSessionPool.getInUseCount();
}
private void closeSession(final ServerSessionImpl serverSession) {
serverSession.close();
// only track closed sessions when pool is in the process of closing
if (!closing) {
return;
}
List<BsonDocument> identifiers = null;
synchronized (this) {
closedSessionIdentifiers.add(serverSession.getIdentifier());
if (closedSessionIdentifiers.size() == END_SESSIONS_BATCH_SIZE) {
identifiers = new ArrayList<>(closedSessionIdentifiers);
closedSessionIdentifiers.clear();
}
}
if (identifiers != null) {
endClosedSessions(identifiers);
}
}
private void endClosedSessions(final List<BsonDocument> identifiers) {
if (identifiers.isEmpty()) {
return;
}
List<ServerDescription> primaryPreferred = new ReadPreferenceServerSelector(ReadPreference.primaryPreferred())
.select(cluster.getCurrentDescription());
if (primaryPreferred.isEmpty()) {
return;
}
Connection connection = null;
try {
connection = cluster.selectServer(clusterDescription -> {
for (ServerDescription cur : clusterDescription.getServerDescriptions()) {
if (cur.getAddress().equals(primaryPreferred.get(0).getAddress())) {
return Collections.singletonList(cur);
}
}
return Collections.emptyList();
}).getServer().getConnection();
connection.command("admin",
new BsonDocument("endSessions", new BsonArray(identifiers)), new NoOpFieldNameValidator(),
ReadPreference.primaryPreferred(), new BsonDocumentCodec(), NoOpSessionContext.INSTANCE, serverApi,
IgnorableRequestContext.INSTANCE);
} catch (MongoException e) {
// ignore exceptions
} finally {
if (connection != null) {
connection.release();
}
}
}
private boolean shouldPrune(final ServerSessionImpl serverSession) {
Integer logicalSessionTimeoutMinutes = cluster.getCurrentDescription().getLogicalSessionTimeoutMinutes();
// if the server no longer supports sessions, prune the session
if (logicalSessionTimeoutMinutes == null) {
return false;
}
if (serverSession.isMarkedDirty()) {
return true;
}
long currentTimeMillis = clock.millis();
long timeSinceLastUse = currentTimeMillis - serverSession.getLastUsedAtMillis();
long oneMinuteFromTimeout = MINUTES.toMillis(logicalSessionTimeoutMinutes - 1);
return timeSinceLastUse > oneMinuteFromTimeout;
}
final class ServerSessionImpl implements ServerSession {
private final BsonDocument identifier;
private long transactionNumber = 0;
private volatile long lastUsedAtMillis = clock.millis();
private volatile boolean closed;
private volatile boolean dirty = false;
ServerSessionImpl(final BsonBinary identifier) {
this.identifier = new BsonDocument("id", identifier);
}
void close() {
closed = true;
}
long getLastUsedAtMillis() {
return lastUsedAtMillis;
}
@Override
public long getTransactionNumber() {
return transactionNumber;
}
@Override
public BsonDocument getIdentifier() {
lastUsedAtMillis = clock.millis();
return identifier;
}
@Override
public long advanceTransactionNumber() {
transactionNumber++;
return transactionNumber;
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public void markDirty() {
dirty = true;
}
@Override
public boolean isMarkedDirty() {
return dirty;
}
}
private final class ServerSessionItemFactory implements ConcurrentPool.ItemFactory<ServerSessionImpl> {
@Override
public ServerSessionImpl create() {
return new ServerSessionImpl(createNewServerSessionIdentifier());
}
@Override
public void close(final ServerSessionImpl serverSession) {
closeSession(serverSession);
}
@Override
public Prune shouldPrune(final ServerSessionImpl serverSession) {
return ServerSessionPool.this.shouldPrune(serverSession) ? Prune.YES : Prune.STOP;
}
private BsonBinary createNewServerSessionIdentifier() {
UuidCodec uuidCodec = new UuidCodec(UuidRepresentation.STANDARD);
BsonDocument holder = new BsonDocument();
BsonDocumentWriter bsonDocumentWriter = new BsonDocumentWriter(holder);
bsonDocumentWriter.writeStartDocument();
bsonDocumentWriter.writeName("id");
uuidCodec.encode(bsonDocumentWriter, UUID.randomUUID(), EncoderContext.builder().build());
bsonDocumentWriter.writeEndDocument();
return holder.getBinary("id");
}
}
}
|
driver-core/src/main/com/mongodb/internal/session/ServerSessionPool.java
|
/*
* Copyright 2008-present MongoDB, 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.mongodb.internal.session;
import com.mongodb.MongoException;
import com.mongodb.ReadPreference;
import com.mongodb.ServerApi;
import com.mongodb.connection.ClusterDescription;
import com.mongodb.connection.ServerDescription;
import com.mongodb.internal.IgnorableRequestContext;
import com.mongodb.internal.connection.Cluster;
import com.mongodb.internal.connection.ConcurrentPool;
import com.mongodb.internal.connection.ConcurrentPool.Prune;
import com.mongodb.internal.connection.Connection;
import com.mongodb.internal.connection.NoOpSessionContext;
import com.mongodb.internal.selector.ReadPreferenceServerSelector;
import com.mongodb.internal.validator.NoOpFieldNameValidator;
import com.mongodb.lang.Nullable;
import com.mongodb.selector.ServerSelector;
import com.mongodb.session.ServerSession;
import org.bson.BsonArray;
import org.bson.BsonBinary;
import org.bson.BsonDocument;
import org.bson.BsonDocumentWriter;
import org.bson.UuidRepresentation;
import org.bson.codecs.BsonDocumentCodec;
import org.bson.codecs.EncoderContext;
import org.bson.codecs.UuidCodec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import static com.mongodb.assertions.Assertions.isTrue;
import static com.mongodb.internal.connection.ConcurrentPool.INFINITE_SIZE;
import static java.util.concurrent.TimeUnit.MINUTES;
public class ServerSessionPool {
private static final int END_SESSIONS_BATCH_SIZE = 10000;
private final ConcurrentPool<ServerSessionImpl> serverSessionPool =
new ConcurrentPool<>(INFINITE_SIZE, new ServerSessionItemFactory());
private final Cluster cluster;
private final ServerSessionPool.Clock clock;
private volatile boolean closing;
private volatile boolean closed;
private final List<BsonDocument> closedSessionIdentifiers = new ArrayList<BsonDocument>();
@Nullable
private final ServerApi serverApi;
interface Clock {
long millis();
}
public ServerSessionPool(final Cluster cluster, @Nullable final ServerApi serverApi) {
this(cluster, serverApi, System::currentTimeMillis);
}
public ServerSessionPool(final Cluster cluster, @Nullable final ServerApi serverApi, final Clock clock) {
this.cluster = cluster;
this.serverApi = serverApi;
this.clock = clock;
}
public ServerSession get() {
isTrue("server session pool is open", !closed);
ServerSessionImpl serverSession = serverSessionPool.get();
while (shouldPrune(serverSession)) {
serverSessionPool.release(serverSession, true);
serverSession = serverSessionPool.get();
}
return serverSession;
}
public void release(final ServerSession serverSession) {
serverSessionPool.release((ServerSessionImpl) serverSession);
serverSessionPool.prune();
}
public void close() {
try {
closing = true;
serverSessionPool.close();
List<BsonDocument> identifiers;
synchronized (this) {
identifiers = new ArrayList<BsonDocument>(closedSessionIdentifiers);
closedSessionIdentifiers.clear();
}
endClosedSessions(identifiers);
} finally {
closed = true;
}
}
public int getInUseCount() {
return serverSessionPool.getInUseCount();
}
private void closeSession(final ServerSessionImpl serverSession) {
serverSession.close();
// only track closed sessions when pool is in the process of closing
if (!closing) {
return;
}
List<BsonDocument> identifiers = null;
synchronized (this) {
closedSessionIdentifiers.add(serverSession.getIdentifier());
if (closedSessionIdentifiers.size() == END_SESSIONS_BATCH_SIZE) {
identifiers = new ArrayList<BsonDocument>(closedSessionIdentifiers);
closedSessionIdentifiers.clear();
}
}
if (identifiers != null) {
endClosedSessions(identifiers);
}
}
private void endClosedSessions(final List<BsonDocument> identifiers) {
if (identifiers.isEmpty()) {
return;
}
List<ServerDescription> primaryPreferred = new ReadPreferenceServerSelector(ReadPreference.primaryPreferred())
.select(cluster.getCurrentDescription());
if (primaryPreferred.isEmpty()) {
return;
}
Connection connection = null;
try {
connection = cluster.selectServer(new ServerSelector() {
@Override
public List<ServerDescription> select(final ClusterDescription clusterDescription) {
for (ServerDescription cur : clusterDescription.getServerDescriptions()) {
if (cur.getAddress().equals(primaryPreferred.get(0).getAddress())) {
return Collections.singletonList(cur);
}
}
return Collections.emptyList();
}
}).getServer().getConnection();
connection.command("admin",
new BsonDocument("endSessions", new BsonArray(identifiers)), new NoOpFieldNameValidator(),
ReadPreference.primaryPreferred(), new BsonDocumentCodec(), NoOpSessionContext.INSTANCE, serverApi,
IgnorableRequestContext.INSTANCE);
} catch (MongoException e) {
// ignore exceptions
} finally {
if (connection != null) {
connection.release();
}
}
}
private boolean shouldPrune(final ServerSessionImpl serverSession) {
Integer logicalSessionTimeoutMinutes = cluster.getCurrentDescription().getLogicalSessionTimeoutMinutes();
// if the server no longer supports sessions, prune the session
if (logicalSessionTimeoutMinutes == null) {
return false;
}
if (serverSession.isMarkedDirty()) {
return true;
}
long currentTimeMillis = clock.millis();
long timeSinceLastUse = currentTimeMillis - serverSession.getLastUsedAtMillis();
long oneMinuteFromTimeout = MINUTES.toMillis(logicalSessionTimeoutMinutes - 1);
return timeSinceLastUse > oneMinuteFromTimeout;
}
final class ServerSessionImpl implements ServerSession {
private final BsonDocument identifier;
private long transactionNumber = 0;
private volatile long lastUsedAtMillis = clock.millis();
private volatile boolean closed;
private volatile boolean dirty = false;
ServerSessionImpl(final BsonBinary identifier) {
this.identifier = new BsonDocument("id", identifier);
}
void close() {
closed = true;
}
long getLastUsedAtMillis() {
return lastUsedAtMillis;
}
@Override
public long getTransactionNumber() {
return transactionNumber;
}
@Override
public BsonDocument getIdentifier() {
lastUsedAtMillis = clock.millis();
return identifier;
}
@Override
public long advanceTransactionNumber() {
transactionNumber++;
return transactionNumber;
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public void markDirty() {
dirty = true;
}
@Override
public boolean isMarkedDirty() {
return dirty;
}
}
private final class ServerSessionItemFactory implements ConcurrentPool.ItemFactory<ServerSessionImpl> {
@Override
public ServerSessionImpl create() {
return new ServerSessionImpl(createNewServerSessionIdentifier());
}
@Override
public void close(final ServerSessionImpl serverSession) {
closeSession(serverSession);
}
@Override
public Prune shouldPrune(final ServerSessionImpl serverSession) {
return ServerSessionPool.this.shouldPrune(serverSession) ? Prune.YES : Prune.STOP;
}
private BsonBinary createNewServerSessionIdentifier() {
UuidCodec uuidCodec = new UuidCodec(UuidRepresentation.STANDARD);
BsonDocument holder = new BsonDocument();
BsonDocumentWriter bsonDocumentWriter = new BsonDocumentWriter(holder);
bsonDocumentWriter.writeStartDocument();
bsonDocumentWriter.writeName("id");
uuidCodec.encode(bsonDocumentWriter, UUID.randomUUID(), EncoderContext.builder().build());
bsonDocumentWriter.writeEndDocument();
return holder.getBinary("id");
}
}
}
|
Modernize ServerSessionPool code
|
driver-core/src/main/com/mongodb/internal/session/ServerSessionPool.java
|
Modernize ServerSessionPool code
|
|
Java
|
apache-2.0
|
00bbc67964aa7eea8ebed376fabe6c3c18284372
| 0
|
CMU-Robotics-Club/QBot-Mobot,CMU-Robotics-Club/QBot-Mobot
|
package edhyah.com.qbot;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.WindowManager;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;
import hanqis.com.qbot.Sample_algorithm;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;
public class MobotActivity extends IOIOActivity implements CameraBridgeViewBase.CvCameraViewListener2 {
private static final String TAG = "MobotActivity";
private PortraitCameraView mOpenCvCameraView; // TODO add a turn off button for when not debugging
private Sample_algorithm algo = new Sample_algorithm();
private double angle;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
@Override
public void onResume()
{
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, this, mLoaderCallback);
}
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_mobot);
mOpenCvCameraView = (PortraitCameraView) findViewById(R.id.video_surface);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
}
@Override
public void onPause()
{
super.onPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
@Override
protected IOIOLooper createIOIOLooper() {
return null; // TODO create custom looper object that takes theta input and drives the mobot, also stops, calibrates
}
public void onCameraViewStarted(int width, int height) {
}
public void onCameraViewStopped() {
}
//------------ Img Processing -------------------------------------------
@Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
angle = algo.Sampling(inputFrame.rgba());
// TODO processing algorithms
// TODO update driving directions
return inputFrame.rgba();
}
}
|
app/src/main/java/edhyah/com/qbot/MobotActivity.java
|
package edhyah.com.qbot;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.WindowManager;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;
public class MobotActivity extends IOIOActivity implements CameraBridgeViewBase.CvCameraViewListener2 {
private static final String TAG = "MobotActivity";
private PortraitCameraView mOpenCvCameraView; // TODO add a turn off button for when not debugging
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
@Override
public void onResume()
{
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, this, mLoaderCallback);
}
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_mobot);
mOpenCvCameraView = (PortraitCameraView) findViewById(R.id.video_surface);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
}
@Override
public void onPause()
{
super.onPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
@Override
protected IOIOLooper createIOIOLooper() {
return null; // TODO create custom looper object that takes theta input and drives the mobot, also stops, calibrates
}
public void onCameraViewStarted(int width, int height) {
}
public void onCameraViewStopped() {
}
//------------ Img Processing -------------------------------------------
@Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
// TODO processing algorithms
// TODO update driving directions
return inputFrame.rgba();
}
}
|
angle output
|
app/src/main/java/edhyah/com/qbot/MobotActivity.java
|
angle output
|
|
Java
|
apache-2.0
|
4703121541b631e98aed163f5538811f6a76c749
| 0
|
learning-layers/SocialSemanticServer,learning-layers/SocialSemanticServer,learning-layers/SocialSemanticServer,learning-layers/SocialSemanticServer
|
/**
* Code contributed to the Learning Layers project
* http://www.learning-layers.eu
* Development is partly funded by the FP7 Programme of the European Commission under
* Grant Agreement FP7-ICT-318209.
* Copyright (c) 2014, Graz University of Technology - KTI (Knowledge Technologies Institute).
* For a list of contributors see the AUTHORS file at the top-level directory of this distribution.
*
* 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 at.tugraz.sss.servs.dataimport.impl.evernote;
import at.kc.tugraz.ss.serv.jobs.evernote.api.SSEvernoteServerI;
import at.kc.tugraz.ss.serv.jobs.evernote.datatypes.par.SSEvernoteResourceByHashGetPar;
import at.tugraz.sss.conf.SSConf;
import at.tugraz.sss.servs.file.api.SSFileServerI;
import at.tugraz.sss.serv.util.SSFileExtE;
import at.tugraz.sss.serv.util.SSFileU;
import at.tugraz.sss.serv.util.SSLogU;
import at.tugraz.sss.serv.util.SSMimeTypeE;
import at.tugraz.sss.serv.util.*;
import at.tugraz.sss.serv.datatype.*;
import at.tugraz.sss.serv.datatype.enums.*;
import at.tugraz.sss.serv.datatype.par.*;
import at.tugraz.sss.serv.reg.*;
import at.tugraz.sss.servs.file.datatype.par.SSEntityFileAddPar;
import com.evernote.clients.NoteStoreClient;
import com.evernote.edam.type.Note;
import com.evernote.edam.type.Resource;
import java.io.*;
public class SSDataImportEvernoteNoteContentHandler{
public void handleNoteContent(
final SSServPar servPar,
final NoteStoreClient noteStore,
final SSUri user,
final String localWorkPath,
final Note note,
final SSUri noteURI,
final SSLabel noteLabel) throws SSErr{
String xhtmlFilePath;
SSUri fileUri;
String pdfFilePath;
try{
final SSFileServerI fileServ = (SSFileServerI) SSServReg.getServ(SSFileServerI.class);
xhtmlFilePath = localWorkPath + SSConf.fileIDFromSSSURI(SSConf.vocURICreate(SSFileExtE.xhtml));
fileUri = SSConf.vocURICreate (SSFileExtE.pdf);
pdfFilePath = localWorkPath+ SSConf.fileIDFromSSSURI (fileUri);
SSFileU.writeStr(note.getContent(), xhtmlFilePath);
try{
SSFileU.writeStr(
downloadNoteResourcesAndFillXHTMLWithLocalImageLinks(
servPar,
localWorkPath,
noteStore,
user,
note,
xhtmlFilePath),
xhtmlFilePath);
SSFileU.writePDFFromXHTML(
pdfFilePath,
xhtmlFilePath,
true);
}catch(Exception error){
SSLogU.info("PDF creation from XHTML failed", error);
try{
try{
SSFileU.writeStr(
reduceXHTMLToTextAndImage(xhtmlFilePath),
xhtmlFilePath);
}catch(Exception error1){
SSLogU.warn("reducing XHTML failed", error1);
throw error;
}
try{
SSFileU.writeStr(
downloadNoteResourcesAndFillXHTMLWithLocalImageLinks(
servPar,
localWorkPath,
noteStore,
user,
note,
xhtmlFilePath),
xhtmlFilePath);
}catch(Exception error1){
SSLogU.warn("filling reduced XHTML failed", error1);
throw error;
}
try{
SSFileU.writePDFFromXHTML(
pdfFilePath,
xhtmlFilePath,
true);
}catch(Exception error1){
SSLogU.warn("PDF creation from reduced and filled XHTML failed", error1);
throw error;
}
}catch(Exception error1){
SSLogU.err(error1);
return;
}
}finally{
try{
SSFileU.delFile(xhtmlFilePath);
}catch(Exception error){
SSLogU.warn(error);
}
}
fileServ.fileAdd(
new SSEntityFileAddPar(
servPar,
user,
null, //fileBytes
null, //fileLength
null, //fileExt
fileUri, //file
SSEntityE.file, //type,
noteLabel, //label
noteURI, //entity
true, //createThumb
noteURI, //entityToAddThumbTo
true, //removeExistingFilesForEntity
true, //withUserRestriction
false));//shouldCommit
}catch(Exception error){
SSServErrReg.regErrThrow(error);
}
}
public static String reduceXHTMLToTextAndImage(final String path) throws SSErr{
BufferedReader br = null;
String result = SSStrU.empty;
String mediaTag;
int mediaStartIndex;
int mediaEndIndex;
try{
result +=
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n" +
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" +
"\n" +
"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
"\n" +
"<body>\n";
String line, text, tag, tmpTag, href, title;
int tagIndex, tagEndIndex, hrefIndex, hrefEndIndex, titleIndex, titleEndIndex;
br = new BufferedReader(new FileReader(new File(path)));
while((line = br.readLine()) != null){
line = line.trim();
while(line.contains("<")){
if(!line.contains(">")){
throw new Exception("xhtml invalid");
}
tagIndex = line.indexOf("<");
tagEndIndex = line.indexOf(">");
tag = line.substring(tagIndex, tagEndIndex + 1);
tmpTag = line.substring(tagIndex, tagEndIndex + 1);
if(tagIndex != 0){
text = line.substring(0, tagIndex).replace("&nbsp;", SSStrU.empty).replace("Â", SSStrU.empty).trim();
if(!text.isEmpty()){
result += "<div>" + text + "</div>" + SSStrU.backslashRBackslashN;
}
}
if(tmpTag.startsWith("<en-media")){
mediaStartIndex = tmpTag.indexOf("<en-media");
mediaEndIndex = tmpTag.indexOf(">");
if(mediaEndIndex != -1){
mediaTag = tmpTag.substring(mediaStartIndex, mediaEndIndex + 1);
if(
!mediaTag.endsWith("/>") &&
mediaTag.length() > 2){
result += mediaTag.substring(0, mediaTag.length() - 1) + "/>";
}else{
result += mediaTag;
}
line = line.replace(mediaTag, SSStrU.empty).replace("&nbsp;", SSStrU.empty).replace("Â", SSStrU.empty).trim();
continue;
}
}
while(tmpTag.contains("href=\"")){
hrefIndex = tmpTag.indexOf("href=\"");
hrefEndIndex = tmpTag.indexOf("\"", hrefIndex + 6);
href = tmpTag.substring(hrefIndex + 6, hrefEndIndex);
if(tmpTag.contains("title=\"")){
titleIndex = tmpTag.indexOf("title=\"");
titleEndIndex = tmpTag.indexOf("\"", titleIndex + 7);
title = tmpTag.substring(titleIndex + 7, titleEndIndex);
title = title.replace("&nbsp;", SSStrU.empty).replace("Â", SSStrU.empty);
tmpTag = tmpTag.substring(0, titleIndex) + tmpTag.substring(titleEndIndex + 1, tmpTag.length() - 1);
hrefIndex = tmpTag.indexOf("href=\"");
hrefEndIndex = tmpTag.indexOf("\"", hrefIndex + 6);
href = tmpTag.substring(hrefIndex + 6, hrefEndIndex);
tmpTag = tmpTag.substring(0, hrefIndex) + tmpTag.substring(hrefEndIndex + 1, tmpTag.length() - 1);
result += "<div>" + "<a href=\"" + href + "\">" + title + "</a>" + "</div>" + SSStrU.backslashRBackslashN;
}else{
result += "<div>" + "<a href=\"" + href + "\">" + href + "</a>" + "</div>" + SSStrU.backslashRBackslashN;
tmpTag = tmpTag.substring(0, hrefIndex) + tmpTag.substring(hrefEndIndex + 1, tmpTag.length() - 1);
}
}
line = line.replace(tag, SSStrU.empty).replace("&nbsp;", SSStrU.empty).replace("Â", SSStrU.empty).trim();
}
line = line.replace("&nbsp;", SSStrU.empty).replace("Â", SSStrU.empty).trim();
if(!line.isEmpty()){
result += "<div>" + line + "</div>" + SSStrU.backslashRBackslashN;
}
}
result +=
"</body>\n"
+ "</html>";
return result;
}catch(Exception error){
SSServErrReg.regErrThrow(error);
return null;
}finally{
if(br != null){
try {
br.close();
} catch (IOException ex) {
SSLogU.err(ex);
}
}
}
}
private String downloadNoteResourcesAndFillXHTMLWithLocalImageLinks(
final SSServPar servPar,
final String localWorkPath,
final NoteStoreClient noteStore,
final SSUri user,
final Note note,
final String path) throws SSErr{
BufferedReader lineReader = null;
String result = SSStrU.empty;
SSUri fileURI = null;
String fileID = null;
Resource resource = null;
// SSUri thumbnailURI;
String line;
String tmpLine;
String hash;
SSMimeTypeE mimeType;
int startIndex;
int endIndex1;
int endIndex2;
int endIndex;
int hashIndex;
int hashEndIndex;
try{
final SSEvernoteServerI evernoteServ = (SSEvernoteServerI) SSServReg.getServ(SSEvernoteServerI.class);
lineReader = new BufferedReader(new FileReader(new File(path)));
while((line = lineReader.readLine()) != null){
line = line.trim();
tmpLine = line;
while(tmpLine.contains("<en-media")){
startIndex = tmpLine.indexOf("<en-media");
if(
!tmpLine.contains("</en-media>") &&
!tmpLine.contains("/>")){
result += tmpLine;
break; //xhtml invalid
}
if(!tmpLine.contains("hash=\"")){
result += tmpLine;
break;
}
endIndex1 = tmpLine.indexOf("</en-media>", startIndex);
endIndex2 = tmpLine.indexOf("/>", startIndex);
if(endIndex1 != -1){
endIndex = endIndex1;
}else{
endIndex = endIndex2;
}
mimeType = null;
if(
tmpLine.contains("type=\"" + SSMimeTypeE.videoMp4 + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.videoMp4 + "\"")){
mimeType = SSMimeTypeE.videoMp4;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationZip + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationZip + "\"")){
mimeType = SSMimeTypeE.applicationZip;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationZipCompressed + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationZipCompressed + "\"")){
mimeType = SSMimeTypeE.applicationZipCompressed;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.textPlain + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.textPlain + "\"")){
mimeType = SSMimeTypeE.textPlain;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.textVcard + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.textVcard + "\"")){
mimeType = SSMimeTypeE.textVcard;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.audioAmr + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.audioAmr + "\"")){
mimeType = SSMimeTypeE.audioAmr;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.audioWav + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.audioWav + "\"")){
mimeType = SSMimeTypeE.audioWav;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.audioMpeg4 + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.audioMpeg4 + "\"")){
mimeType = SSMimeTypeE.audioMpeg4;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.audioMpeg + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.audioMpeg + "\"")){
mimeType = SSMimeTypeE.audioMpeg;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.textHtml + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.textHtml + "\"")){
mimeType = SSMimeTypeE.textHtml;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationBin + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationBin + "\"")){
mimeType = SSMimeTypeE.applicationBin;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.imageJpeg + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.imageJpeg + "\"")){
mimeType = SSMimeTypeE.imageJpeg;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.imagePng + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.imagePng + "\"")){
mimeType = SSMimeTypeE.imagePng;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.imageGif + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.imageGif + "\"")){
mimeType = SSMimeTypeE.imageGif;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.imageTiff + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.imageTiff + "\"")){
mimeType = SSMimeTypeE.imageTiff;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationPdf + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationPdf + "\"")){
mimeType = SSMimeTypeE.applicationPdf;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationMsword2007 + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationMsword2007 + "\"")){
mimeType = SSMimeTypeE.applicationMsword2007;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationMsword + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationMsword + "\"")){
mimeType = SSMimeTypeE.applicationMsword;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationMsword2 + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationMsword2 + "\"")){
mimeType = SSMimeTypeE.applicationMsword2;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationMspowerpoint2007 + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationMspowerpoint2007 + "\"")){
mimeType = SSMimeTypeE.applicationMspowerpoint2007;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationMspowerpoint + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationMspowerpoint + "\"")){
mimeType = SSMimeTypeE.applicationMspowerpoint;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationMsexcel2007 + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationMsexcel2007 + "\"")){
mimeType = SSMimeTypeE.applicationMsexcel2007;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationMsexcel + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationMsexcel + "\"")){
mimeType = SSMimeTypeE.applicationMsexcel;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationMsexcelBinary + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationMsexcelBinary + "\"")){
mimeType = SSMimeTypeE.applicationMsexcelBinary;
}
if(mimeType == null){
SSLogU.warn("no / unknown mime type set in:" + tmpLine, null);
if(endIndex == endIndex1){
result += tmpLine.substring(0, endIndex + 11);
tmpLine = tmpLine.substring(endIndex + 11);
}else{
result += tmpLine.substring(0, endIndex + 2);
tmpLine = tmpLine.substring(endIndex + 2);
}
continue;
}
hashIndex = tmpLine.indexOf("hash=\"");
if(!(tmpLine.contains("hash=\"") && endIndex > hashIndex)){
if(endIndex == endIndex1){
result += tmpLine.substring(0, endIndex + 11);
tmpLine = tmpLine.substring(endIndex + 11);
}else{
result += tmpLine.substring(0, endIndex + 2);
tmpLine = tmpLine.substring(endIndex + 2);
}
continue;
}
if(
SSStrU.isEqual(mimeType, SSMimeTypeE.imageJpeg) ||
SSStrU.isEqual(mimeType, SSMimeTypeE.imagePng) ||
SSStrU.isEqual(mimeType, SSMimeTypeE.imageGif) ||
SSStrU.isEqual(mimeType, SSMimeTypeE.imageTiff)
// ||
// SSStrU.isEqual(mimeType, SSMimeTypeE.applicationPdf)
){
hashEndIndex = tmpLine.indexOf ("\"", hashIndex + 6);
hash = tmpLine.substring (hashIndex + 6, hashEndIndex);
fileURI = SSConf.vocURICreate (SSMimeTypeE.fileExtForMimeType(mimeType));
fileID = SSConf.fileIDFromSSSURI (fileURI);
resource =
evernoteServ.evernoteResourceByHashGet(
new SSEvernoteResourceByHashGetPar(
servPar,
user,
noteStore,
note.getGuid(),
hash));
SSFileU.writeFileBytes(
new FileOutputStream(localWorkPath + fileID),
resource.getData().getBody(),
resource.getData().getSize());
}
result += tmpLine.substring(0, startIndex);
// if(SSStrU.isEqual(mimeType, SSMimeTypeE.applicationPdf)){
// thumbnailURI =
// SSDataImportEvernoteThumbHelper.createThumbnail(
// user,
// localWorkPath,
// fileURI,
// 500,
// 500);
// fileID = SSConf.fileIDFromSSSURI(thumbnailURI);
// result += "<div>PDF Included here (please see for resoruces)</div>";
// +
// "<img width=\"" +
// 500 +
// "\" height=\"" +
// 500 +
// "\" class=\"xmyImagex\" src=\"" +
// localWorkPath + fileID +
// "\"/>";
// }
if(
resource != null &&
!SSStrU.isEqual(mimeType, SSMimeTypeE.applicationPdf)){
result +=
"<img width=\"" +
resource.getWidth() +
"\" height=\"" +
resource.getHeight() +
"\" class=\"xmyImagex\" src=\"" +
localWorkPath + fileID +
"\"/>";
}
if(SSStrU.isEqual(mimeType, SSMimeTypeE.applicationPdf)){
result += "<div>Includes PDF (no preview available; see timeline for resources)</div>";
}
if(
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationZip) ||
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationZipCompressed)){
result += "<div>Includes Compressed Archive (no preview available)</div>";
}
if(
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationMsword) ||
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationMsword2) ||
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationMsword2007)){
result += "<div>Includes Microsoft Office Document (no preview available)</div>";
}
if(
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationMspowerpoint) ||
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationMspowerpoint2007)){
result += "<div>Includes Microsoft Office Powerpoint Document (no preview available)</div>";
}
if(
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationMsexcel) ||
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationMsexcel2007)){
result += "<div>Includes Microsoft Office Excel Document (no preview available)</div>";
}
if(tmpLine.contains("type=\"" + SSMimeTypeE.textPlain + "\"")){
result += "<div>Includes Plain Text Document (no preview available)</div>";
}
if(tmpLine.contains("type=\"" + SSMimeTypeE.textVcard + "\"")){
result += "<div>Includes VCard (no preview available)</div>";
}
if(tmpLine.contains("type=\"" + SSMimeTypeE.audioAmr + "\"")){
result += "<div>Includes Adaptive Multi-Rate Audio (no preview available)</div>";
}
if(tmpLine.contains("type=\"" + SSMimeTypeE.audioWav + "\"")){
result += "<div>Includes Wave Audio (no preview available)</div>";
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.audioMpeg4 + "\"") ||
tmpLine.contains("type=\"" + SSMimeTypeE.audioMpeg + "\"")){
result += "<div>Includes MPEG Audio (no preview available)</div>";
}
if(tmpLine.contains("type=\"" + SSMimeTypeE.textHtml + "\"")){
result += "<div>Includes HTML Page (no preview available)</div>";
}
if(tmpLine.contains("type=\"" + SSMimeTypeE.applicationBin + "\"")){
result += "<div>Includes Application File (no preview available)</div>";
}
if(tmpLine.contains("type=\"" + SSMimeTypeE.applicationMsexcelBinary + "\"")){
result += "<div>Includes Binary Spreadsheet File (no preview available)</div>";
}
if(endIndex == endIndex1){
tmpLine = tmpLine.substring(endIndex + 11, tmpLine.length());
}else{
tmpLine = tmpLine.substring(endIndex + 2, tmpLine.length());
}
}
result += tmpLine;
result += SSStrU.backslashRBackslashN;
}
return result.replace("&nbsp;", SSStrU.empty).replace("Â", SSStrU.empty).trim();
}catch(Exception error){
SSServErrReg.regErrThrow(error);
return null;
}finally{
if(lineReader != null){
try {
lineReader.close();
} catch (IOException ex) {
SSLogU.err(ex);
}
}
}
}
}
|
servs/dataimport/dataimport.impl/src/main/java/at/tugraz/sss/servs/dataimport/impl/evernote/SSDataImportEvernoteNoteContentHandler.java
|
/**
* Code contributed to the Learning Layers project
* http://www.learning-layers.eu
* Development is partly funded by the FP7 Programme of the European Commission under
* Grant Agreement FP7-ICT-318209.
* Copyright (c) 2014, Graz University of Technology - KTI (Knowledge Technologies Institute).
* For a list of contributors see the AUTHORS file at the top-level directory of this distribution.
*
* 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 at.tugraz.sss.servs.dataimport.impl.evernote;
import at.kc.tugraz.ss.serv.jobs.evernote.api.SSEvernoteServerI;
import at.kc.tugraz.ss.serv.jobs.evernote.datatypes.par.SSEvernoteResourceByHashGetPar;
import at.tugraz.sss.conf.SSConf;
import at.tugraz.sss.servs.file.api.SSFileServerI;
import at.tugraz.sss.serv.util.SSFileExtE;
import at.tugraz.sss.serv.util.SSFileU;
import at.tugraz.sss.serv.util.SSLogU;
import at.tugraz.sss.serv.util.SSMimeTypeE;
import at.tugraz.sss.serv.util.*;
import at.tugraz.sss.serv.datatype.*;
import at.tugraz.sss.serv.datatype.enums.*;
import at.tugraz.sss.serv.datatype.par.*;
import at.tugraz.sss.serv.reg.*;
import at.tugraz.sss.servs.file.datatype.par.SSEntityFileAddPar;
import com.evernote.clients.NoteStoreClient;
import com.evernote.edam.type.Note;
import com.evernote.edam.type.Resource;
import java.io.*;
public class SSDataImportEvernoteNoteContentHandler{
public void handleNoteContent(
final SSServPar servPar,
final NoteStoreClient noteStore,
final SSUri user,
final String localWorkPath,
final Note note,
final SSUri noteURI,
final SSLabel noteLabel) throws SSErr{
String xhtmlFilePath;
SSUri fileUri;
String pdfFilePath;
try{
final SSFileServerI fileServ = (SSFileServerI) SSServReg.getServ(SSFileServerI.class);
xhtmlFilePath = localWorkPath + SSConf.fileIDFromSSSURI(SSConf.vocURICreate(SSFileExtE.xhtml));
fileUri = SSConf.vocURICreate (SSFileExtE.pdf);
pdfFilePath = localWorkPath+ SSConf.fileIDFromSSSURI (fileUri);
SSFileU.writeStr(note.getContent(), xhtmlFilePath);
try{
SSFileU.writeStr(
downloadNoteResourcesAndFillXHTMLWithLocalImageLinks(
servPar,
localWorkPath,
noteStore,
user,
note,
xhtmlFilePath),
xhtmlFilePath);
SSFileU.writePDFFromXHTML(
pdfFilePath,
xhtmlFilePath,
true);
}catch(Exception error){
SSLogU.info("PDF creation from XHTML failed", error);
try{
try{
SSFileU.writeStr(
reduceXHTMLToTextAndImage(xhtmlFilePath),
xhtmlFilePath);
}catch(Exception error1){
SSLogU.warn("reducing XHTML failed", error1);
throw error;
}
try{
SSFileU.writeStr(
downloadNoteResourcesAndFillXHTMLWithLocalImageLinks(
servPar,
localWorkPath,
noteStore,
user,
note,
xhtmlFilePath),
xhtmlFilePath);
}catch(Exception error1){
SSLogU.warn("filling reduced XHTML failed", error1);
throw error;
}
try{
SSFileU.writePDFFromXHTML(
pdfFilePath,
xhtmlFilePath,
true);
}catch(Exception error1){
SSLogU.warn("PDF creation from reduced and filled XHTML failed", error1);
throw error;
}
}catch(Exception error1){
SSLogU.err(error1);
return;
}
}finally{
try{
SSFileU.delFile(xhtmlFilePath);
}catch(Exception error){
SSLogU.warn(error);
}
}
fileServ.fileAdd(
new SSEntityFileAddPar(
servPar,
user,
null, //fileBytes
null, //fileLength
null, //fileExt
fileUri, //file
SSEntityE.file, //type,
noteLabel, //label
noteURI, //entity
true, //createThumb
noteURI, //entityToAddThumbTo
true, //removeExistingFilesForEntity
true, //withUserRestriction
false));//shouldCommit
}catch(Exception error){
SSServErrReg.regErrThrow(error);
}
}
public static String reduceXHTMLToTextAndImage(final String path) throws SSErr{
BufferedReader br = null;
String result = SSStrU.empty;
String mediaTag;
int mediaStartIndex;
int mediaEndIndex;
try{
result +=
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n" +
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" +
"\n" +
"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
"\n" +
"<body>\n";
String line, text, tag, tmpTag, href, title;
int tagIndex, tagEndIndex, hrefIndex, hrefEndIndex, titleIndex, titleEndIndex;
br = new BufferedReader(new FileReader(new File(path)));
while((line = br.readLine()) != null){
line = line.trim();
while(line.contains("<")){
if(!line.contains(">")){
throw new Exception("xhtml invalid");
}
tagIndex = line.indexOf("<");
tagEndIndex = line.indexOf(">");
tag = line.substring(tagIndex, tagEndIndex + 1);
tmpTag = line.substring(tagIndex, tagEndIndex + 1);
if(tagIndex != 0){
text = line.substring(0, tagIndex).replace("&nbsp;", SSStrU.empty).replace("Â", SSStrU.empty).trim();
if(!text.isEmpty()){
result += "<div>" + text + "</div>" + SSStrU.backslashRBackslashN;
}
}
if(tmpTag.startsWith("<en-media")){
mediaStartIndex = tmpTag.indexOf("<en-media");
mediaEndIndex = tmpTag.indexOf(">");
if(mediaEndIndex != -1){
mediaTag = tmpTag.substring(mediaStartIndex, mediaEndIndex + 1);
if(
!mediaTag.endsWith("/>") &&
mediaTag.length() > 2){
result += mediaTag.substring(0, mediaTag.length() - 1) + "/>";
}else{
result += mediaTag;
}
line = line.replace(mediaTag, SSStrU.empty).replace("&nbsp;", SSStrU.empty).replace("Â", SSStrU.empty).trim();
continue;
}
}
while(tmpTag.contains("href=\"")){
hrefIndex = tmpTag.indexOf("href=\"");
hrefEndIndex = tmpTag.indexOf("\"", hrefIndex + 6);
href = tmpTag.substring(hrefIndex + 6, hrefEndIndex);
if(tmpTag.contains("title=\"")){
titleIndex = tmpTag.indexOf("title=\"");
titleEndIndex = tmpTag.indexOf("\"", titleIndex + 7);
title = tmpTag.substring(titleIndex + 7, titleEndIndex);
title = title.replace("&nbsp;", SSStrU.empty).replace("Â", SSStrU.empty);
tmpTag = tmpTag.substring(0, titleIndex) + tmpTag.substring(titleEndIndex + 1, tmpTag.length() - 1);
hrefIndex = tmpTag.indexOf("href=\"");
hrefEndIndex = tmpTag.indexOf("\"", hrefIndex + 6);
href = tmpTag.substring(hrefIndex + 6, hrefEndIndex);
tmpTag = tmpTag.substring(0, hrefIndex) + tmpTag.substring(hrefEndIndex + 1, tmpTag.length() - 1);
result += "<div>" + "<a href=\"" + href + "\">" + title + "</a>" + "</div>" + SSStrU.backslashRBackslashN;
}else{
result += "<div>" + "<a href=\"" + href + "\">" + href + "</a>" + "</div>" + SSStrU.backslashRBackslashN;
tmpTag = tmpTag.substring(0, hrefIndex) + tmpTag.substring(hrefEndIndex + 1, tmpTag.length() - 1);
}
}
line = line.replace(tag, SSStrU.empty).replace("&nbsp;", SSStrU.empty).replace("Â", SSStrU.empty).trim();
}
line = line.replace("&nbsp;", SSStrU.empty).replace("Â", SSStrU.empty).trim();
if(!line.isEmpty()){
result += "<div>" + line + "</div>" + SSStrU.backslashRBackslashN;
}
}
result +=
"</body>\n"
+ "</html>";
return result;
}catch(Exception error){
SSServErrReg.regErrThrow(error);
return null;
}finally{
if(br != null){
try {
br.close();
} catch (IOException ex) {
SSLogU.err(ex);
}
}
}
}
private String downloadNoteResourcesAndFillXHTMLWithLocalImageLinks(
final SSServPar servPar,
final String localWorkPath,
final NoteStoreClient noteStore,
final SSUri user,
final Note note,
final String path) throws SSErr{
BufferedReader lineReader = null;
String result = SSStrU.empty;
SSUri fileURI = null;
String fileID = null;
Resource resource = null;
// SSUri thumbnailURI;
String line;
String tmpLine;
String hash;
SSMimeTypeE mimeType;
int startIndex;
int endIndex1;
int endIndex2;
int endIndex;
int hashIndex;
int hashEndIndex;
try{
final SSEvernoteServerI evernoteServ = (SSEvernoteServerI) SSServReg.getServ(SSEvernoteServerI.class);
lineReader = new BufferedReader(new FileReader(new File(path)));
while((line = lineReader.readLine()) != null){
line = line.trim();
tmpLine = line;
while(tmpLine.contains("<en-media")){
startIndex = tmpLine.indexOf("<en-media");
if(
!tmpLine.contains("</en-media>") &&
!tmpLine.contains("/>")){
result += tmpLine;
break; //xhtml invalid
}
if(!tmpLine.contains("hash=\"")){
result += tmpLine;
break;
}
endIndex1 = tmpLine.indexOf("</en-media>", startIndex);
endIndex2 = tmpLine.indexOf("/>", startIndex);
if(endIndex1 != -1){
endIndex = endIndex1;
}else{
endIndex = endIndex2;
}
mimeType = null;
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationZip + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationZip + "\"")){
mimeType = SSMimeTypeE.applicationZip;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationZipCompressed + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationZipCompressed + "\"")){
mimeType = SSMimeTypeE.applicationZipCompressed;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.textPlain + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.textPlain + "\"")){
mimeType = SSMimeTypeE.textPlain;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.textVcard + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.textVcard + "\"")){
mimeType = SSMimeTypeE.textVcard;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.audioAmr + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.audioAmr + "\"")){
mimeType = SSMimeTypeE.audioAmr;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.audioWav + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.audioWav + "\"")){
mimeType = SSMimeTypeE.audioWav;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.audioMpeg4 + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.audioMpeg4 + "\"")){
mimeType = SSMimeTypeE.audioMpeg4;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.audioMpeg + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.audioMpeg + "\"")){
mimeType = SSMimeTypeE.audioMpeg;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.textHtml + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.textHtml + "\"")){
mimeType = SSMimeTypeE.textHtml;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationBin + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationBin + "\"")){
mimeType = SSMimeTypeE.applicationBin;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.imageJpeg + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.imageJpeg + "\"")){
mimeType = SSMimeTypeE.imageJpeg;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.imagePng + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.imagePng + "\"")){
mimeType = SSMimeTypeE.imagePng;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.imageGif + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.imageGif + "\"")){
mimeType = SSMimeTypeE.imageGif;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.imageTiff + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.imageTiff + "\"")){
mimeType = SSMimeTypeE.imageTiff;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationPdf + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationPdf + "\"")){
mimeType = SSMimeTypeE.applicationPdf;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationMsword2007 + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationMsword2007 + "\"")){
mimeType = SSMimeTypeE.applicationMsword2007;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationMsword + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationMsword + "\"")){
mimeType = SSMimeTypeE.applicationMsword;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationMsword2 + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationMsword2 + "\"")){
mimeType = SSMimeTypeE.applicationMsword2;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationMspowerpoint2007 + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationMspowerpoint2007 + "\"")){
mimeType = SSMimeTypeE.applicationMspowerpoint2007;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationMspowerpoint + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationMspowerpoint + "\"")){
mimeType = SSMimeTypeE.applicationMspowerpoint;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationMsexcel2007 + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationMsexcel2007 + "\"")){
mimeType = SSMimeTypeE.applicationMsexcel2007;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationMsexcel + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationMsexcel + "\"")){
mimeType = SSMimeTypeE.applicationMsexcel;
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.applicationMsexcelBinary + "\"") &&
endIndex > tmpLine.indexOf("type=\"" + SSMimeTypeE.applicationMsexcelBinary + "\"")){
mimeType = SSMimeTypeE.applicationMsexcelBinary;
}
if(mimeType == null){
SSLogU.warn("no / unknown mime type set in:" + tmpLine, null);
if(endIndex == endIndex1){
result += tmpLine.substring(0, endIndex + 11);
tmpLine = tmpLine.substring(endIndex + 11);
}else{
result += tmpLine.substring(0, endIndex + 2);
tmpLine = tmpLine.substring(endIndex + 2);
}
continue;
}
hashIndex = tmpLine.indexOf("hash=\"");
if(!(tmpLine.contains("hash=\"") && endIndex > hashIndex)){
if(endIndex == endIndex1){
result += tmpLine.substring(0, endIndex + 11);
tmpLine = tmpLine.substring(endIndex + 11);
}else{
result += tmpLine.substring(0, endIndex + 2);
tmpLine = tmpLine.substring(endIndex + 2);
}
continue;
}
if(
SSStrU.isEqual(mimeType, SSMimeTypeE.imageJpeg) ||
SSStrU.isEqual(mimeType, SSMimeTypeE.imagePng) ||
SSStrU.isEqual(mimeType, SSMimeTypeE.imageGif) ||
SSStrU.isEqual(mimeType, SSMimeTypeE.imageTiff)
// ||
// SSStrU.isEqual(mimeType, SSMimeTypeE.applicationPdf)
){
hashEndIndex = tmpLine.indexOf ("\"", hashIndex + 6);
hash = tmpLine.substring (hashIndex + 6, hashEndIndex);
fileURI = SSConf.vocURICreate (SSMimeTypeE.fileExtForMimeType(mimeType));
fileID = SSConf.fileIDFromSSSURI (fileURI);
resource =
evernoteServ.evernoteResourceByHashGet(
new SSEvernoteResourceByHashGetPar(
servPar,
user,
noteStore,
note.getGuid(),
hash));
SSFileU.writeFileBytes(
new FileOutputStream(localWorkPath + fileID),
resource.getData().getBody(),
resource.getData().getSize());
}
result += tmpLine.substring(0, startIndex);
// if(SSStrU.isEqual(mimeType, SSMimeTypeE.applicationPdf)){
// thumbnailURI =
// SSDataImportEvernoteThumbHelper.createThumbnail(
// user,
// localWorkPath,
// fileURI,
// 500,
// 500);
// fileID = SSConf.fileIDFromSSSURI(thumbnailURI);
// result += "<div>PDF Included here (please see for resoruces)</div>";
// +
// "<img width=\"" +
// 500 +
// "\" height=\"" +
// 500 +
// "\" class=\"xmyImagex\" src=\"" +
// localWorkPath + fileID +
// "\"/>";
// }
if(
resource != null &&
!SSStrU.isEqual(mimeType, SSMimeTypeE.applicationPdf)){
result +=
"<img width=\"" +
resource.getWidth() +
"\" height=\"" +
resource.getHeight() +
"\" class=\"xmyImagex\" src=\"" +
localWorkPath + fileID +
"\"/>";
}
if(SSStrU.isEqual(mimeType, SSMimeTypeE.applicationPdf)){
result += "<div>Includes PDF (no preview available; see timeline for resources)</div>";
}
if(
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationZip) ||
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationZipCompressed)){
result += "<div>Includes Compressed Archive (no preview available)</div>";
}
if(
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationMsword) ||
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationMsword2) ||
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationMsword2007)){
result += "<div>Includes Microsoft Office Document (no preview available)</div>";
}
if(
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationMspowerpoint) ||
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationMspowerpoint2007)){
result += "<div>Includes Microsoft Office Powerpoint Document (no preview available)</div>";
}
if(
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationMsexcel) ||
SSStrU.isEqual(mimeType, SSMimeTypeE.applicationMsexcel2007)){
result += "<div>Includes Microsoft Office Excel Document (no preview available)</div>";
}
if(tmpLine.contains("type=\"" + SSMimeTypeE.textPlain + "\"")){
result += "<div>Includes Plain Text Document (no preview available)</div>";
}
if(tmpLine.contains("type=\"" + SSMimeTypeE.textVcard + "\"")){
result += "<div>Includes VCard (no preview available)</div>";
}
if(tmpLine.contains("type=\"" + SSMimeTypeE.audioAmr + "\"")){
result += "<div>Includes Adaptive Multi-Rate Audio (no preview available)</div>";
}
if(tmpLine.contains("type=\"" + SSMimeTypeE.audioWav + "\"")){
result += "<div>Includes Wave Audio (no preview available)</div>";
}
if(
tmpLine.contains("type=\"" + SSMimeTypeE.audioMpeg4 + "\"") ||
tmpLine.contains("type=\"" + SSMimeTypeE.audioMpeg + "\"")){
result += "<div>Includes MPEG Audio (no preview available)</div>";
}
if(tmpLine.contains("type=\"" + SSMimeTypeE.textHtml + "\"")){
result += "<div>Includes HTML Page (no preview available)</div>";
}
if(tmpLine.contains("type=\"" + SSMimeTypeE.applicationBin + "\"")){
result += "<div>Includes Application File (no preview available)</div>";
}
if(tmpLine.contains("type=\"" + SSMimeTypeE.applicationMsexcelBinary + "\"")){
result += "<div>Includes Binary Spreadsheet File (no preview available)</div>";
}
if(endIndex == endIndex1){
tmpLine = tmpLine.substring(endIndex + 11, tmpLine.length());
}else{
tmpLine = tmpLine.substring(endIndex + 2, tmpLine.length());
}
}
result += tmpLine;
result += SSStrU.backslashRBackslashN;
}
return result.replace("&nbsp;", SSStrU.empty).replace("Â", SSStrU.empty).trim();
}catch(Exception error){
SSServErrReg.regErrThrow(error);
return null;
}finally{
if(lineReader != null){
try {
lineReader.close();
} catch (IOException ex) {
SSLogU.err(ex);
}
}
}
}
}
|
SSS-428
|
servs/dataimport/dataimport.impl/src/main/java/at/tugraz/sss/servs/dataimport/impl/evernote/SSDataImportEvernoteNoteContentHandler.java
|
SSS-428
|
|
Java
|
apache-2.0
|
6a52bb53135e967b1abce0266c13f44cee23f2a9
| 0
|
tourn/ChallP1,tourn/ChallP1,tourn/ChallP1
|
package ch.trq.carrera.javapilot.akka;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import ch.trq.carrera.javapilot.akka.history.StrategyParameters;
import ch.trq.carrera.javapilot.akka.history.TrackHistory;
import ch.trq.carrera.javapilot.akka.positiontracker.CarUpdate;
import ch.trq.carrera.javapilot.akka.positiontracker.PositionTracker;
import ch.trq.carrera.javapilot.akka.positiontracker.SectionUpdate;
import ch.trq.carrera.javapilot.akka.trackanalyzer.Track;
import ch.trq.carrera.javapilot.akka.trackanalyzer.TrackAndPhysicModelStorage;
import ch.trq.carrera.javapilot.akka.trackanalyzer.TrackSection;
import com.zuehlke.carrera.javapilot.akka.PowerAction;
import com.zuehlke.carrera.relayapi.messages.PenaltyMessage;
import com.zuehlke.carrera.relayapi.messages.RoundTimeMessage;
import com.zuehlke.carrera.relayapi.messages.SensorEvent;
import com.zuehlke.carrera.relayapi.messages.VelocityMessage;
public class SpeedOptimizer extends UntypedActor {
private final int WAIT_TIME_FOR_RECOVERY = 3000;
private final int ZERO_POWER = 0;
private final long WAIT_TIME_FOR_PENALTY = 3000;
private static final int MIN_DECREMENT = 2;
private boolean hasPenalty = false;
private long reciveLastPenaltyMessageTime = 0; // Computer-System-Time... CARE
private ActorRef pilot;
private final Track track;
private final int minPower = 120;
private final int maxTurnPower = 150;
private int maxPower = 200;
private PositionTracker positionTracker;
private String actorDescription;
private final TrackHistory history;
private StrategyParameters currentStrategyParams;
private boolean recoveringFromPenalty = false;
public SpeedOptimizer(ActorRef pilot, TrackAndPhysicModelStorage storage) {
this.pilot = pilot;
this.track = storage.getTrack();
positionTracker = new PositionTracker(storage.getTrack(), storage.getPhysicModel());
positionTracker.setOnSectionChanged(this::onSectionChanged);
history = new TrackHistory(track);
TrackSection currentSection = positionTracker.getCarPosition().getSection();
currentStrategyParams = createStrategyParams(history.getValidHistory(currentSection.getId()));
tellChangePower(maxTurnPower);
actorDescription = getActorDescription();
}
private void onSectionChanged(TrackSection section) {
tellSectionUpdate(section);
updateHistory(section);
}
public static Props props(ActorRef pilot, TrackAndPhysicModelStorage storage) {
return Props.create(SpeedOptimizer.class, () -> new SpeedOptimizer(pilot, storage));
}
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof SensorEvent) {
handleSensorEvent((SensorEvent) message);
} else if (message instanceof VelocityMessage) {
handleVelocityMessage((VelocityMessage) message);
} else if (message instanceof RoundTimeMessage) {
handleRoundTimeMessage((RoundTimeMessage) message);
} else if (message instanceof PenaltyMessage) {
handlePenaltyMessage((PenaltyMessage) message);
} else {
unhandled(message);
}
}
private void handleRoundTimeMessage(RoundTimeMessage message) {
//ignore
}
private void handleVelocityMessage(VelocityMessage message) {
if (System.currentTimeMillis() - reciveLastPenaltyMessageTime > (WAIT_TIME_FOR_RECOVERY + WAIT_TIME_FOR_PENALTY)) {
recoveringFromPenalty = false;
}
positionTracker.velocityUpdate(message);
}
private void handleSensorEvent(SensorEvent event) {
positionTracker.sensorUpdate(event);
if (hasPenalty) {
tellChangePower(ZERO_POWER);
if (System.currentTimeMillis() - reciveLastPenaltyMessageTime > WAIT_TIME_FOR_PENALTY) {
hasPenalty = false;
}
} else {
if (recoveringFromPenalty) {
tellChangePower(maxTurnPower);
} else {
if (!positionTracker.isTurn()) {
if (positionTracker.getPercentageDistance() > currentStrategyParams.getBrakePercentage()) {
tellChangePower(minPower);
} else {
tellChangePower(currentStrategyParams.getPower());
}
} else {
tellChangePower(maxTurnPower);
}
}
}
Track.Position carPosition = positionTracker.getCarPosition();
pilot.tell(new CarUpdate(carPosition.getSection().getId(), carPosition.getDurationOffset(), carPosition.getPercentage()), getSelf());
}
private void handlePenaltyMessage(PenaltyMessage message) {
tellChangePower(ZERO_POWER);
reciveLastPenaltyMessageTime = System.currentTimeMillis();
hasPenalty = true;
recoveringFromPenalty = true;
currentStrategyParams.setPenaltyOccurred(true);
}
public String getActorDescription() {
return "SpeedOptimizer";
}
private void tellChangePower(int power) {
pilot.tell(new PowerAction(power), getSelf());
positionTracker.setPower(power);
}
private void updateHistory(TrackSection section) {
currentStrategyParams.setDuration(section.getDuration()); //FIXME: duration is currently not set in the section
history.addEntry(currentStrategyParams);
currentStrategyParams = createStrategyParams(history.getValidHistory(positionTracker.getCarPosition().getSection().getId()));
}
private StrategyParameters createStrategyParams(StrategyParameters previous) {
StrategyParameters params = new StrategyParameters();
params.setPowerIncrement(previous.getPowerIncrement());
params.setBrakePercentage(previous.getBrakePercentage());
params.setSection(previous.getSection());
int power = previous.getPower();
if (previous.isPenaltyOccurred()) {
power -= Math.max(MIN_DECREMENT, params.getPowerIncrement());
params.setPowerIncrement((int) (params.getPowerIncrement() * 0.5));
} else {
if (power + params.getPowerIncrement() < maxPower) {
power += params.getPowerIncrement();
}
}
params.setPower(power);
if (recoveringFromPenalty) {
params.setValid(false);
}
return params;
}
public void tellSectionUpdate(TrackSection section) {
SectionUpdate sectionUpdate = new SectionUpdate(section);
sectionUpdate.setPenaltyOccured(currentStrategyParams.isPenaltyOccurred());
if (positionTracker.isTurn()) {
sectionUpdate.setPowerInSection(positionTracker.getPower());
} else {
sectionUpdate.setPowerInSection(currentStrategyParams.getPower());
}
pilot.tell(sectionUpdate, getSelf());
}
}
|
src/main/java/ch/trq/carrera/javapilot/akka/SpeedOptimizer.java
|
package ch.trq.carrera.javapilot.akka;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import ch.trq.carrera.javapilot.akka.history.StrategyParameters;
import ch.trq.carrera.javapilot.akka.history.TrackHistory;
import ch.trq.carrera.javapilot.akka.log.LogMessage;
import ch.trq.carrera.javapilot.akka.positiontracker.CarUpdate;
import ch.trq.carrera.javapilot.akka.positiontracker.PositionTracker;
import ch.trq.carrera.javapilot.akka.positiontracker.SectionUpdate;
import ch.trq.carrera.javapilot.akka.trackanalyzer.Track;
import ch.trq.carrera.javapilot.akka.trackanalyzer.TrackAndPhysicModelStorage;
import ch.trq.carrera.javapilot.akka.trackanalyzer.TrackSection;
import com.zuehlke.carrera.javapilot.akka.PowerAction;
import com.zuehlke.carrera.relayapi.messages.PenaltyMessage;
import com.zuehlke.carrera.relayapi.messages.RoundTimeMessage;
import com.zuehlke.carrera.relayapi.messages.SensorEvent;
import com.zuehlke.carrera.relayapi.messages.VelocityMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SpeedOptimizer extends UntypedActor {
private final int WAIT_TIME_FOR_RECOVERY = 3000;
private final int ZERO_POWER = 0;
private final long WAIT_TIME_FOR_PENALTY = 3000;
private static final int MIN_DECREMENT = 2;
private boolean hasPenalty = false;
private long reciveLastPenaltyMessageTime = 0; // Computer-System-Time... CARE
private final Logger LOGGER = LoggerFactory.getLogger(SpeedOptimizer.class);
private ActorRef pilot;
private final Track track;
private final int minPower = 120;
private final int maxTurnPower = 150;
private int maxPower = 200;
private PositionTracker positionTracker;
private String actorDescription;
private final TrackHistory history;
private StrategyParameters currentStrategyParams;
private boolean recoveringFromPenalty = false;
public SpeedOptimizer(ActorRef pilot, TrackAndPhysicModelStorage storage) {
this.pilot = pilot;
this.track = storage.getTrack();
positionTracker = new PositionTracker(storage.getTrack(), storage.getPhysicModel());
positionTracker.setOnSectionChanged(this::onSectionChanged);
history = new TrackHistory(track);
TrackSection currentSection = positionTracker.getCarPosition().getSection();
currentStrategyParams = createStrategyParams(history.getValidHistory(currentSection.getId()));
tellChangePower(maxTurnPower);
actorDescription = getActorDescription();
}
private void onSectionChanged(TrackSection section){
tellSectionUpdate(section);
updateHistory(section);
}
public static Props props(ActorRef pilot, TrackAndPhysicModelStorage storage) {
return Props.create(SpeedOptimizer.class, () -> new SpeedOptimizer(pilot, storage));
}
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof SensorEvent) {
handleSensorEvent((SensorEvent) message);
} else if (message instanceof VelocityMessage) {
handleVelocityMessage((VelocityMessage) message);
} else if (message instanceof RoundTimeMessage) {
handleRoundTimeMessage((RoundTimeMessage) message);
} else if (message instanceof PenaltyMessage) {
handlePenaltyMessage((PenaltyMessage) message);
} else {
unhandled(message);
}
}
private void handleRoundTimeMessage(RoundTimeMessage message) {
//ignore
}
private void handleVelocityMessage(VelocityMessage message) {
if (System.currentTimeMillis() - reciveLastPenaltyMessageTime > (WAIT_TIME_FOR_RECOVERY + WAIT_TIME_FOR_PENALTY)) {
recoveringFromPenalty = false;
}
positionTracker.velocityUpdate(message);
}
private void handleSensorEvent(SensorEvent event) {
LogMessage log = new LogMessage(event, System.currentTimeMillis());
positionTracker.sensorUpdate(event);
if (hasPenalty) {
tellChangePower(ZERO_POWER);
if (System.currentTimeMillis() - reciveLastPenaltyMessageTime > WAIT_TIME_FOR_PENALTY) {
hasPenalty = false;
}
} else {
if (recoveringFromPenalty) {
tellChangePower(maxTurnPower);
} else {
if (!positionTracker.isTurn()) {
if (positionTracker.getPercentageDistance() > currentStrategyParams.getBrakePercentage()) {
tellChangePower(minPower);
} else {
tellChangePower(currentStrategyParams.getPower());
}
} else {
tellChangePower(maxTurnPower);
}
}
}
popluateLog(log);
Track.Position carPosition = positionTracker.getCarPosition();
pilot.tell(new CarUpdate(carPosition.getSection().getId(), carPosition.getDurationOffset(), carPosition.getPercentage()), getSelf());
pilot.tell(log, getSelf());
}
private void handlePenaltyMessage(PenaltyMessage message) {
tellChangePower(ZERO_POWER);
reciveLastPenaltyMessageTime = System.currentTimeMillis();
hasPenalty = true;
recoveringFromPenalty = true;
currentStrategyParams.setPenaltyOccurred(true);
}
private void popluateLog(LogMessage log) {
log.setPower(positionTracker.getPower());
log.setActorDescription(actorDescription);
log.setPositionRelative(positionTracker.getCarPosition().getDistanceOffset());
log.settAfterCalculation(System.currentTimeMillis());
}
public String getActorDescription() {
return "SpeedOptimizer";
}
private void tellChangePower(int power) {
pilot.tell(new PowerAction(power), getSelf());
positionTracker.setPower(power);
}
private void updateHistory(TrackSection section){
currentStrategyParams.setDuration(section.getDuration()); //FIXME: duration is currently not set in the section
history.addEntry(currentStrategyParams);
currentStrategyParams = createStrategyParams(history.getValidHistory(positionTracker.getCarPosition().getSection().getId()));
}
private StrategyParameters createStrategyParams(StrategyParameters previous) {
StrategyParameters params = new StrategyParameters();
params.setPowerIncrement(previous.getPowerIncrement());
params.setBrakePercentage(previous.getBrakePercentage());
params.setSection(previous.getSection());
int power = previous.getPower();
if (previous.isPenaltyOccurred()) {
power -= Math.max(MIN_DECREMENT, params.getPowerIncrement());
params.setPowerIncrement((int) (params.getPowerIncrement() * 0.5));
} else {
if (power + params.getPowerIncrement() < maxPower) {
power += params.getPowerIncrement();
}
}
params.setPower(power);
if (recoveringFromPenalty) {
params.setValid(false);
}
return params;
}
public void tellSectionUpdate(TrackSection section) {
SectionUpdate sectionUpdate = new SectionUpdate(section);
sectionUpdate.setPenaltyOccured(currentStrategyParams.isPenaltyOccurred());
if (positionTracker.isTurn()) {
sectionUpdate.setPowerInSection(positionTracker.getPower());
} else {
sectionUpdate.setPowerInSection(currentStrategyParams.getPower());
}
pilot.tell(sectionUpdate, getSelf());
}
}
|
Remove unused logger from SpeedOptimizer
|
src/main/java/ch/trq/carrera/javapilot/akka/SpeedOptimizer.java
|
Remove unused logger from SpeedOptimizer
|
|
Java
|
apache-2.0
|
ba5124899c0ae31e315f43705341ceea18f292be
| 0
|
crawler-commons/http-fetcher,crawler-commons/http-fetcher
|
/**
* Copyright 2016 Crawler-Commons
*
* 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 crawlercommons.fetcher.http;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieIdentityComparator;
/**
* Default implementation of {@link CookieStore} Initially copied from
* HttpComponents Changes: removed synchronization
*
*/
public class LocalCookieStore implements CookieStore, Serializable {
private static final long serialVersionUID = -7581093305228232025L;
private final TreeSet<Cookie> cookies;
public LocalCookieStore() {
super();
this.cookies = new TreeSet<Cookie>(new CookieIdentityComparator());
}
/**
* Adds an {@link Cookie HTTP cookie}, replacing any existing equivalent
* cookies. If the given ookie has already expired it will not be added, but
* existing values will still be removed.
*
* @param cookie
* the {@link Cookie cookie} to be added
*
* @see #addCookies(Cookie[])
*
*/
public void addCookie(Cookie cookie) {
if (cookie != null) {
// first remove any old cookie that is equivalent
cookies.remove(cookie);
if (!cookie.isExpired(new Date())) {
cookies.add(cookie);
}
}
}
/**
* Adds an array of {@link Cookie HTTP cookies}. Cookies are added
* individually and in the given array order. If any of the given cookies
* has already expired it will not be added, but existing values will still
* be removed.
*
* @param cookies
* the {@link Cookie cookies} to be added
*
* @see #addCookie(Cookie)
*
*/
public void addCookies(Cookie[] cookies) {
if (cookies != null) {
for (Cookie cooky : cookies) {
this.addCookie(cooky);
}
}
}
/**
* Returns an immutable array of {@link Cookie cookies} that this HTTP state
* currently contains.
*
* @return an array of {@link Cookie cookies}.
*/
public List<Cookie> getCookies() {
// create defensive copy so it won't be concurrently modified
return new ArrayList<Cookie>(cookies);
}
/**
* Removes all of {@link Cookie cookies} in this HTTP state that have
* expired by the specified {@link java.util.Date date}.
*
* @return true if any cookies were purged.
*
* @see Cookie#isExpired(Date)
*/
public boolean clearExpired(final Date date) {
if (date == null) {
return false;
}
boolean removed = false;
for (Iterator<Cookie> it = cookies.iterator(); it.hasNext();) {
if (it.next().isExpired(date)) {
it.remove();
removed = true;
}
}
return removed;
}
/**
* Clears all cookies.
*/
public void clear() {
cookies.clear();
}
@Override
public String toString() {
return cookies.toString();
}
}
|
src/main/java/crawlercommons/fetcher/http/LocalCookieStore.java
|
/**
* Copyright 2016 Crawler-Commons
*
* 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 crawlercommons.fetcher.http;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieIdentityComparator;
/**
* Default implementation of {@link CookieStore} Initially copied from
* HttpComponents Changes: removed synchronization
*
*/
@NotThreadSafe
public class LocalCookieStore implements CookieStore, Serializable {
private static final long serialVersionUID = -7581093305228232025L;
private final TreeSet<Cookie> cookies;
public LocalCookieStore() {
super();
this.cookies = new TreeSet<Cookie>(new CookieIdentityComparator());
}
/**
* Adds an {@link Cookie HTTP cookie}, replacing any existing equivalent
* cookies. If the given ookie has already expired it will not be added, but
* existing values will still be removed.
*
* @param cookie
* the {@link Cookie cookie} to be added
*
* @see #addCookies(Cookie[])
*
*/
public void addCookie(Cookie cookie) {
if (cookie != null) {
// first remove any old cookie that is equivalent
cookies.remove(cookie);
if (!cookie.isExpired(new Date())) {
cookies.add(cookie);
}
}
}
/**
* Adds an array of {@link Cookie HTTP cookies}. Cookies are added
* individually and in the given array order. If any of the given cookies
* has already expired it will not be added, but existing values will still
* be removed.
*
* @param cookies
* the {@link Cookie cookies} to be added
*
* @see #addCookie(Cookie)
*
*/
public void addCookies(Cookie[] cookies) {
if (cookies != null) {
for (Cookie cooky : cookies) {
this.addCookie(cooky);
}
}
}
/**
* Returns an immutable array of {@link Cookie cookies} that this HTTP state
* currently contains.
*
* @return an array of {@link Cookie cookies}.
*/
public List<Cookie> getCookies() {
// create defensive copy so it won't be concurrently modified
return new ArrayList<Cookie>(cookies);
}
/**
* Removes all of {@link Cookie cookies} in this HTTP state that have
* expired by the specified {@link java.util.Date date}.
*
* @return true if any cookies were purged.
*
* @see Cookie#isExpired(Date)
*/
public boolean clearExpired(final Date date) {
if (date == null) {
return false;
}
boolean removed = false;
for (Iterator<Cookie> it = cookies.iterator(); it.hasNext();) {
if (it.next().isExpired(date)) {
it.remove();
removed = true;
}
}
return removed;
}
/**
* Clears all cookies.
*/
public void clear() {
cookies.clear();
}
@Override
public String toString() {
return cookies.toString();
}
}
|
Fix missing annotation
|
src/main/java/crawlercommons/fetcher/http/LocalCookieStore.java
|
Fix missing annotation
|
|
Java
|
apache-2.0
|
208e848060f8c4ade8ebd583a70700d665bde770
| 0
|
quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus
|
package io.quarkus.cli;
import static io.quarkus.registry.Constants.DEFAULT_REGISTRY_ID;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import io.quarkus.cli.registry.BaseRegistryCommand;
import io.quarkus.registry.config.RegistriesConfig;
import io.quarkus.registry.config.RegistryConfig;
import picocli.CommandLine;
@CommandLine.Command(name = "add", header = "Add a Quarkus extension registry", description = "%n"
+ "This command will add a Quarkus extension registry to the registry client configuration unless it's already present.")
public class RegistryAddCommand extends BaseRegistryCommand {
@CommandLine.Parameters(arity = "1..*", split = ",", paramLabel = "REGISTRY-ID[,REGISTRY-ID]", description = "Registry ID to add to the registry client configuration%n"
+ " Example:%n"
+ " registry.quarkus.io%n"
+ " registry.quarkus.acme.com,registry.quarkus.io%n")
List<String> registryIds;
@Override
public Integer call() throws Exception {
boolean existingConfig = false;
Path configYaml = null;
// If a configuration was specified, check if it exists
if (registryClient.getConfigArg() != null) {
configYaml = Paths.get(registryClient.getConfigArg());
existingConfig = Files.exists(configYaml);
}
final RegistriesConfig.Mutable config;
if (configYaml != null && !existingConfig) {
// we're creating a new configuration for a new file
config = RegistriesConfig.builder();
} else {
config = registryClient.resolveConfig().mutable();
}
registryClient.refreshRegistryCache(output);
boolean persist = false;
for (String registryId : registryIds) {
persist |= config.addRegistry(registryId);
}
if (persist) {
output.printText("Configured registries:");
for (RegistryConfig rc : config.getRegistries()) {
if (!existingConfig && config.getRegistries().size() == 1
&& !rc.getId().equals(DEFAULT_REGISTRY_ID)) {
output.warn(
rc.getId() + " is the only registry configured in the config file.\n" + rc.getId()
+ " replaced the Default registry: "
+ DEFAULT_REGISTRY_ID);
} else {
output.printText("- " + rc.getId());
}
}
if (configYaml != null) {
config.persist(configYaml);
} else {
config.persist();
}
}
return CommandLine.ExitCode.OK;
}
}
|
devtools/cli/src/main/java/io/quarkus/cli/RegistryAddCommand.java
|
package io.quarkus.cli;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import io.quarkus.cli.registry.BaseRegistryCommand;
import io.quarkus.registry.config.RegistriesConfig;
import io.quarkus.registry.config.RegistryConfig;
import picocli.CommandLine;
@CommandLine.Command(name = "add", header = "Add a Quarkus extension registry", description = "%n"
+ "This command will add a Quarkus extension registry to the registry client configuration unless it's already present.")
public class RegistryAddCommand extends BaseRegistryCommand {
@CommandLine.Parameters(arity = "1..*", split = ",", paramLabel = "REGISTRY-ID[,REGISTRY-ID]", description = "Registry ID to add to the registry client configuration%n"
+ " Example:%n"
+ " registry.quarkus.io%n"
+ " registry.quarkus.acme.com,registry.quarkus.io%n")
List<String> registryIds;
@Override
public Integer call() throws Exception {
boolean existingConfig = false;
Path configYaml = null;
// If a configuration was specified, check if it exists
if (registryClient.getConfigArg() != null) {
configYaml = Paths.get(registryClient.getConfigArg());
existingConfig = Files.exists(configYaml);
}
final RegistriesConfig.Mutable config;
if (configYaml != null && !existingConfig) {
// we're creating a new configuration for a new file
config = RegistriesConfig.builder();
} else {
config = registryClient.resolveConfig().mutable();
}
registryClient.refreshRegistryCache(output);
boolean persist = false;
for (String registryId : registryIds) {
persist |= config.addRegistry(registryId);
}
if (persist) {
output.printText("Configured registries:");
for (RegistryConfig rc : config.getRegistries()) {
output.printText("- " + rc.getId());
}
if (configYaml != null) {
config.persist(configYaml);
} else {
config.persist();
}
}
return CommandLine.ExitCode.OK;
}
}
|
add warning if no registry set.
|
devtools/cli/src/main/java/io/quarkus/cli/RegistryAddCommand.java
|
add warning if no registry set.
|
|
Java
|
apache-2.0
|
63845eeb79f7fc6479a26e843846c25f4a6242f0
| 0
|
AlanJinTS/zstack,MatheMatrix/zstack,AlanJinTS/zstack,AlanJager/zstack,AlanJager/zstack,camilesing/zstack,MaJin1996/zstack,camilesing/zstack,AlanJinTS/zstack,WangXijue/zstack,zstackorg/zstack,zsyzsyhao/zstack,Alvin-Lau/zstack,zxwing/zstack-1,zstackio/zstack,mingjian2049/zstack,HeathHose/zstack,zxwing/zstack-1,Alvin-Lau/zstack,zstackio/zstack,liningone/zstack,zstackorg/zstack,zstackio/zstack,hhjuliet/zstack,winger007/zstack,AlanJager/zstack,camilesing/zstack,hhjuliet/zstack,WangXijue/zstack,zxwing/zstack-1,zsyzsyhao/zstack,MatheMatrix/zstack,MaJin1996/zstack,HeathHose/zstack,Alvin-Lau/zstack,mingjian2049/zstack,winger007/zstack,WangXijue/zstack,MatheMatrix/zstack,liningone/zstack,mingjian2049/zstack,liningone/zstack,HeathHose/zstack
|
package org.zstack.header.vm;
import org.zstack.header.configuration.PythonClass;
import org.zstack.header.exception.CloudRuntimeException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@PythonClass
public enum VmInstanceState {
Created(null),
Starting(VmInstanceStateEvent.starting),
Running(VmInstanceStateEvent.running),
Stopping(VmInstanceStateEvent.stopping),
Stopped(VmInstanceStateEvent.stopped),
Rebooting(VmInstanceStateEvent.rebooting),
Destroying(VmInstanceStateEvent.destroying),
Destroyed(VmInstanceStateEvent.destroyed),
Migrating(VmInstanceStateEvent.migrating),
Expunging(VmInstanceStateEvent.expunging),
Pausing(VmInstanceStateEvent.pausing),
Paused(VmInstanceStateEvent.paused),
Resuming(VmInstanceStateEvent.resuming),
Error(null),
Unknown(VmInstanceStateEvent.unknown);
public static List<VmInstanceState> intermediateStates = new ArrayList<VmInstanceState>();
static {
intermediateStates.add(Starting);
intermediateStates.add(Stopping);
intermediateStates.add(Rebooting);
intermediateStates.add(Destroying);
intermediateStates.add(Migrating);
intermediateStates.add(Pausing);
intermediateStates.add(Resuming);
Created.transactions(
new Transaction(VmInstanceStateEvent.starting, VmInstanceState.Starting),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.destroyed, VmInstanceState.Destroyed)
);
Starting.transactions(
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown)
);
Running.transactions(
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.stopping, VmInstanceState.Stopping),
new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped),
new Transaction(VmInstanceStateEvent.rebooting, VmInstanceState.Rebooting),
new Transaction(VmInstanceStateEvent.migrating, VmInstanceState.Migrating),
new Transaction(VmInstanceStateEvent.pausing, VmInstanceState.Pausing),
new Transaction(VmInstanceStateEvent.paused, VmInstanceState.Paused),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown)
);
Stopping.transactions(
new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown)
);
Stopped.transactions(
new Transaction(VmInstanceStateEvent.starting, VmInstanceState.Starting),
new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped),
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown)
);
Migrating.transactions(
new Transaction(VmInstanceStateEvent.migrated, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying)
);
Rebooting.transactions(
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying)
);
Paused.transactions(
new Transaction(VmInstanceStateEvent.resuming, VmInstanceState.Resuming),
//new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped),
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.stopping, VmInstanceState.Stopping),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown),
new Transaction(VmInstanceStateEvent.migrating, VmInstanceState.Migrating)
);
Pausing.transactions(
new Transaction(VmInstanceStateEvent.paused, VmInstanceState.Paused),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown)
);
Resuming.transactions(
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.paused, VmInstanceState.Paused),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown)
);
Unknown.transactions(
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.stopping, VmInstanceState.Stopping),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown),
new Transaction(VmInstanceStateEvent.paused,VmInstanceState.Paused),
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped)
);
Destroying.transactions(
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown),
new Transaction(VmInstanceStateEvent.destroyed, VmInstanceState.Destroyed),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.expunging, VmInstanceState.Expunging)
);
Destroyed.transactions(
new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped)
);
}
private VmInstanceState(VmInstanceStateEvent drivenEvent) {
this.drivenEvent = drivenEvent;
}
private static class Transaction {
VmInstanceStateEvent event;
VmInstanceState nextState;
private Transaction(VmInstanceStateEvent event, VmInstanceState nextState) {
this.event = event;
this.nextState = nextState;
}
}
private Map<VmInstanceStateEvent, Transaction> transactionMap = new HashMap<VmInstanceStateEvent, Transaction>();
private VmInstanceStateEvent drivenEvent;
public VmInstanceStateEvent getDrivenEvent() {
return drivenEvent;
}
private void transactions(Transaction... transactions) {
for (Transaction tran : transactions) {
transactionMap.put(tran.event, tran);
}
}
public VmInstanceState nextState(VmInstanceStateEvent event) {
Transaction tran = transactionMap.get(event);
if (tran == null) {
throw new CloudRuntimeException(String.format("cannot find next state for current state[%s] on transaction event[%s]",
this, event));
}
return tran.nextState;
}
}
|
header/src/main/java/org/zstack/header/vm/VmInstanceState.java
|
package org.zstack.header.vm;
import org.zstack.header.configuration.PythonClass;
import org.zstack.header.exception.CloudRuntimeException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@PythonClass
public enum VmInstanceState {
Created(null),
Starting(VmInstanceStateEvent.starting),
Running(VmInstanceStateEvent.running),
Stopping(VmInstanceStateEvent.stopping),
Stopped(VmInstanceStateEvent.stopped),
Rebooting(VmInstanceStateEvent.rebooting),
Destroying(VmInstanceStateEvent.destroying),
Destroyed(VmInstanceStateEvent.destroyed),
Migrating(VmInstanceStateEvent.migrating),
Expunging(VmInstanceStateEvent.expunging),
Pausing(VmInstanceStateEvent.pausing),
Paused(VmInstanceStateEvent.paused),
Resuming(VmInstanceStateEvent.resuming),
Error(null),
Unknown(VmInstanceStateEvent.unknown);
public static List<VmInstanceState> intermediateStates = new ArrayList<VmInstanceState>();
static {
intermediateStates.add(Starting);
intermediateStates.add(Stopping);
intermediateStates.add(Rebooting);
intermediateStates.add(Destroying);
intermediateStates.add(Migrating);
intermediateStates.add(Pausing);
intermediateStates.add(Resuming);
Created.transactions(
new Transaction(VmInstanceStateEvent.starting, VmInstanceState.Starting),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.destroyed, VmInstanceState.Destroyed)
);
Starting.transactions(
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown)
);
Running.transactions(
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.stopping, VmInstanceState.Stopping),
new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped),
new Transaction(VmInstanceStateEvent.rebooting, VmInstanceState.Rebooting),
new Transaction(VmInstanceStateEvent.migrating, VmInstanceState.Migrating),
new Transaction(VmInstanceStateEvent.pausing, VmInstanceState.Pausing),
new Transaction(VmInstanceStateEvent.paused, VmInstanceState.Paused),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown)
);
Stopping.transactions(
new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown)
);
Stopped.transactions(
new Transaction(VmInstanceStateEvent.starting, VmInstanceState.Starting),
new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped),
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown)
);
Migrating.transactions(
new Transaction(VmInstanceStateEvent.migrated, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying)
);
Rebooting.transactions(
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying)
);
Paused.transactions(
new Transaction(VmInstanceStateEvent.resuming, VmInstanceState.Resuming),
//new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped),
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.stopping, VmInstanceState.Stopping),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown)
);
Pausing.transactions(
new Transaction(VmInstanceStateEvent.paused, VmInstanceState.Paused),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown)
);
Resuming.transactions(
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.paused, VmInstanceState.Paused),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown)
);
Unknown.transactions(
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.stopping, VmInstanceState.Stopping),
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown),
new Transaction(VmInstanceStateEvent.paused,VmInstanceState.Paused),
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped)
);
Destroying.transactions(
new Transaction(VmInstanceStateEvent.unknown, VmInstanceState.Unknown),
new Transaction(VmInstanceStateEvent.destroyed, VmInstanceState.Destroyed),
new Transaction(VmInstanceStateEvent.destroying, VmInstanceState.Destroying),
new Transaction(VmInstanceStateEvent.running, VmInstanceState.Running),
new Transaction(VmInstanceStateEvent.expunging, VmInstanceState.Expunging)
);
Destroyed.transactions(
new Transaction(VmInstanceStateEvent.stopped, VmInstanceState.Stopped)
);
}
private VmInstanceState(VmInstanceStateEvent drivenEvent) {
this.drivenEvent = drivenEvent;
}
private static class Transaction {
VmInstanceStateEvent event;
VmInstanceState nextState;
private Transaction(VmInstanceStateEvent event, VmInstanceState nextState) {
this.event = event;
this.nextState = nextState;
}
}
private Map<VmInstanceStateEvent, Transaction> transactionMap = new HashMap<VmInstanceStateEvent, Transaction>();
private VmInstanceStateEvent drivenEvent;
public VmInstanceStateEvent getDrivenEvent() {
return drivenEvent;
}
private void transactions(Transaction... transactions) {
for (Transaction tran : transactions) {
transactionMap.put(tran.event, tran);
}
}
public VmInstanceState nextState(VmInstanceStateEvent event) {
Transaction tran = transactionMap.get(event);
if (tran == null) {
throw new CloudRuntimeException(String.format("cannot find next state for current state[%s] on transaction event[%s]",
this, event));
}
return tran.nextState;
}
}
|
fix live migrate a paused vm issue
for https://github.com/zxwing/premium/issues/1950
Signed-off-by: Mei Lei <d1c6e4e75080176552ef8271b379adabccaa7551@gmail.com>
|
header/src/main/java/org/zstack/header/vm/VmInstanceState.java
|
fix live migrate a paused vm issue
|
|
Java
|
apache-2.0
|
a23d51a5724c2e1c96ec33fdcc824d6c9465b41b
| 0
|
cloudera/recordservice,scalingdata/Impala,scalingdata/Impala,scalingdata/Impala,scalingdata/Impala,cloudera/recordservice,cloudera/recordservice,cloudera/recordservice,cloudera/recordservice,cloudera/recordservice,scalingdata/Impala,cloudera/recordservice,scalingdata/Impala
|
// Copyright (c) 2012 Cloudera, 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.cloudera.impala.analysis;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import junit.framework.Assert;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.junit.Test;
import com.cloudera.impala.catalog.CatalogException;
import com.cloudera.impala.catalog.DataSource;
import com.cloudera.impala.catalog.DataSourceTable;
import com.cloudera.impala.catalog.PrimitiveType;
import com.cloudera.impala.catalog.ScalarType;
import com.cloudera.impala.catalog.Type;
import com.cloudera.impala.common.AnalysisException;
import com.cloudera.impala.common.FileSystemUtil;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
public class AnalyzeDDLTest extends AnalyzerTest {
@Test
public void TestAlterTableAddDropPartition() throws CatalogException {
String[] addDrop = {"add if not exists", "drop if exists"};
for (String kw: addDrop) {
// Add different partitions for different column types
AnalyzesOk("alter table functional.alltypes " + kw +
" partition(year=2050, month=10)");
AnalyzesOk("alter table functional.alltypes " + kw +
" partition(month=10, year=2050)");
AnalyzesOk("alter table functional.insert_string_partitioned " + kw +
" partition(s2='1234')");
// Can't add/drop partitions to/from unpartitioned tables
AnalysisError("alter table functional.alltypesnopart " + kw + " partition (i=1)",
"Table is not partitioned: functional.alltypesnopart");
AnalysisError("alter table functional_hbase.alltypesagg " + kw +
" partition (i=1)", "Table is not partitioned: functional_hbase.alltypesagg");
// Duplicate partition key name
AnalysisError("alter table functional.alltypes " + kw +
" partition(year=2050, year=2051)", "Duplicate partition key name: year");
// Not a partition column
AnalysisError("alter table functional.alltypes " + kw +
" partition(year=2050, int_col=1)",
"Column 'int_col' is not a partition column in table: functional.alltypes");
// NULL partition keys
AnalyzesOk("alter table functional.alltypes " + kw +
" partition(year=NULL, month=1)");
AnalyzesOk("alter table functional.alltypes " + kw +
" partition(year=NULL, month=NULL)");
AnalyzesOk("alter table functional.alltypes " + kw +
" partition(year=ascii(null), month=ascii(NULL))");
// Empty string partition keys
AnalyzesOk("alter table functional.insert_string_partitioned " + kw +
" partition(s2='')");
// Arbitrary exprs as partition key values. Constant exprs are ok.
AnalyzesOk("alter table functional.alltypes " + kw +
" partition(year=-1, month=cast((10+5*4) as INT))");
// Arbitrary exprs as partition key values. Non-constant exprs should fail.
AnalysisError("alter table functional.alltypes " + kw +
" partition(year=2050, month=int_col)",
"Non-constant expressions are not supported as static partition-key values " +
"in 'month=int_col'.");
AnalysisError("alter table functional.alltypes " + kw +
" partition(year=cast(int_col as int), month=12)",
"Non-constant expressions are not supported as static partition-key values " +
"in 'year=CAST(int_col AS INT)'.");
// Not a valid column
AnalysisError("alter table functional.alltypes " + kw +
" partition(year=2050, blah=1)",
"Partition column 'blah' not found in table: functional.alltypes");
// Data types don't match
AnalysisError(
"alter table functional.insert_string_partitioned " + kw +
" partition(s2=1234)",
"Value of partition spec (column=s2) has incompatible type: 'SMALLINT'. " +
"Expected type: 'STRING'.");
// Loss of precision
AnalysisError(
"alter table functional.alltypes " + kw +
" partition(year=100000000000, month=10)",
"Partition key value may result in loss of precision.\nWould need to cast" +
" '100000000000' to 'INT' for partition column: year");
// Table/Db does not exist
AnalysisError("alter table db_does_not_exist.alltypes " + kw +
" partition (i=1)", "Database does not exist: db_does_not_exist");
AnalysisError("alter table functional.table_does_not_exist " + kw +
" partition (i=1)", "Table does not exist: functional.table_does_not_exist");
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view " + kw +
" partition(year=2050, month=10)",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
AnalysisError("alter table functional.alltypes_datasource " + kw +
" partition(year=2050, month=10)",
"ALTER TABLE not allowed on a table produced by a data source: " +
"functional.alltypes_datasource");
}
// IF NOT EXISTS properly checks for partition existence
AnalyzesOk("alter table functional.alltypes add " +
"partition(year=2050, month=10)");
AnalysisError("alter table functional.alltypes add " +
"partition(year=2010, month=10)",
"Partition spec already exists: (year=2010, month=10).");
AnalyzesOk("alter table functional.alltypes add if not exists " +
" partition(year=2010, month=10)");
AnalyzesOk("alter table functional.alltypes add if not exists " +
" partition(year=2010, month=10) location " +
"'/test-warehouse/alltypes/year=2010/month=10'");
// IF EXISTS properly checks for partition existence
AnalyzesOk("alter table functional.alltypes drop " +
"partition(year=2010, month=10)");
AnalysisError("alter table functional.alltypes drop " +
"partition(year=2050, month=10)",
"Partition spec does not exist: (year=2050, month=10).");
AnalyzesOk("alter table functional.alltypes drop if exists " +
"partition(year=2050, month=10)");
// Caching ops
AnalyzesOk("alter table functional.alltypes add " +
"partition(year=2050, month=10) cached in 'testPool'");
AnalyzesOk("alter table functional.alltypes add " +
"partition(year=2050, month=10) cached in 'testPool' with replication = 10");
AnalyzesOk("alter table functional.alltypes add " +
"partition(year=2050, month=10) uncached");
AnalysisError("alter table functional.alltypes add " +
"partition(year=2050, month=10) cached in 'badPool'",
"The specified cache pool does not exist: badPool");
// Valid URIs.
AnalyzesOk("alter table functional.alltypes add " +
" partition(year=2050, month=10) location " +
"'/test-warehouse/alltypes/year=2010/month=10'");
AnalyzesOk("alter table functional.alltypes add " +
" partition(year=2050, month=10) location " +
"'hdfs://localhost:20500/test-warehouse/alltypes/year=2010/month=10'");
AnalyzesOk("alter table functional.alltypes add " +
" partition(year=2050, month=10) location " +
"'s3n://bucket/test-warehouse/alltypes/year=2010/month=10'");
AnalyzesOk("alter table functional.alltypes add " +
" partition(year=2050, month=10) location " +
"'file:///test-warehouse/alltypes/year=2010/month=10'");
// Invalid URIs.
AnalysisError("alter table functional.alltypes add " +
" partition(year=2050, month=10) location " +
"'foofs://bar/test-warehouse/alltypes/year=2010/month=10'",
"No FileSystem for scheme: foofs");
AnalysisError("alter table functional.alltypes add " +
" partition(year=2050, month=10) location ' '",
"URI path cannot be empty.");
}
@Test
public void TestAlterTableAddReplaceColumns() throws AnalysisException {
AnalyzesOk("alter table functional.alltypes add columns (new_col int)");
AnalyzesOk("alter table functional.alltypes add columns (c1 string comment 'hi')");
AnalyzesOk("alter table functional.alltypes add columns (c struct<f1:int>)");
AnalyzesOk(
"alter table functional.alltypes replace columns (c1 int comment 'c', c2 int)");
AnalyzesOk("alter table functional.alltypes replace columns (c array<string>)");
// Column name must be unique for add
AnalysisError("alter table functional.alltypes add columns (int_col int)",
"Column already exists: int_col");
// Add a column with same name as a partition column
AnalysisError("alter table functional.alltypes add columns (year int)",
"Column name conflicts with existing partition column: year");
// Invalid column name.
AnalysisError("alter table functional.alltypes add columns (`???` int)",
"Invalid column/field name: ???");
AnalysisError("alter table functional.alltypes replace columns (`???` int)",
"Invalid column/field name: ???");
// Replace should not throw an error if the column already exists
AnalyzesOk("alter table functional.alltypes replace columns (int_col int)");
// It is not possible to replace a partition column
AnalysisError("alter table functional.alltypes replace columns (Year int)",
"Column name conflicts with existing partition column: year");
// Duplicate column names
AnalysisError("alter table functional.alltypes add columns (c1 int, c1 int)",
"Duplicate column name: c1");
AnalysisError("alter table functional.alltypes replace columns (c1 int, C1 int)",
"Duplicate column name: c1");
// Table/Db does not exist
AnalysisError("alter table db_does_not_exist.alltypes add columns (i int)",
"Database does not exist: db_does_not_exist");
AnalysisError("alter table functional.table_does_not_exist add columns (i int)",
"Table does not exist: functional.table_does_not_exist");
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view " +
"add columns (c1 string comment 'hi')",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
// Cannot ALTER TABLE produced by a data source.
AnalysisError("alter table functional.alltypes_datasource " +
"add columns (c1 string comment 'hi')",
"ALTER TABLE not allowed on a table produced by a data source: " +
"functional.alltypes_datasource");
// Cannot ALTER TABLE ADD/REPLACE COLUMNS on an HBase table.
AnalysisError("alter table functional_hbase.alltypes add columns (i int)",
"ALTER TABLE ADD|REPLACE COLUMNS not currently supported on HBase tables.");
}
@Test
public void TestAlterTableDropColumn() throws AnalysisException {
AnalyzesOk("alter table functional.alltypes drop column int_col");
AnalysisError("alter table functional.alltypes drop column no_col",
"Column 'no_col' does not exist in table: functional.alltypes");
AnalysisError("alter table functional.alltypes drop column year",
"Cannot drop partition column: year");
// Tables should always have at least 1 column
AnalysisError("alter table functional_seq_snap.bad_seq_snap drop column field",
"Cannot drop column 'field' from functional_seq_snap.bad_seq_snap. " +
"Tables must contain at least 1 column.");
// Table/Db does not exist
AnalysisError("alter table db_does_not_exist.alltypes drop column col1",
"Database does not exist: db_does_not_exist");
AnalysisError("alter table functional.table_does_not_exist drop column col1",
"Table does not exist: functional.table_does_not_exist");
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view drop column int_col",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
// Cannot ALTER TABLE produced by a data source.
AnalysisError("alter table functional.alltypes_datasource drop column int_col",
"ALTER TABLE not allowed on a table produced by a data source: " +
"functional.alltypes_datasource");
// Cannot ALTER TABLE DROP COLUMN on an HBase table.
AnalysisError("alter table functional_hbase.alltypes drop column int_col",
"ALTER TABLE DROP COLUMN not currently supported on HBase tables.");
}
@Test
public void TestAlterTableChangeColumn() throws AnalysisException {
// Rename a column
AnalyzesOk("alter table functional.alltypes change column int_col int_col2 int");
// Rename and change the datatype
AnalyzesOk("alter table functional.alltypes change column int_col c2 string");
AnalyzesOk(
"alter table functional.alltypes change column int_col c2 map<int, string>");
// Change only the datatype
AnalyzesOk("alter table functional.alltypes change column int_col int_col tinyint");
// Add a comment to a column.
AnalyzesOk("alter table functional.alltypes change int_col int_col int comment 'c'");
AnalysisError("alter table functional.alltypes change column no_col c1 int",
"Column 'no_col' does not exist in table: functional.alltypes");
AnalysisError("alter table functional.alltypes change column year year int",
"Cannot modify partition column: year");
AnalysisError(
"alter table functional.alltypes change column int_col Tinyint_col int",
"Column already exists: Tinyint_col");
// Invalid column name.
AnalysisError("alter table functional.alltypes change column int_col `???` int",
"Invalid column/field name: ???");
// Table/Db does not exist
AnalysisError("alter table db_does_not_exist.alltypes change c1 c2 int",
"Database does not exist: db_does_not_exist");
AnalysisError("alter table functional.table_does_not_exist change c1 c2 double",
"Table does not exist: functional.table_does_not_exist");
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view " +
"change column int_col int_col2 int",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
// Cannot ALTER TABLE produced by a data source.
AnalysisError("alter table functional.alltypes_datasource " +
"change column int_col int_col2 int",
"ALTER TABLE not allowed on a table produced by a data source: " +
"functional.alltypes_datasource");
// Cannot ALTER TABLE CHANGE COLUMN on an HBase table.
AnalysisError("alter table functional_hbase.alltypes CHANGE COLUMN int_col i int",
"ALTER TABLE CHANGE COLUMN not currently supported on HBase tables.");
}
@Test
public void TestAlterTableSet() throws AnalysisException {
AnalyzesOk("alter table functional.alltypes set fileformat sequencefile");
AnalyzesOk("alter table functional.alltypes set location '/a/b'");
AnalyzesOk("alter table functional.alltypes set tblproperties('a'='1')");
AnalyzesOk("alter table functional.alltypes set serdeproperties('a'='2')");
AnalyzesOk("alter table functional.alltypes PARTITION (Year=2010, month=11) " +
"set location '/a/b'");
AnalyzesOk("alter table functional.alltypes PARTITION (month=11, year=2010) " +
"set fileformat parquetfile");
AnalyzesOk("alter table functional.stringpartitionkey PARTITION " +
"(string_col='partition1') set fileformat parquet");
AnalyzesOk("alter table functional.stringpartitionkey PARTITION " +
"(string_col='PaRtiTion1') set location '/a/b/c'");
AnalyzesOk("alter table functional.alltypes PARTITION (year=2010, month=11) " +
"set tblproperties('a'='1')");
AnalyzesOk("alter table functional.alltypes PARTITION (year=2010, month=11) " +
"set serdeproperties ('a'='2')");
// Arbitrary exprs as partition key values. Constant exprs are ok.
AnalyzesOk("alter table functional.alltypes PARTITION " +
"(year=cast(100*20+10 as INT), month=cast(2+9 as INT)) " +
"set fileformat sequencefile");
AnalyzesOk("alter table functional.alltypes PARTITION " +
"(year=cast(100*20+10 as INT), month=cast(2+9 as INT)) " +
"set location '/a/b'");
// Arbitrary exprs as partition key values. Non-constant exprs should fail.
AnalysisError("alter table functional.alltypes PARTITION " +
"(Year=2050, month=int_col) set fileformat sequencefile",
"Non-constant expressions are not supported as static partition-key " +
"values in 'month=int_col'.");
AnalysisError("alter table functional.alltypes PARTITION " +
"(Year=2050, month=int_col) set location '/a/b'",
"Non-constant expressions are not supported as static partition-key " +
"values in 'month=int_col'.");
// Partition spec does not exist
AnalysisError("alter table functional.alltypes PARTITION (year=2014, month=11) " +
"set location '/a/b'",
"Partition spec does not exist: (year=2014, month=11)");
AnalysisError("alter table functional.alltypes PARTITION (year=2014, month=11) " +
"set tblproperties('a'='1')",
"Partition spec does not exist: (year=2014, month=11)");
AnalysisError("alter table functional.alltypes PARTITION (year=2010) " +
"set tblproperties('a'='1')",
"Items in partition spec must exactly match the partition columns " +
"in the table definition: functional.alltypes (1 vs 2)");
AnalysisError("alter table functional.alltypes PARTITION (year=2010, year=2010) " +
"set location '/a/b'",
"Duplicate partition key name: year");
AnalysisError("alter table functional.alltypes PARTITION (month=11, year=2014) " +
"set fileformat sequencefile",
"Partition spec does not exist: (month=11, year=2014)");
AnalysisError("alter table functional.alltypesnopart PARTITION (month=1) " +
"set fileformat sequencefile",
"Table is not partitioned: functional.alltypesnopart");
AnalysisError("alter table functional.alltypesnopart PARTITION (month=1) " +
"set location '/a/b/c'",
"Table is not partitioned: functional.alltypesnopart");
AnalysisError("alter table functional.stringpartitionkey PARTITION " +
"(string_col='partition2') set location '/a/b'",
"Partition spec does not exist: (string_col='partition2')");
AnalysisError("alter table functional.stringpartitionkey PARTITION " +
"(string_col='partition2') set fileformat sequencefile",
"Partition spec does not exist: (string_col='partition2')");
AnalysisError("alter table functional.alltypes PARTITION " +
"(year=cast(10*20+10 as INT), month=cast(5*3 as INT)) " +
"set location '/a/b'",
"Partition spec does not exist: " +
"(year=CAST(10 * 20 + 10 AS INT), month=CAST(5 * 3 AS INT))");
AnalysisError("alter table functional.alltypes PARTITION " +
"(year=cast(10*20+10 as INT), month=cast(5*3 as INT)) " +
"set fileformat sequencefile",
"Partition spec does not exist: " +
"(year=CAST(10 * 20 + 10 AS INT), month=CAST(5 * 3 AS INT))");
// Table/Db does not exist
AnalysisError("alter table db_does_not_exist.alltypes set fileformat sequencefile",
"Database does not exist: db_does_not_exist");
AnalysisError("alter table functional.table_does_not_exist set fileformat rcfile",
"Table does not exist: functional.table_does_not_exist");
AnalysisError("alter table db_does_not_exist.alltypes set location '/a/b'",
"Database does not exist: db_does_not_exist");
AnalysisError("alter table functional.table_does_not_exist set location '/a/b'",
"Table does not exist: functional.table_does_not_exist");
AnalysisError("alter table functional.no_tbl partition(i=1) set location '/a/b'",
"Table does not exist: functional.no_tbl");
AnalysisError("alter table no_db.alltypes partition(i=1) set fileformat textfile",
"Database does not exist: no_db");
// Valid location
AnalyzesOk("alter table functional.alltypes set location " +
"'hdfs://localhost:20500/test-warehouse/a/b'");
AnalyzesOk("alter table functional.alltypes set location " +
"'s3n://bucket/test-warehouse/a/b'");
AnalyzesOk("alter table functional.alltypes set location " +
"'file:///test-warehouse/a/b'");
// Invalid location
AnalysisError("alter table functional.alltypes set location 'test/warehouse'",
"URI path must be absolute: test/warehouse");
AnalysisError("alter table functional.alltypes set location 'blah:///warehouse/'",
"No FileSystem for scheme: blah");
AnalysisError("alter table functional.alltypes set location ''",
"URI path cannot be empty.");
AnalysisError("alter table functional.alltypes set location ' '",
"URI path cannot be empty.");
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view set fileformat sequencefile",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
// Cannot ALTER TABLE produced by a data source.
AnalysisError("alter table functional.alltypes_datasource set fileformat parquet",
"ALTER TABLE not allowed on a table produced by a data source: " +
"functional.alltypes_datasource");
// Cannot ALTER TABLE SET on an HBase table.
AnalysisError("alter table functional_hbase.alltypes set tblproperties('a'='b')",
"ALTER TABLE SET not currently supported on HBase tables.");
}
@Test
public void TestAlterTableSetCached() {
// Positive cases
AnalyzesOk("alter table functional.alltypesnopart set cached in 'testPool'");
AnalyzesOk("alter table functional.alltypes set cached in 'testPool'");
AnalyzesOk("alter table functional.alltypes partition(year=2010, month=12) " +
"set cached in 'testPool'");
// Replication factor
AnalyzesOk("alter table functional.alltypes set cached in 'testPool' " +
"with replication = 10");
AnalyzesOk("alter table functional.alltypes partition(year=2010, month=12) " +
"set cached in 'testPool' with replication = 4");
AnalysisError("alter table functional.alltypes set cached in 'testPool' " +
"with replication = 0",
"Cache replication factor must be between 0 and Short.MAX_VALUE");
AnalysisError("alter table functional.alltypes set cached in 'testPool' " +
"with replication = 90000",
"Cache replication factor must be between 0 and Short.MAX_VALUE");
// Attempt to alter a table that is not backed by HDFS.
AnalysisError("alter table functional_hbase.alltypesnopart set cached in 'testPool'",
"ALTER TABLE SET not currently supported on HBase tables.");
AnalysisError("alter table functional.view_view set cached in 'testPool'",
"ALTER TABLE not allowed on a view: functional.view_view");
AnalysisError("alter table functional.alltypes set cached in 'badPool'",
"The specified cache pool does not exist: badPool");
AnalysisError("alter table functional.alltypes partition(year=2010, month=12) " +
"set cached in 'badPool'", "The specified cache pool does not exist: badPool");
// Attempt to uncache a table that is not cached. Should be a no-op.
AnalyzesOk("alter table functional.alltypes set uncached");
AnalyzesOk("alter table functional.alltypes partition(year=2010, month=12) " +
"set uncached");
// Attempt to cache a table that is already cached. Should be a no-op.
AnalyzesOk("alter table functional.alltypestiny set cached in 'testPool'");
AnalyzesOk("alter table functional.alltypestiny partition(year=2009, month=1) " +
"set cached in 'testPool'");
// Change location of a cached table/partition
AnalysisError("alter table functional.alltypestiny set location '/tmp/tiny'",
"Target table is cached, please uncache before changing the location using: " +
"ALTER TABLE functional.alltypestiny SET UNCACHED");
AnalysisError("alter table functional.alltypestiny partition (year=2009,month=1) " +
"set location '/test-warehouse/new_location'",
"Target partition is cached, please uncache before changing the location " +
"using: ALTER TABLE functional.alltypestiny PARTITION (year=2009, month=1) " +
"SET UNCACHED");
// Table/db/partition do not exist
AnalysisError("alter table baddb.alltypestiny set cached in 'testPool'",
"Database does not exist: baddb");
AnalysisError("alter table functional.badtbl set cached in 'testPool'",
"Table does not exist: functional.badtbl");
AnalysisError("alter table functional.alltypestiny partition(year=9999, month=1) " +
"set cached in 'testPool'",
"Partition spec does not exist: (year=9999, month=1).");
}
@Test
public void TestAlterTableRename() throws AnalysisException {
AnalyzesOk("alter table functional.alltypes rename to new_alltypes");
AnalyzesOk("alter table functional.alltypes rename to functional.new_alltypes");
AnalysisError("alter table functional.alltypes rename to functional.alltypes",
"Table already exists: functional.alltypes");
AnalysisError("alter table functional.alltypes rename to functional.alltypesagg",
"Table already exists: functional.alltypesagg");
AnalysisError("alter table functional.table_does_not_exist rename to new_table",
"Table does not exist: functional.table_does_not_exist");
AnalysisError("alter table db_does_not_exist.alltypes rename to new_table",
"Database does not exist: db_does_not_exist");
// Invalid database/table name.
AnalysisError("alter table functional.alltypes rename to `???`.new_table",
"Invalid database name: ???");
AnalysisError("alter table functional.alltypes rename to functional.`%^&`",
"Invalid table/view name: %^&");
AnalysisError(
"alter table functional.alltypes rename to db_does_not_exist.new_table",
"Database does not exist: db_does_not_exist");
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view rename to new_alltypes",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
// It should be okay to rename an HBase table.
AnalyzesOk("alter table functional_hbase.alltypes rename to new_alltypes");
// It should be okay to rename a table produced by a data source.
AnalyzesOk("alter table functional.alltypes_datasource rename to new_datasrc_tbl");
}
@Test
public void TestAlterView() {
// View-definition references a table.
AnalyzesOk("alter view functional.alltypes_view as " +
"select * from functional.alltypesagg");
// View-definition references a view.
AnalyzesOk("alter view functional.alltypes_view as " +
"select * from functional.alltypes_view");
// View-definition resulting in Hive-style auto-generated column names.
AnalyzesOk("alter view functional.alltypes_view as " +
"select trim('abc'), 17 * 7");
// Cannot ALTER VIEW a table.
AnalysisError("alter view functional.alltypes as " +
"select * from functional.alltypesagg",
"ALTER VIEW not allowed on a table: functional.alltypes");
AnalysisError("alter view functional_hbase.alltypesagg as " +
"select * from functional.alltypesagg",
"ALTER VIEW not allowed on a table: functional_hbase.alltypesagg");
// Target database does not exist.
AnalysisError("alter view baddb.alltypes_view as " +
"select * from functional.alltypesagg",
"Database does not exist: baddb");
// Target view does not exist.
AnalysisError("alter view functional.badview as " +
"select * from functional.alltypesagg",
"Table does not exist: functional.badview");
// View-definition statement fails to analyze. Database does not exist.
AnalysisError("alter view functional.alltypes_view as " +
"select * from baddb.alltypesagg",
"Database does not exist: baddb");
// View-definition statement fails to analyze. Table does not exist.
AnalysisError("alter view functional.alltypes_view as " +
"select * from functional.badtable",
"Table does not exist: functional.badtable");
// Duplicate column name.
AnalysisError("alter view functional.alltypes_view as " +
"select * from functional.alltypessmall a inner join " +
"functional.alltypessmall b on a.id = b.id",
"Duplicate column name: id");
// Invalid column name.
AnalysisError("alter view functional.alltypes_view as select 'abc' as `???`",
"Invalid column/field name: ???");
}
@Test
public void TestAlterViewRename() throws AnalysisException {
AnalyzesOk("alter view functional.alltypes_view rename to new_view");
AnalyzesOk("alter view functional.alltypes_view rename to functional.new_view");
AnalysisError("alter view functional.alltypes_view rename to functional.alltypes",
"Table already exists: functional.alltypes");
AnalysisError("alter view functional.alltypes_view rename to functional.alltypesagg",
"Table already exists: functional.alltypesagg");
AnalysisError("alter view functional.view_does_not_exist rename to new_view",
"Table does not exist: functional.view_does_not_exist");
AnalysisError("alter view db_does_not_exist.alltypes_view rename to new_view",
"Database does not exist: db_does_not_exist");
AnalysisError("alter view functional.alltypes_view " +
"rename to db_does_not_exist.new_view",
"Database does not exist: db_does_not_exist");
// Invalid database/table name.
AnalysisError("alter view functional.alltypes_view rename to `???`.new_view",
"Invalid database name: ???");
AnalysisError("alter view functional.alltypes_view rename to functional.`%^&`",
"Invalid table/view name: %^&");
// Cannot ALTER VIEW a able.
AnalysisError("alter view functional.alltypes rename to new_alltypes",
"ALTER VIEW not allowed on a table: functional.alltypes");
}
void checkComputeStatsStmt(String stmt) throws AnalysisException {
ParseNode parseNode = AnalyzesOk(stmt);
assertTrue(parseNode instanceof ComputeStatsStmt);
ComputeStatsStmt parsedStmt = (ComputeStatsStmt)parseNode;
AnalyzesOk(parsedStmt.getTblStatsQuery());
AnalyzesOk(parsedStmt.getColStatsQuery());
}
@Test
public void TestComputeStats() throws AnalysisException {
// Analyze the stmt itself as well as the generated child queries.
checkComputeStatsStmt("compute stats functional.alltypes");
checkComputeStatsStmt("compute stats functional_hbase.alltypes");
// Test that complex-typed columns are ignored.
checkComputeStatsStmt("compute stats functional.allcomplextypes");
// Cannot compute stats on a database.
AnalysisError("compute stats tbl_does_not_exist",
"Table does not exist: default.tbl_does_not_exist");
// Cannot compute stats on a view.
AnalysisError("compute stats functional.alltypes_view",
"COMPUTE STATS not supported for view functional.alltypes_view");
AnalyzesOk("compute stats functional_avro_snap.alltypes");
// Test mismatched column definitions and Avro schema (HIVE-6308, IMPALA-867).
// See testdata/avro_schema_resolution/create_table.sql for the CREATE TABLE stmts.
// Mismatched column type is ok because the conflict is resolved in favor of
// the type in the column definition list in the CREATE TABLE.
AnalyzesOk("compute stats functional_avro_snap.alltypes_type_mismatch");
// Missing column definition is ok because the schema mismatch is resolved
// in the CREATE TABLE.
AnalyzesOk("compute stats functional_avro_snap.alltypes_missing_coldef");
// Extra column definition is ok because the schema mismatch is resolved
// in the CREATE TABLE.
AnalyzesOk("compute stats functional_avro_snap.alltypes_extra_coldef");
// Mismatched column name (tables were created by Hive).
AnalysisError("compute stats functional_avro_snap.schema_resolution_test",
"Cannot COMPUTE STATS on Avro table 'schema_resolution_test' because its " +
"column definitions do not match those in the Avro schema.\nDefinition of " +
"column 'col1' of type 'string' does not match the Avro-schema column " +
"'boolean1' of type 'BOOLEAN' at position '0'.\nPlease re-create the table " +
"with column definitions, e.g., using the result of 'SHOW CREATE TABLE'");
}
@Test
public void TestComputeIncrementalStats() throws AnalysisException {
checkComputeStatsStmt("compute incremental stats functional.alltypes");
checkComputeStatsStmt(
"compute incremental stats functional.alltypes partition(year=2010, month=10)");
AnalysisError(
"compute incremental stats functional.alltypes partition(year=9999, month=10)",
"Partition spec does not exist: (year=9999, month=10)");
AnalysisError(
"compute incremental stats functional.alltypes partition(year=2010)",
"Items in partition spec must exactly match the partition columns in the table " +
"definition: functional.alltypes (1 vs 2)");
AnalysisError(
"compute incremental stats functional.alltypes partition(year=2010, month)",
"Syntax error");
// Test that NULL partitions generates a valid query
checkComputeStatsStmt("compute incremental stats functional.alltypesagg " +
"partition(year=2010, month=1, day=NULL)");
AnalysisError("compute incremental stats functional_hbase.alltypes " +
"partition(year=2010, month=1)", "COMPUTE INCREMENTAL ... PARTITION not " +
"supported for non-HDFS table functional_hbase.alltypes");
AnalysisError("compute incremental stats functional.view_view",
"COMPUTE STATS not supported for view functional.view_view");
}
@Test
public void TestDropIncrementalStats() throws AnalysisException {
AnalyzesOk(
"drop incremental stats functional.alltypes partition(year=2010, month=10)");
AnalysisError(
"drop incremental stats functional.alltypes partition(year=9999, month=10)",
"Partition spec does not exist: (year=9999, month=10)");
}
@Test
public void TestDropStats() throws AnalysisException {
AnalyzesOk("drop stats functional.alltypes");
// Table does not exist
AnalysisError("drop stats tbl_does_not_exist",
"Table does not exist: default.tbl_does_not_exist");
// Database does not exist
AnalysisError("drop stats no_db.no_tbl",
"Database does not exist: no_db");
AnalysisError("drop stats functional.alltypes partition(year=2010, month=10)",
"Syntax error");
AnalysisError("drop stats functional.alltypes partition(year, month)",
"Syntax error");
}
@Test
public void TestDrop() throws AnalysisException {
AnalyzesOk("drop database functional");
AnalyzesOk("drop table functional.alltypes");
AnalyzesOk("drop view functional.alltypes_view");
// If the database does not exist, and the user hasn't specified "IF EXISTS",
// an analysis error should be thrown
AnalysisError("drop database db_does_not_exist",
"Database does not exist: db_does_not_exist");
AnalysisError("drop table db_does_not_exist.alltypes",
"Database does not exist: db_does_not_exist");
AnalysisError("drop view db_does_not_exist.alltypes_view",
"Database does not exist: db_does_not_exist");
// Invalid name reports non-existence instead of invalidity.
AnalysisError("drop database `???`",
"Database does not exist: ???");
AnalysisError("drop table functional.`%^&`",
"Table does not exist: functional.%^&");
AnalysisError("drop view functional.`@#$%`",
"Table does not exist: functional.@#$%");
// If the database exist but the table doesn't, and the user hasn't specified
// "IF EXISTS", an analysis error should be thrown
AnalysisError("drop table functional.badtable",
"Table does not exist: functional.badtable");
AnalysisError("drop view functional.badview",
"Table does not exist: functional.badview");
// No error is thrown if the user specifies IF EXISTS
AnalyzesOk("drop database if exists db_does_not_exist");
// No error is thrown if the database does not exist
AnalyzesOk("drop table if exists db_does_not_exist.alltypes");
AnalyzesOk("drop view if exists db_does_not_exist.alltypes");
// No error is thrown if the database table does not exist and IF EXISTS
// is true
AnalyzesOk("drop table if exists functional.notbl");
AnalyzesOk("drop view if exists functional.notbl");
// Cannot drop a view with DROP TABLE.
AnalysisError("drop table functional.alltypes_view",
"DROP TABLE not allowed on a view: functional.alltypes_view");
// Cannot drop a table with DROP VIEW.
AnalysisError("drop view functional.alltypes",
"DROP VIEW not allowed on a table: functional.alltypes");
}
@Test
public void TestCreateDataSource() {
final String DATA_SOURCE_NAME = "TestDataSource1";
final DataSource DATA_SOURCE = new DataSource(DATA_SOURCE_NAME, "/foo.jar",
"foo.Bar", "V1");
catalog_.addDataSource(DATA_SOURCE);
AnalyzesOk("CREATE DATA SOURCE IF NOT EXISTS " + DATA_SOURCE_NAME +
" LOCATION '/foo.jar' CLASS 'foo.Bar' API_VERSION 'V1'");
AnalyzesOk("CREATE DATA SOURCE IF NOT EXISTS " + DATA_SOURCE_NAME.toLowerCase() +
" LOCATION '/foo.jar' CLASS 'foo.Bar' API_VERSION 'V1'");
AnalyzesOk("CREATE DATA SOURCE IF NOT EXISTS " + DATA_SOURCE_NAME +
" LOCATION 'hdfs://localhost:20500/foo.jar' CLASS 'foo.Bar' API_VERSION 'V1'");
AnalyzesOk("CREATE DATA SOURCE foo LOCATION '/' CLASS '' API_VERSION 'v1'");
AnalyzesOk("CREATE DATA SOURCE foo LOCATION '/foo.jar' CLASS 'com.bar.Foo' " +
"API_VERSION 'V1'");
AnalyzesOk("CREATE DATA SOURCE foo LOCATION '/FOO.jar' CLASS 'COM.BAR.FOO' " +
"API_VERSION 'v1'");
AnalyzesOk("CREATE DATA SOURCE foo LOCATION \"/foo.jar\" CLASS \"com.bar.Foo\" " +
"API_VERSION \"V1\"");
AnalyzesOk("CREATE DATA SOURCE foo LOCATION '/x/foo@hi_^!#.jar' " +
"CLASS 'com.bar.Foo' API_VERSION 'V1'");
AnalyzesOk("CREATE DATA SOURCE foo LOCATION 'hdfs://localhost:20500/a/b/foo.jar' " +
"CLASS 'com.bar.Foo' API_VERSION 'V1'");
AnalyzesOk("CREATE DATA SOURCE foo LOCATION 's3n://bucket/a/b/foo.jar' " +
"CLASS 'com.bar.Foo' API_VERSION 'V1'");
AnalysisError("CREATE DATA SOURCE foo LOCATION 'blah://localhost:20500/foo.jar' " +
"CLASS 'com.bar.Foo' API_VERSION 'V1'",
"No FileSystem for scheme: blah");
AnalysisError("CREATE DATA SOURCE " + DATA_SOURCE_NAME + " LOCATION '/foo.jar' " +
"CLASS 'foo.Bar' API_VERSION 'V1'",
"Data source already exists: " + DATA_SOURCE_NAME.toLowerCase());
AnalysisError("CREATE DATA SOURCE foo LOCATION '/foo.jar' " +
"CLASS 'foo.Bar' API_VERSION 'V2'", "Invalid API version: 'V2'");
}
@Test
public void TestCreateDb() throws AnalysisException {
AnalyzesOk("create database some_new_database");
AnalysisError("create database functional", "Database already exists: functional");
AnalyzesOk("create database if not exists functional");
// Invalid database name,
AnalysisError("create database `%^&`", "Invalid database name: %^&");
// Valid URIs.
AnalyzesOk("create database new_db location " +
"'/test-warehouse/new_db'");
AnalyzesOk("create database new_db location " +
"'hdfs://localhost:50200/test-warehouse/new_db'");
AnalyzesOk("create database new_db location " +
"'s3n://bucket/test-warehouse/new_db'");
// Invalid URI.
AnalysisError("create database new_db location " +
"'blah://bucket/test-warehouse/new_db'",
"No FileSystem for scheme: blah");
}
@Test
public void TestCreateTableLikeFile() throws AnalysisException {
// check that we analyze all of the CREATE TABLE options
AnalyzesOk("create table if not exists newtbl_DNE like parquet "
+ "'/test-warehouse/schemas/alltypestiny.parquet'");
AnalyzesOk("create table newtbl_DNE like parquet "
+ "'/test-warehouse/schemas/zipcode_incomes.parquet'");
AnalyzesOk("create table default.newtbl_DNE like parquet "
+ "'/test-warehouse/schemas/zipcode_incomes.parquet'");
AnalyzesOk("create table newtbl_DNE like parquet "
+ "'/test-warehouse/schemas/zipcode_incomes.parquet' STORED AS PARQUET");
AnalyzesOk("create external table newtbl_DNE like parquet "
+ "'/test-warehouse/schemas/zipcode_incomes.parquet' STORED AS PARQUET");
AnalyzesOk("create table if not exists functional.zipcode_incomes like parquet "
+ "'/test-warehouse/schemas/zipcode_incomes.parquet'");
AnalyzesOk("create table if not exists newtbl_DNE like parquet "
+ "'/test-warehouse/schemas/zipcode_incomes.parquet'");
AnalyzesOk("create table if not exists newtbl_DNE like parquet "
+ "'/test-warehouse/schemas/decimal.parquet'");
// check we error in the same situations as standard create table
AnalysisError("create table functional.zipcode_incomes like parquet "
+ "'/test-warehouse/schemas/zipcode_incomes.parquet'",
"Table already exists: functional.zipcode_incomes");
AnalysisError("create table database_DNE.newtbl_DNE like parquet "
+ "'/test-warehouse/schemas/zipcode_incomes.parquet'",
"Database does not exist: database_DNE");
// check invalid paths
AnalysisError("create table if not exists functional.zipcode_incomes like parquet "
+ "'/test-warehouse'",
"Cannot infer schema, path is not a file: hdfs://localhost:20500/test-warehouse");
AnalysisError("create table newtbl_DNE like parquet 'foobar'",
"URI path must be absolute: foobar");
AnalysisError("create table newtbl_DNE like parquet '/not/a/file/path'",
"Cannot infer schema, path is not a file: "
+ "hdfs://localhost:20500/not/a/file/path");
AnalysisError("create table if not exists functional.zipcode_incomes like parquet "
+ "'file:///tmp/foobar'",
"Cannot infer schema, path is not a file: file:/tmp/foobar");
// check valid paths with bad file contents
AnalysisError("create table database_DNE.newtbl_DNE like parquet "
+ "'/test-warehouse/zipcode_incomes_rc/000000_0'",
"File is not a parquet file: "
+ "hdfs://localhost:20500/test-warehouse/zipcode_incomes_rc/000000_0");
// this is a decimal file without annotations
AnalysisError("create table if not exists functional.zipcode_incomes like parquet "
+ "'/test-warehouse/schemas/malformed_decimal_tiny.parquet'",
"Unsupported parquet type FIXED_LEN_BYTE_ARRAY for field c1");
// this has structures, maps, and arrays
AnalysisError("create table table_DNE like parquet "
+ "'/test-warehouse/schemas/unsupported.parquet'",
"Unsupported parquet type for field strct");
AnalysisError("create table table_DNE like parquet "
+ "'/test-warehouse/schemas/map.parquet'",
"Unsupported parquet type for field mp");
AnalysisError("create table table_DNE like parquet "
+ "'/test-warehouse/schemas/array.parquet'",
"Unsupported parquet type for field lst");
AnalysisError("create table table_DNE like parquet "
+ "'/test-warehouse/schemas/struct.parquet'",
"Unsupported parquet type for field strct");
}
@Test
public void TestCreateTableAsSelect() throws AnalysisException {
// Constant select.
AnalyzesOk("create table newtbl as select 1+2, 'abc'");
// Select from partitioned and unpartitioned tables using different
// queries.
AnalyzesOk("create table newtbl stored as textfile " +
"as select * from functional.jointbl");
AnalyzesOk("create table newtbl stored as parquetfile " +
"as select * from functional.alltypes");
AnalyzesOk("create table newtbl stored as parquet " +
"as select * from functional.alltypes");
AnalyzesOk("create table newtbl as select int_col from functional.alltypes");
AnalyzesOk("create table functional.newtbl " +
"as select count(*) as CNT from functional.alltypes");
AnalyzesOk("create table functional.tbl as select a.* from functional.alltypes a " +
"join functional.alltypes b on (a.int_col=b.int_col) limit 1000");
// Caching operations
AnalyzesOk("create table functional.newtbl cached in 'testPool'" +
" as select count(*) as CNT from functional.alltypes");
AnalyzesOk("create table functional.newtbl uncached" +
" as select count(*) as CNT from functional.alltypes");
// Table already exists with and without IF NOT EXISTS
AnalysisError("create table functional.alltypes as select 1",
"Table already exists: functional.alltypes");
AnalyzesOk("create table if not exists functional.alltypes as select 1");
// Database does not exist
AnalysisError("create table db_does_not_exist.new_table as select 1",
"Database does not exist: db_does_not_exist");
// Analysis errors in the SELECT statement
AnalysisError("create table newtbl as select * from tbl_does_not_exist",
"Table does not exist: default.tbl_does_not_exist");
AnalysisError("create table newtbl as select 1 as c1, 2 as c1",
"Duplicate column name: c1");
// Unsupported file formats
AnalysisError("create table foo stored as sequencefile as select 1",
"CREATE TABLE AS SELECT does not support (SEQUENCEFILE) file format. " +
"Supported formats are: (PARQUET, TEXTFILE)");
AnalysisError("create table foo stored as RCFILE as select 1",
"CREATE TABLE AS SELECT does not support (RCFILE) file format. " +
"Supported formats are: (PARQUET, TEXTFILE)");
// CTAS with a WITH clause and inline view (IMPALA-1100)
AnalyzesOk("create table test_with as with with_1 as (select 1 as int_col from " +
"functional.alltypes as t1 right join (select 1 as int_col from " +
"functional.alltypestiny as t1) as t2 on t2.int_col = t1.int_col) " +
"select * from with_1 limit 10");
}
@Test
public void TestCreateTableLike() throws AnalysisException {
AnalyzesOk("create table if not exists functional.new_tbl like functional.alltypes");
AnalyzesOk("create table functional.like_view like functional.view_view");
AnalyzesOk(
"create table if not exists functional.alltypes like functional.alltypes");
AnalysisError("create table functional.alltypes like functional.alltypes",
"Table already exists: functional.alltypes");
AnalysisError("create table functional.new_table like functional.tbl_does_not_exist",
"Table does not exist: functional.tbl_does_not_exist");
AnalysisError("create table functional.new_table like db_does_not_exist.alltypes",
"Database does not exist: db_does_not_exist");
// Invalid database name.
AnalysisError("create table `???`.new_table like functional.alltypes",
"Invalid database name: ???");
// Invalid table/view name.
AnalysisError("create table functional.`^&*` like functional.alltypes",
"Invalid table/view name: ^&*");
// Invalid source database/table name reports non-existence instead of invalidity.
AnalysisError("create table functional.foo like `???`.alltypes",
"Database does not exist: ???");
AnalysisError("create table functional.foo like functional.`%^&`",
"Table does not exist: functional.%^&");
// Valid URI values.
AnalyzesOk("create table tbl like functional.alltypes location " +
"'/test-warehouse/new_table'");
AnalyzesOk("create table tbl like functional.alltypes location " +
"'hdfs://localhost:20500/test-warehouse/new_table'");
// 'file' scheme does not take an authority, so file:/// is equivalent to file://
// and file:/.
AnalyzesOk("create table tbl like functional.alltypes location " +
"'file:///test-warehouse/new_table'");
AnalyzesOk("create table tbl like functional.alltypes location " +
"'file://test-warehouse/new_table'");
AnalyzesOk("create table tbl like functional.alltypes location " +
"'file:/test-warehouse/new_table'");
AnalyzesOk("create table tbl like functional.alltypes location " +
"'s3n://bucket/test-warehouse/new_table'");
// Invalid URI values.
AnalysisError("create table tbl like functional.alltypes location " +
"'foofs://test-warehouse/new_table'",
"No FileSystem for scheme: foofs");
AnalysisError("create table functional.baz like functional.alltypes location ' '",
"URI path cannot be empty.");
}
@Test
public void TestCreateTable() throws AnalysisException {
AnalyzesOk("create table functional.new_table (i int)");
AnalyzesOk("create table if not exists functional.alltypes (i int)");
AnalysisError("create table functional.alltypes",
"Table already exists: functional.alltypes");
AnalysisError("create table functional.alltypes (i int)",
"Table already exists: functional.alltypes");
AnalyzesOk("create table functional.new_table (i int) row format delimited fields " +
"terminated by '|'");
AnalyzesOk("create table new_table (i int) PARTITIONED BY (d decimal)");
AnalyzesOk("create table new_table (i int) PARTITIONED BY (d decimal(3,1))");
AnalyzesOk("create table new_table(d1 decimal, d2 decimal(10), d3 decimal(5, 2))");
AnalysisError("create table new_table (i int) PARTITIONED BY (d decimal(40,1))",
"Decimal precision must be <= 38.");
AnalyzesOk("create table new_table(s1 varchar(1), s2 varchar(32672))");
AnalysisError("create table new_table(s1 varchar(0))",
"Varchar size must be > 0. Size is too small: 0.");
AnalysisError("create table new_table(s1 varchar(65356))",
"Varchar size must be <= 65355. Size is too large: 65356.");
AnalysisError("create table new_table(s1 char(0))",
"Char size must be > 0. Size is too small: 0.");
AnalysisError("create table new_table(s1 Char(256))",
"Char size must be <= 255. Size is too large: 256.");
AnalyzesOk("create table new_table (i int) PARTITIONED BY (s varchar(3))");
AnalyzesOk("create table functional.new_table (c char(250))");
AnalyzesOk("create table new_table (i int) PARTITIONED BY (c char(3))");
// Supported file formats. Exclude Avro since it is tested separately.
String [] fileFormats =
{"TEXTFILE", "SEQUENCEFILE", "PARQUET", "PARQUETFILE", "RCFILE"};
for (String format: fileFormats) {
AnalyzesOk(String.format("create table new_table (i int) " +
"partitioned by (d decimal) comment 'c' stored as %s", format));
// No column definitions.
AnalysisError(String.format("create table new_table " +
"partitioned by (d decimal) comment 'c' stored as %s", format),
"Table requires at least 1 column");
}
// Note: Backslashes need to be escaped twice - once for Java and once for Impala.
// For example, if this were a real query the value '\' would be stored in the
// metastore for the ESCAPED BY field.
AnalyzesOk("create table functional.new_table (i int) row format delimited fields " +
"terminated by '\\t' escaped by '\\\\' lines terminated by '\\n'");
AnalyzesOk("create table functional.new_table (i int) row format delimited fields " +
"terminated by '\\001' escaped by '\\002' lines terminated by '\\n'");
AnalyzesOk("create table functional.new_table (i int) row format delimited fields " +
"terminated by '-2' escaped by '-3' lines terminated by '\\n'");
AnalyzesOk("create table functional.new_table (i int) row format delimited fields " +
"terminated by '-128' escaped by '127' lines terminated by '40'");
AnalysisError("create table functional.new_table (i int) row format delimited " +
"fields terminated by '-2' escaped by '128' lines terminated by '\\n'",
"ESCAPED BY values and LINE/FIELD terminators must be specified as a single " +
"character or as a decimal value in the range [-128:127]: 128");
AnalysisError("create table functional.new_table (i int) row format delimited " +
"fields terminated by '-2' escaped by '127' lines terminated by '255'",
"ESCAPED BY values and LINE/FIELD terminators must be specified as a single " +
"character or as a decimal value in the range [-128:127]: 255");
AnalysisError("create table functional.new_table (i int) row format delimited " +
"fields terminated by '-129' escaped by '127' lines terminated by '\\n'",
"ESCAPED BY values and LINE/FIELD terminators must be specified as a single " +
"character or as a decimal value in the range [-128:127]: -129");
AnalysisError("create table functional.new_table (i int) row format delimited " +
"fields terminated by '||' escaped by '\\\\' lines terminated by '\\n'",
"ESCAPED BY values and LINE/FIELD terminators must be specified as a single " +
"character or as a decimal value in the range [-128:127]: ||");
AnalysisError("create table db_does_not_exist.new_table (i int)",
"Database does not exist: db_does_not_exist");
AnalysisError("create table new_table (i int, I string)",
"Duplicate column name: I");
AnalysisError("create table new_table (c1 double, col2 int, c1 double, c4 string)",
"Duplicate column name: c1");
AnalysisError("create table new_table (i int, s string) PARTITIONED BY (i int)",
"Duplicate column name: i");
AnalysisError("create table new_table (i int) PARTITIONED BY (C int, c2 int, c int)",
"Duplicate column name: c");
// Unsupported partition-column types.
AnalysisError("create table new_table (i int) PARTITIONED BY (t timestamp)",
"Type 'TIMESTAMP' is not supported as partition-column type in column: t");
AnalysisError("create table new_table (i int) PARTITIONED BY (d date)",
"Type 'DATE' is not supported as partition-column type in column: d");
AnalysisError("create table new_table (i int) PARTITIONED BY (d datetime)",
"Type 'DATETIME' is not supported as partition-column type in column: d");
// Caching ops
AnalyzesOk("create table cached_tbl(i int) partitioned by(j int) " +
"cached in 'testPool'");
AnalyzesOk("create table cached_tbl(i int) partitioned by(j int) uncached");
AnalyzesOk("create table cached_tbl(i int) partitioned by(j int) " +
"location '/test-warehouse/' cached in 'testPool'");
AnalyzesOk("create table cached_tbl(i int) partitioned by(j int) " +
"location '/test-warehouse/' uncached");
// Invalid database name.
AnalysisError("create table `???`.new_table (x int) PARTITIONED BY (y int)",
"Invalid database name: ???");
// Invalid table/view name.
AnalysisError("create table functional.`^&*` (x int) PARTITIONED BY (y int)",
"Invalid table/view name: ^&*");
// Invalid column names.
AnalysisError("create table new_table (`???` int) PARTITIONED BY (i int)",
"Invalid column/field name: ???");
AnalysisError("create table new_table (i int) PARTITIONED BY (`^&*` int)",
"Invalid column/field name: ^&*");
// Valid URI values.
AnalyzesOk("create table tbl (i int) location '/test-warehouse/new_table'");
AnalyzesOk("create table tbl (i int) location " +
"'hdfs://localhost:20500/test-warehouse/new_table'");
AnalyzesOk("create table tbl (i int) location " +
"'file:///test-warehouse/new_table'");
AnalyzesOk("create table tbl (i int) location " +
"'s3n://bucket/test-warehouse/new_table'");
AnalyzesOk("ALTER TABLE functional_seq_snap.alltypes SET LOCATION " +
"'file://test-warehouse/new_table'");
// Invalid URI values.
AnalysisError("create table functional.foo (x int) location " +
"'foofs://test-warehouse/new_table'",
"No FileSystem for scheme: foofs");
AnalysisError("create table functional.foo (x int) location " +
"' '", "URI path cannot be empty.");
AnalysisError("ALTER TABLE functional_seq_snap.alltypes SET LOCATION " +
"'foofs://test-warehouse/new_table'",
"No FileSystem for scheme: foofs");
AnalysisError("ALTER TABLE functional_seq_snap.alltypes SET LOCATION " +
"' '", "URI path cannot be empty.");
// Create table PRODUCED BY DATA SOURCE
final String DATA_SOURCE_NAME = "TestDataSource1";
catalog_.addDataSource(new DataSource(DATA_SOURCE_NAME, "/foo.jar",
"foo.Bar", "V1"));
AnalyzesOk("CREATE TABLE DataSrcTable1 (x int) PRODUCED BY DATA SOURCE " +
DATA_SOURCE_NAME);
AnalyzesOk("CREATE TABLE DataSrcTable1 (x int) PRODUCED BY DATA SOURCE " +
DATA_SOURCE_NAME.toLowerCase());
AnalyzesOk("CREATE TABLE DataSrcTable1 (x int) PRODUCED BY DATA SOURCE " +
DATA_SOURCE_NAME + "(\"\")");
AnalyzesOk("CREATE TABLE DataSrcTable1 (a tinyint, b smallint, c int, d bigint, " +
"e float, f double, g boolean, h string) PRODUCED BY DATA SOURCE " +
DATA_SOURCE_NAME);
AnalysisError("CREATE TABLE DataSrcTable1 (x int) PRODUCED BY DATA SOURCE " +
"not_a_data_src(\"\")", "Data source does not exist");
for (Type t: Type.getSupportedTypes()) {
PrimitiveType type = t.getPrimitiveType();
if (DataSourceTable.isSupportedPrimitiveType(type) || t.isNull()) continue;
String typeSpec = type.name();
if (type == PrimitiveType.CHAR || type == PrimitiveType.DECIMAL ||
type == PrimitiveType.VARCHAR) {
typeSpec += "(10)";
}
AnalysisError("CREATE TABLE DataSrcTable1 (x " + typeSpec + ") PRODUCED " +
"BY DATA SOURCE " + DATA_SOURCE_NAME,
"Tables produced by an external data source do not support the column type: " +
type.name());
}
}
@Test
public void TestCreateAvroTest() {
String alltypesSchemaLoc =
"hdfs:///test-warehouse/avro_schemas/functional/alltypes.json";
// Analysis of Avro schemas. Column definitions match the Avro schema exactly.
// Note: Avro does not have a tinyint and smallint type.
AnalyzesOk(String.format(
"create table foo_avro (id int, bool_col boolean, tinyint_col int, " +
"smallint_col int, int_col int, bigint_col bigint, float_col float," +
"double_col double, date_string_col string, string_col string, " +
"timestamp_col timestamp) with serdeproperties ('avro.schema.url'='%s')" +
"stored as avro", alltypesSchemaLoc));
AnalyzesOk(String.format(
"create table foo_avro (id int, bool_col boolean, tinyint_col int, " +
"smallint_col int, int_col int, bigint_col bigint, float_col float," +
"double_col double, date_string_col string, string_col string, " +
"timestamp_col timestamp) stored as avro tblproperties ('avro.schema.url'='%s')",
alltypesSchemaLoc));
AnalyzesOk("create table foo_avro (string1 string) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\": \"string1\", \"type\": \"string\"}]}')");
// No column definitions.
AnalyzesOk(String.format(
"create table foo_avro with serdeproperties ('avro.schema.url'='%s')" +
"stored as avro", alltypesSchemaLoc));
AnalyzesOk(String.format(
"create table foo_avro stored as avro tblproperties ('avro.schema.url'='%s')",
alltypesSchemaLoc));
AnalyzesOk("create table foo_avro stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\": \"string1\", \"type\": \"string\"}]}')");
// Analysis of Avro schemas. Column definitions do not match Avro schema.
AnalyzesOk(String.format(
"create table foo_avro (id int) with serdeproperties ('avro.schema.url'='%s')" +
"stored as avro", alltypesSchemaLoc),
"Ignoring column definitions in favor of Avro schema.\n" +
"The Avro schema has 11 column(s) but 1 column definition(s) were given.");
AnalyzesOk(String.format(
"create table foo_avro (bool_col boolean, string_col string) " +
"stored as avro tblproperties ('avro.schema.url'='%s')",
alltypesSchemaLoc),
"Ignoring column definitions in favor of Avro schema.\n" +
"The Avro schema has 11 column(s) but 2 column definition(s) were given.");
AnalyzesOk("create table foo_avro (string1 string) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\": \"string1\", \"type\": \"string\"}," +
"{\"name\": \"string2\", \"type\": \"string\"}]}')",
"Ignoring column definitions in favor of Avro schema.\n" +
"The Avro schema has 2 column(s) but 1 column definition(s) were given.");
// Mismatched name.
AnalyzesOk(String.format(
"create table foo_avro (id int, bool_col boolean, tinyint_col int, " +
"smallint_col int, bad_int_col int, bigint_col bigint, float_col float," +
"double_col double, date_string_col string, string_col string, " +
"timestamp_col timestamp) with serdeproperties ('avro.schema.url'='%s')" +
"stored as avro", alltypesSchemaLoc),
"Ignoring column definitions in favor of Avro schema due to a mismatched " +
"column name at position 5.\n" +
"Column definition: bad_int_col INT\n" +
"Avro schema column: int_col INT");
// Mismatched type.
AnalyzesOk(String.format(
"create table foo_avro (id int, bool_col boolean, tinyint_col int, " +
"smallint_col int, int_col int, bigint_col bigint, float_col float," +
"double_col bigint, date_string_col string, string_col string, " +
"timestamp_col timestamp) stored as avro tblproperties ('avro.schema.url'='%s')",
alltypesSchemaLoc),
"Ignoring column definitions in favor of Avro schema due to a mismatched " +
"column type at position 8.\n" +
"Column definition: double_col BIGINT\n" +
"Avro schema column: double_col DOUBLE");
// No Avro schema specified for Avro format table.
AnalysisError("create table foo_avro (i int) stored as avro",
"No Avro schema provided in SERDEPROPERTIES or TBLPROPERTIES for table: " +
"default.foo_avro");
AnalysisError("create table foo_avro (i int) stored as avro tblproperties ('a'='b')",
"No Avro schema provided in SERDEPROPERTIES or TBLPROPERTIES for table: " +
"default.foo_avro");
AnalysisError("create table foo_avro stored as avro tblproperties ('a'='b')",
"No Avro schema provided in SERDEPROPERTIES or TBLPROPERTIES for table: "+
"default.foo_avro");
// Invalid schema URL
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.url'='schema.avsc')",
"Invalid avro.schema.url: schema.avsc. Path does not exist.");
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.url'='hdfs://invalid*host/schema.avsc')",
"Invalid avro.schema.url: hdfs://invalid*host/schema.avsc. " +
"Incomplete HDFS URI, no host: hdfs://invalid*host/schema.avsc");
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.url'='foo://bar/schema.avsc')",
"Invalid avro.schema.url: foo://bar/schema.avsc. No FileSystem for scheme: foo");
// Decimal parsing
AnalyzesOk("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\":\"value\",\"type\":{\"type\":\"bytes\", " +
"\"logicalType\":\"decimal\",\"precision\":5,\"scale\":2}}]}')");
// Scale not required (defaults to zero).
AnalyzesOk("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\":\"value\",\"type\":{\"type\":\"bytes\", " +
"\"logicalType\":\"decimal\",\"precision\":5}}]}')");
// Precision is always required
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\":\"value\",\"type\":{\"type\":\"bytes\", " +
"\"logicalType\":\"decimal\",\"scale\":5}}]}')",
"Error parsing Avro schema for table 'default.foo_avro': " +
"No 'precision' property specified for 'decimal' logicalType");
// Precision/Scale must be positive integers
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\":\"value\",\"type\":{\"type\":\"bytes\", " +
"\"logicalType\":\"decimal\",\"scale\":5, \"precision\":-20}}]}')",
"Error parsing Avro schema for table 'default.foo_avro': " +
"Invalid decimal 'precision' property value: -20");
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\":\"value\",\"type\":{\"type\":\"bytes\", " +
"\"logicalType\":\"decimal\",\"scale\":-1, \"precision\":20}}]}')",
"Error parsing Avro schema for table 'default.foo_avro': " +
"Invalid decimal 'scale' property value: -1");
// Invalid schema (bad JSON - missing opening bracket for "field" array)
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": {\"name\": \"string1\", \"type\": \"string\"}]}')",
"Error parsing Avro schema for table 'default.foo_avro': " +
"org.codehaus.jackson.JsonParseException: Unexpected close marker ']': "+
"expected '}'");
// Unsupported types
// Array
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\": \"string1\", \"type\": \"string\"}," +
"{\"name\": \"list1\", \"type\": {\"type\":\"array\", \"items\": \"int\"}}]}')",
"Error parsing Avro schema for table 'default.foo_avro': " +
"Unsupported type 'array' of column 'list1'");
// Map
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\": \"string1\", \"type\": \"string\"}," +
"{\"name\": \"map1\", \"type\": {\"type\":\"map\", \"values\": \"int\"}}]}')",
"Error parsing Avro schema for table 'default.foo_avro': " +
"Unsupported type 'map' of column 'map1'");
// Union
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\": \"string1\", \"type\": \"string\"}," +
"{\"name\": \"union1\", \"type\": [\"float\", \"boolean\"]}]}')",
"Error parsing Avro schema for table 'default.foo_avro': " +
"Unsupported type 'union' of column 'union1'");
// TODO: Add COLLECTION ITEMS TERMINATED BY and MAP KEYS TERMINATED BY clauses.
// Test struct complex type.
AnalyzesOk("create table functional.new_table (" +
"a struct<f1: int, f2: string, f3: timestamp, f4: boolean>, " +
"b struct<f1: struct<f11: int>, f2: struct<f21: struct<f22: string>>>, " +
"c struct<f1: map<int, string>, f2: array<bigint>>," +
"d struct<f1: struct<f11: map<int, string>, f12: array<bigint>>>)");
// Test array complex type.
AnalyzesOk("create table functional.new_table (" +
"a array<int>, b array<timestamp>, c array<string>, d array<boolean>, " +
"e array<array<int>>, f array<array<array<string>>>, " +
"g array<struct<f1: int, f2: string>>, " +
"h array<map<string,int>>)");
// Test map complex type.
AnalyzesOk("create table functional.new_table (" +
"a map<string, int>, b map<timestamp, boolean>, c map<bigint, float>, " +
"d array<array<int>>, e array<array<array<string>>>, " +
"f array<struct<f1: int, f2: string>>," +
"g array<map<string,int>>)");
// Cannot partition by a complex column.
AnalysisError("create table functional.new_table (i int) " +
"partitioned by (x array<int>)",
"Type 'ARRAY<INT>' is not supported as partition-column type in column: x");
AnalysisError("create table functional.new_table (i int) " +
"partitioned by (x map<int,int>)",
"Type 'MAP<INT,INT>' is not supported as partition-column type in column: x");
AnalysisError("create table functional.new_table (i int) " +
"partitioned by (x struct<f1:int>)",
"Type 'STRUCT<f1:INT>' is not supported as partition-column type in column: x");
}
@Test
public void TestCreateView() throws AnalysisException {
AnalyzesOk(
"create view foo_new as select int_col, string_col from functional.alltypes");
AnalyzesOk("create view functional.foo as select * from functional.alltypes");
AnalyzesOk("create view if not exists foo as select * from functional.alltypes");
AnalyzesOk("create view foo (a, b) as select int_col, string_col " +
"from functional.alltypes");
AnalyzesOk("create view functional.foo (a, b) as select int_col x, double_col y " +
"from functional.alltypes");
// View can have complex-typed columns.
AnalyzesOk("create view functional.foo (a, b, c) as " +
"select int_array_col, int_map_col, int_struct_col " +
"from functional.allcomplextypes");
// Creating a view on a view is ok (alltypes_view is a view on alltypes).
AnalyzesOk("create view foo as select * from functional.alltypes_view");
AnalyzesOk("create view foo (aaa, bbb) as select * from functional.complex_view");
// Create a view resulting in Hive-style auto-generated column names.
AnalyzesOk("create view foo as select trim('abc'), 17 * 7");
// Creating a view on an HBase table is ok.
AnalyzesOk("create view foo as select * from functional_hbase.alltypesagg");
// Complex view definition with joins and aggregates.
AnalyzesOk("create view foo (cnt) as " +
"select count(distinct x.int_col) from functional.alltypessmall x " +
"inner join functional.alltypessmall y on (x.id = y.id) group by x.bigint_col");
// Test different query-statement types as view definition.
AnalyzesOk("create view foo (a, b) as values(1, 'a'), (2, 'b')");
AnalyzesOk("create view foo (a, b) as select 1, 'a' union all select 2, 'b'");
// Mismatching number of columns in column definition and view-definition statement.
AnalysisError("create view foo (a) as select int_col, string_col " +
"from functional.alltypes",
"Column-definition list has fewer columns (1) than the " +
"view-definition query statement returns (2).");
AnalysisError("create view foo (a, b, c) as select int_col " +
"from functional.alltypes",
"Column-definition list has more columns (3) than the " +
"view-definition query statement returns (1).");
// Duplicate columns in the view-definition statement.
AnalysisError("create view foo as select * from functional.alltypessmall a " +
"inner join functional.alltypessmall b on a.id = b.id",
"Duplicate column name: id");
// Duplicate columns in the column definition.
AnalysisError("create view foo (a, b, a) as select int_col, int_col, int_col " +
"from functional.alltypes",
"Duplicate column name: a");
// Invalid database/view/column names.
AnalysisError("create view `???`.new_view as select 1, 2, 3",
"Invalid database name: ???");
AnalysisError("create view `^%&` as select 1, 2, 3",
"Invalid table/view name: ^%&");
AnalysisError("create view foo as select 1 as `???`",
"Invalid column/field name: ???");
AnalysisError("create view foo(`%^&`) as select 1",
"Invalid column/field name: %^&");
// Table/view already exists.
AnalysisError("create view functional.alltypes as " +
"select * from functional.alltypessmall ",
"Table already exists: functional.alltypes");
// Target database does not exist.
AnalysisError("create view wrongdb.test as " +
"select * from functional.alltypessmall ",
"Database does not exist: wrongdb");
// Source database does not exist,
AnalysisError("create view foo as " +
"select * from wrongdb.alltypessmall ",
"Database does not exist: wrongdb");
// Source table does not exist,
AnalysisError("create view foo as " +
"select * from wrongdb.alltypessmall ",
"Database does not exist: wrongdb");
// Analysis error in view-definition statement.
AnalysisError("create view foo as " +
"select int_col from functional.alltypessmall union all " +
"select string_col from functional.alltypes",
"Incompatible return types 'INT' and 'STRING' of exprs " +
"'int_col' and 'string_col'.");
// View with a subquery
AnalyzesOk("create view test_view_with_subquery as " +
"select * from functional.alltypestiny t where exists " +
"(select * from functional.alltypessmall s where s.id = t.id)");
}
@Test
public void TestUdf() throws AnalysisException {
final String symbol =
"'_Z8IdentityPN10impala_udf15FunctionContextERKNS_10BooleanValE'";
final String udfSuffix = " LOCATION '/test-warehouse/libTestUdfs.so' " +
"SYMBOL=" + symbol;
final String udfSuffixIr = " LOCATION '/test-warehouse/test-udfs.ll' " +
"SYMBOL=" + symbol;
final String hdfsPath = "hdfs://localhost:20500/test-warehouse/libTestUdfs.so";
AnalyzesOk("create function foo() RETURNS int" + udfSuffix);
AnalyzesOk("create function foo(int, int, string) RETURNS int" + udfSuffix);
// Try some fully qualified function names
AnalyzesOk("create function functional.B() RETURNS int" + udfSuffix);
AnalyzesOk("create function functional.B1() RETURNS int" + udfSuffix);
AnalyzesOk("create function functional.`B1C`() RETURNS int" + udfSuffix);
// Name with underscore
AnalyzesOk("create function A_B() RETURNS int" + udfSuffix);
// Locations for all the udfs types.
AnalyzesOk("create function foo() RETURNS int LOCATION " +
"'/test-warehouse/libTestUdfs.so' " +
"SYMBOL='_Z8IdentityPN10impala_udf15FunctionContextERKNS_10BooleanValE'");
AnalysisError("create function foo() RETURNS int LOCATION " +
"'/test-warehouse/libTestUdfs.ll' " +
"SYMBOL='_Z8IdentityPN10impala_udf15FunctionContextERKNS_10BooleanValE'",
"Could not load binary: /test-warehouse/libTestUdfs.ll");
AnalyzesOk("create function foo() RETURNS int LOCATION " +
"'/test-warehouse/test-udfs.ll' " +
"SYMBOL='_Z8IdentityPN10impala_udf15FunctionContextERKNS_10BooleanValE'");
AnalyzesOk("create function foo(int) RETURNS int LOCATION " +
"'/test-warehouse/test-udfs.ll' SYMBOL='Identity'");
AnalyzesOk("create function foo() RETURNS int LOCATION " +
"'/test-warehouse/libTestUdfs.SO' " +
"SYMBOL='_Z8IdentityPN10impala_udf15FunctionContextERKNS_10BooleanValE'");
AnalyzesOk("create function foo() RETURNS int LOCATION " +
"'/test-warehouse/hive-exec.jar' SYMBOL='a'");
// Test hive UDFs for unsupported types
AnalysisError("create function foo() RETURNS timestamp LOCATION '/a.jar'",
"Hive UDFs that use TIMESTAMP are not yet supported.");
AnalysisError("create function foo(timestamp) RETURNS int LOCATION '/a.jar'",
"Hive UDFs that use TIMESTAMP are not yet supported.");
AnalysisError("create function foo() RETURNS decimal LOCATION '/a.jar'",
"Hive UDFs that use DECIMAL are not yet supported.");
AnalysisError("create function foo(Decimal) RETURNS int LOCATION '/a.jar'",
"Hive UDFs that use DECIMAL are not yet supported.");
AnalysisError("create function foo(char(5)) RETURNS int LOCATION '/a.jar'",
"UDFs that use CHAR are not yet supported.");
AnalysisError("create function foo(varchar(5)) RETURNS int LOCATION '/a.jar'",
"UDFs that use VARCHAR are not yet supported.");
AnalysisError("create function foo() RETURNS CHAR(5) LOCATION '/a.jar'",
"UDFs that use CHAR are not yet supported.");
AnalysisError("create function foo() RETURNS VARCHAR(5) LOCATION '/a.jar'",
"UDFs that use VARCHAR are not yet supported.");
AnalysisError("create function foo() RETURNS CHAR(5)" + udfSuffix,
"UDFs that use CHAR are not yet supported.");
AnalysisError("create function foo() RETURNS VARCHAR(5)" + udfSuffix,
"UDFs that use VARCHAR are not yet supported.");
AnalysisError("create function foo(CHAR(5)) RETURNS int" + udfSuffix,
"UDFs that use CHAR are not yet supported.");
AnalysisError("create function foo(VARCHAR(5)) RETURNS int" + udfSuffix,
"UDFs that use VARCHAR are not yet supported.");
AnalyzesOk("create function foo() RETURNS decimal" + udfSuffix);
AnalyzesOk("create function foo() RETURNS decimal(38,10)" + udfSuffix);
AnalyzesOk("create function foo(Decimal, decimal(10, 2)) RETURNS int" + udfSuffix);
AnalysisError("create function foo() RETURNS decimal(100)" + udfSuffix,
"Decimal precision must be <= 38.");
AnalysisError("create function foo(Decimal(2, 3)) RETURNS int" + udfSuffix,
"Decimal scale (3) must be <= precision (2).");
// Varargs
AnalyzesOk("create function foo(INT...) RETURNS int" + udfSuffix);
// Prepare/Close functions
AnalyzesOk("create function foo() returns int" + udfSuffix
+ " prepare_fn='ValidateOpenPrepare'" + " close_fn='ValidateOpenClose'");
AnalyzesOk("create function foo() returns int" + udfSuffixIr
+ " prepare_fn='ValidateOpenPrepare'" + " close_fn='ValidateOpenClose'");
AnalyzesOk("create function foo() returns int" + udfSuffixIr
+ " prepare_fn='_Z19ValidateOpenPreparePN10impala_udf15FunctionContextENS0_18FunctionStateScopeE'"
+ " close_fn='_Z17ValidateOpenClosePN10impala_udf15FunctionContextENS0_18FunctionStateScopeE'");
AnalysisError("create function foo() returns int" + udfSuffix + " prepare_fn=''",
"Could not find symbol ''");
AnalysisError("create function foo() returns int" + udfSuffix + " close_fn=''",
"Could not find symbol ''");
AnalysisError("create function foo() returns int" + udfSuffix +
" prepare_fn='FakePrepare'",
"Could not find function FakePrepare(impala_udf::FunctionContext*, "+
"impala_udf::FunctionContext::FunctionStateScope) in: ");
// Try to create a function with the same name as a builtin
AnalysisError("create function sin(double) RETURNS double" + udfSuffix,
"Function cannot have the same name as a builtin: sin");
AnalysisError("create function sin() RETURNS double" + udfSuffix,
"Function cannot have the same name as a builtin: sin");
// Try to create with a bad location
AnalysisError("create function foo() RETURNS int LOCATION 'bad-location' SYMBOL='c'",
"URI path must be absolute: bad-location");
AnalysisError("create function foo() RETURNS int LOCATION " +
"'blah://localhost:50200/bad-location' SYMBOL='c'",
"No FileSystem for scheme: blah");
AnalysisError("create function foo() RETURNS int LOCATION " +
"'file:///foo.jar' SYMBOL='c'",
"Could not load binary: file:///foo.jar");
// Try creating udfs with unknown extensions
AnalysisError("create function foo() RETURNS int LOCATION '/binary' SYMBOL='a'",
"Unknown binary type: '/binary'. Binary must end in .jar, .so or .ll");
AnalysisError("create function foo() RETURNS int LOCATION '/binary.a' SYMBOL='a'",
"Unknown binary type: '/binary.a'. Binary must end in .jar, .so or .ll");
AnalysisError("create function foo() RETURNS int LOCATION '/binary.so.' SYMBOL='a'",
"Unknown binary type: '/binary.so.'. Binary must end in .jar, .so or .ll");
// Try with missing symbol
AnalysisError("create function foo() RETURNS int LOCATION '/binary.so'",
"Argument 'SYMBOL' must be set.");
// Try with symbols missing in binary and symbols
AnalysisError("create function foo() RETURNS int LOCATION '/blah.so' " +
"SYMBOL='ab'", "Could not load binary: /blah.so");
AnalysisError("create function foo() RETURNS int LOCATION '/binary.JAR' SYMBOL='a'",
"Could not load binary: /binary.JAR");
AnalysisError("create function foo() RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " +
"SYMBOL='b'", "Could not find function b() in: " + hdfsPath);
AnalysisError("create function foo() RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " +
"SYMBOL=''", "Could not find symbol ''");
AnalysisError("create function foo() RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " +
"SYMBOL='_ZAB'",
"Could not find symbol '_ZAB' in: " + hdfsPath);
// Infer the fully mangled symbol from the signature
AnalyzesOk("create function foo() RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='NoArgs'");
// We can't get the return type so any of those will match
AnalyzesOk("create function foo() RETURNS double " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='NoArgs'");
// The part the user specifies is case sensitive
AnalysisError("create function foo() RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='noArgs'",
"Could not find function noArgs() in: " + hdfsPath);
// Types no longer match
AnalysisError("create function foo(int) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='NoArgs'",
"Could not find function NoArgs(INT) in: " + hdfsPath);
// Check we can match identity for all types
AnalyzesOk("create function identity(boolean) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='Identity'");
AnalyzesOk("create function identity(tinyint) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='Identity'");
AnalyzesOk("create function identity(smallint) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='Identity'");
AnalyzesOk("create function identity(int) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='Identity'");
AnalyzesOk("create function identity(bigint) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='Identity'");
AnalyzesOk("create function identity(float) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='Identity'");
AnalyzesOk("create function identity(double) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='Identity'");
AnalyzesOk("create function identity(string) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='Identity'");
AnalyzesOk("create function all_types_fn(string, boolean, tinyint, " +
"smallint, int, bigint, float, double, decimal) returns int " +
"location '/test-warehouse/libTestUdfs.so' symbol='AllTypes'");
// Try creating functions with illegal function names.
AnalysisError("create function 123A() RETURNS int" + udfSuffix,
"Function cannot start with a digit: 123a");
AnalysisError("create function A.`1A`() RETURNS int" + udfSuffix,
"Function cannot start with a digit: 1a");
AnalysisError("create function A.`ABC-D`() RETURNS int" + udfSuffix,
"Function names must be all alphanumeric or underscore. Invalid name: abc-d");
AnalysisError("create function baddb.f() RETURNS int" + udfSuffix,
"Database does not exist: baddb");
// Try creating functions with unsupported return/arg types.
AnalysisError("create function f() RETURNS array<int>" + udfSuffix,
"Type 'ARRAY<INT>' is not supported in UDFs/UDAs.");
AnalysisError("create function f(map<string,int>) RETURNS int" + udfSuffix,
"Type 'MAP<STRING,INT>' is not supported in UDFs/UDAs.");
AnalysisError("create function f() RETURNS struct<f:int>" + udfSuffix,
"Type 'STRUCT<f:INT>' is not supported in UDFs/UDAs.");
// Try dropping functions.
AnalyzesOk("drop function if exists foo()");
AnalysisError("drop function foo()", "Function does not exist: foo()");
AnalyzesOk("drop function if exists a.foo()");
AnalysisError("drop function a.foo()", "Database does not exist: a");
AnalyzesOk("drop function if exists foo()");
AnalyzesOk("drop function if exists foo(int...)");
AnalyzesOk("drop function if exists foo(double, int...)");
// Add functions default.TestFn(), default.TestFn(double), default.TestFn(String...),
addTestFunction("TestFn", new ArrayList<ScalarType>(), false);
addTestFunction("TestFn", Lists.newArrayList(Type.DOUBLE), false);
addTestFunction("TestFn", Lists.newArrayList(Type.STRING), true);
AnalysisError("create function TestFn() RETURNS INT " + udfSuffix,
"Function already exists: testfn()");
AnalysisError("create function TestFn(double) RETURNS INT " + udfSuffix,
"Function already exists: testfn(DOUBLE)");
// Fn(Double) and Fn(Double...) should be a conflict.
AnalysisError("create function TestFn(double...) RETURNS INT" + udfSuffix,
"Function already exists: testfn(DOUBLE)");
AnalysisError("create function TestFn(double) RETURNS INT" + udfSuffix,
"Function already exists: testfn(DOUBLE)");
// Add default.TestFn(int, int)
addTestFunction("TestFn", Lists.newArrayList(Type.INT, Type.INT), false);
AnalyzesOk("drop function TestFn(int, int)");
AnalysisError("drop function TestFn(int, int, int)",
"Function does not exist: testfn(INT, INT, INT)");
// Fn(String...) was already added.
AnalysisError("create function TestFn(String) RETURNS INT" + udfSuffix,
"Function already exists: testfn(STRING...)");
AnalysisError("create function TestFn(String...) RETURNS INT" + udfSuffix,
"Function already exists: testfn(STRING...)");
AnalysisError("create function TestFn(String, String) RETURNS INT" + udfSuffix,
"Function already exists: testfn(STRING...)");
AnalyzesOk("create function TestFn(String, String, Int) RETURNS INT" + udfSuffix);
// Check function overloading.
AnalyzesOk("create function TestFn(int) RETURNS INT " + udfSuffix);
// Create a function with the same signature in a different db
AnalyzesOk("create function functional.TestFn() RETURNS INT " + udfSuffix);
AnalyzesOk("drop function TestFn()");
AnalyzesOk("drop function TestFn(double)");
AnalyzesOk("drop function TestFn(string...)");
AnalysisError("drop function TestFn(double...)",
"Function does not exist: testfn(DOUBLE...)");
AnalysisError("drop function TestFn(int)", "Function does not exist: testfn(INT)");
AnalysisError(
"drop function functional.TestFn()", "Function does not exist: testfn()");
AnalysisError("create function f() returns int " + udfSuffix +
"init_fn='a'", "Optional argument 'INIT_FN' should not be set");
AnalysisError("create function f() returns int " + udfSuffix +
"serialize_fn='a'", "Optional argument 'SERIALIZE_FN' should not be set");
AnalysisError("create function f() returns int " + udfSuffix +
"merge_fn='a'", "Optional argument 'MERGE_FN' should not be set");
AnalysisError("create function f() returns int " + udfSuffix +
"finalize_fn='a'", "Optional argument 'FINALIZE_FN' should not be set");
}
@Test
public void TestUda() throws AnalysisException {
final String loc = " LOCATION '/test-warehouse/libTestUdas.so' ";
final String hdfsLoc = "hdfs://localhost:20500/test-warehouse/libTestUdas.so";
AnalyzesOk("create aggregate function foo(int) RETURNS int" + loc +
"UPDATE_FN='AggUpdate'");
AnalyzesOk("create aggregate function foo(int) RETURNS int" + loc +
"UPDATE_FN='AggUpdate' INIT_FN='AggInit'");
AnalyzesOk("create aggregate function foo(int) RETURNS int" + loc +
"UPDATE_FN='AggUpdate' INIT_FN='AggInit' MERGE_FN='AggMerge'");
AnalysisError("create aggregate function foo(int) RETURNS int" + loc +
"UPDATE_FN='AggUpdate' INIT_FN='AGgInit'",
"Could not find function AGgInit() returns INT in: " + hdfsLoc);
AnalyzesOk("create aggregate function foo(int, int) RETURNS int" + loc +
"UPDATE_FN='AggUpdate'");
AnalyzesOk("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='AggUpdate'");
// TODO: remove these when the BE can execute them
AnalysisError("create aggregate function foo(int...) RETURNS int" + loc,
"UDAs with varargs are not yet supported.");
AnalysisError("create aggregate function "
+ "foo(int, int, int, int, int, int, int , int, int) "
+ "RETURNS int" + loc,
"UDAs with more than 8 arguments are not yet supported.");
// Check that CHAR and VARCHAR are not valid UDA argument or return types
String symbols =
" UPDATE_FN='_Z9AggUpdatePN10impala_udf15FunctionContextERKNS_6IntValEPS2_' " +
"INIT_FN='_Z7AggInitPN10impala_udf15FunctionContextEPNS_6IntValE' " +
"MERGE_FN='_Z8AggMergePN10impala_udf15FunctionContextERKNS_6IntValEPS2_'";
AnalysisError("create aggregate function foo(CHAR(5)) RETURNS int" + loc + symbols,
"UDAs with CHAR arguments are not yet supported.");
AnalysisError("create aggregate function foo(VARCHAR(5)) RETURNS int" + loc + symbols,
"UDAs with VARCHAR arguments are not yet supported.");
AnalysisError("create aggregate function foo(int) RETURNS CHAR(5)" + loc + symbols,
"UDAs with CHAR return type are not yet supported.");
AnalysisError("create aggregate function foo(int) RETURNS VARCHAR(5)" + loc + symbols,
"UDAs with VARCHAR return type are not yet supported.");
// Specify the complete symbol. If the user does this, we can't guess the
// other function names.
// TODO: think about these error messages more. Perhaps they can be made
// more actionable.
AnalysisError("create aggregate function foo(int) RETURNS int" + loc +
"UPDATE_FN='_Z9AggUpdatePN10impala_udf15FunctionContextERKNS_6IntValEPS2_'",
"Could not infer symbol for init() function.");
AnalysisError("create aggregate function foo(int) RETURNS int" + loc +
"UPDATE_FN='_Z9AggUpdatePN10impala_udf15FunctionContextERKNS_6IntValEPS2_' " +
"INIT_FN='_Z7AggInitPN10impala_udf15FunctionContextEPNS_6IntValE'",
"Could not infer symbol for merge() function.");
AnalyzesOk("create aggregate function foo(int) RETURNS int" + loc +
"UPDATE_FN='_Z9AggUpdatePN10impala_udf15FunctionContextERKNS_6IntValEPS2_' " +
"INIT_FN='_Z7AggInitPN10impala_udf15FunctionContextEPNS_6IntValE' " +
"MERGE_FN='_Z8AggMergePN10impala_udf15FunctionContextERKNS_6IntValEPS2_'");
// Try with intermediate type
// TODO: this is currently not supported. Remove these tests and re-enable
// the commented out ones when we do.
AnalyzesOk("create aggregate function foo(int) RETURNS int " +
"INTERMEDIATE int" + loc + "UPDATE_FN='AggUpdate'");
AnalysisError("create aggregate function foo(int) RETURNS int " +
"INTERMEDIATE double" + loc + "UPDATE_FN='AggUpdate'",
"UDAs with an intermediate type, DOUBLE, that is different from the " +
"return type, INT, are currently not supported.");
AnalysisError("create aggregate function foo(int) RETURNS int " +
"INTERMEDIATE char(10)" + loc + "UPDATE_FN='AggUpdate'",
"UDAs with an intermediate type, CHAR(10), that is different from the " +
"return type, INT, are currently not supported.");
AnalysisError("create aggregate function foo(int) RETURNS int " +
"INTERMEDIATE decimal(10)" + loc + "UPDATE_FN='AggUpdate'",
"UDAs with an intermediate type, DECIMAL(10,0), that is different from the " +
"return type, INT, are currently not supported.");
AnalysisError("create aggregate function foo(int) RETURNS int " +
"INTERMEDIATE decimal(40)" + loc + "UPDATE_FN='AggUpdate'",
"Decimal precision must be <= 38.");
//AnalyzesOk("create aggregate function foo(int) RETURNS int " +
// "INTERMEDIATE CHAR(10)" + loc + "UPDATE_FN='AggUpdate'");
//AnalysisError("create aggregate function foo(int) RETURNS int " +
// "INTERMEDIATE CHAR(10)" + loc + "UPDATE_FN='Agg' INIT_FN='AggInit' " +
// "MERGE_FN='AggMerge'" ,
// "Finalize() is required for this UDA.");
//AnalyzesOk("create aggregate function foo(int) RETURNS int " +
// "INTERMEDIATE CHAR(10)" + loc + "UPDATE_FN='Agg' INIT_FN='AggInit' " +
// "MERGE_FN='AggMerge' FINALIZE_FN='AggFinalize'");
// Udf only arguments must not be set.
AnalysisError("create aggregate function foo(int) RETURNS int" + loc + "SYMBOL='Bad'",
"Optional argument 'SYMBOL' should not be set.");
// Invalid char(0) type.
AnalysisError("create aggregate function foo(int) RETURNS int " +
"INTERMEDIATE CHAR(0) LOCATION '/foo.so' UPDATE_FN='b'",
"Char size must be > 0. Size is too small: 0.");
AnalysisError("create aggregate function foo() RETURNS int" + loc,
"UDAs must take at least one argument.");
AnalysisError("create aggregate function foo(int) RETURNS int LOCATION " +
"'/foo.jar' UPDATE_FN='b'", "Java UDAs are not supported.");
// Try creating functions with unsupported return/arg types.
AnalysisError("create aggregate function foo(string, double) RETURNS array<int> " +
loc + "UPDATE_FN='AggUpdate'",
"Type 'ARRAY<INT>' is not supported in UDFs/UDAs.");
AnalysisError("create aggregate function foo(map<string,int>) RETURNS int " +
loc + "UPDATE_FN='AggUpdate'",
"Type 'MAP<STRING,INT>' is not supported in UDFs/UDAs.");
AnalysisError("create aggregate function foo(int) RETURNS struct<f:int> " +
loc + "UPDATE_FN='AggUpdate'",
"Type 'STRUCT<f:INT>' is not supported in UDFs/UDAs.");
// Test missing .ll file. TODO: reenable when we can run IR UDAs
AnalysisError("create aggregate function foo(int) RETURNS int LOCATION " +
"'/foo.ll' UPDATE_FN='Fn'", "IR UDAs are not yet supported.");
//AnalysisError("create aggregate function foo(int) RETURNS int LOCATION " +
// "'/foo.ll' UPDATE_FN='Fn'", "Could not load binary: /foo.ll");
//AnalysisError("create aggregate function foo(int) RETURNS int LOCATION " +
// "'/foo.ll' UPDATE_FN='_ZABCD'", "Could not load binary: /foo.ll");
// Test cases where the UPDATE_FN doesn't contain "Update" in which case the user has
// to explicitly specify the other functions.
AnalysisError("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg'", "Could not infer symbol for init() function.");
AnalysisError("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg' INIT_FN='AggInit'",
"Could not infer symbol for merge() function.");
AnalyzesOk("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg' INIT_FN='AggInit' MERGE_FN='AggMerge'");
AnalyzesOk("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg' INIT_FN='AggInit' MERGE_FN='AggMerge' " +
"SERIALIZE_FN='AggSerialize'");
AnalyzesOk("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg' INIT_FN='AggInit' MERGE_FN='AggMerge' " +
"SERIALIZE_FN='AggSerialize' FINALIZE_FN='AggFinalize'");
// Serialize and Finalize have the same signature, make sure that's possible.
AnalyzesOk("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='AggUpdate' SERIALIZE_FN='AggSerialize' FINALIZE_FN='AggSerialize'");
AnalyzesOk("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='AggUpdate' SERIALIZE_FN='AggFinalize' FINALIZE_FN='AggFinalize'");
// If you don't specify the full symbol, we look for it in the binary. This should
// prevent mismatched names by accident.
AnalysisError("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='AggUpdate' INIT_FN='AggSerialize'",
"Could not find function AggSerialize() returns STRING in: " + hdfsLoc);
// If you specify a mangled name, we just check it exists.
// TODO: we should be able to validate better. This is almost certainly going
// to crash everything.
AnalyzesOk("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='AggUpdate' "+
"INIT_FN='_Z12AggSerializePN10impala_udf15FunctionContextERKNS_6IntValE'");
AnalysisError("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='AggUpdate' INIT_FN='_ZAggSerialize'",
"Could not find symbol '_ZAggSerialize' in: " + hdfsLoc);
// Tests for checking the symbol exists
AnalysisError("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg2Update'",
"Could not find function Agg2Init() returns STRING in: " + hdfsLoc);
AnalysisError("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg2Update' INIT_FN='AggInit'",
"Could not find function Agg2Merge(STRING) returns STRING in: " + hdfsLoc);
AnalyzesOk("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg2Update' INIT_FN='AggInit' MERGE_FN='AggMerge'");
AnalysisError("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg2Update' INIT_FN='AggInit' MERGE_FN='BadFn'",
"Could not find function BadFn(STRING) returns STRING in: " + hdfsLoc);
AnalysisError("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg2Update' INIT_FN='AggInit' MERGE_FN='AggMerge' "+
"FINALIZE_FN='not there'",
"Could not find function not there(STRING) in: " + hdfsLoc);
}
/**
* Wraps the given typeDefs in a CREATE TABLE stmt and runs AnalyzesOk().
* Also tests that the type is analyzes correctly in ARRAY, MAP, and STRUCT types.
*/
private void TypeDefsAnalyzeOk(String... typeDefs) {
for (String typeDefStr: typeDefs) {
ParseNode stmt = AnalyzesOk(String.format("CREATE TABLE t (i %s)", typeDefStr));
AnalyzesOk(String.format("CREATE TABLE t (i ARRAY<%s>)", typeDefStr));
AnalyzesOk(String.format("CREATE TABLE t (i STRUCT<f:%s>)", typeDefStr));
Preconditions.checkState(stmt instanceof CreateTableStmt);
CreateTableStmt createTableStmt = (CreateTableStmt) stmt;
Type t = createTableStmt.getColumnDefs().get(0).getType();
// If the given type is complex, don't use it as a map key.
if (t.isComplexType()) {
AnalyzesOk(String.format(
"CREATE TABLE t (i MAP<int, %s>)", typeDefStr, typeDefStr));
} else {
AnalyzesOk(String.format(
"CREATE TABLE t (i MAP<%s, %s>)", typeDefStr, typeDefStr));
}
}
}
/**
* Wraps the given typeDefs in a CREATE TABLE stmt and asserts that the type def
* failed to analyze with the given error message.
*/
private void TypeDefAnalysisError(String typeDef, String expectedError) {
AnalysisError(String.format("CREATE TABLE t (i %s)", typeDef), expectedError);
}
@Test
public void TestTypes() {
// Test primitive types.
TypeDefsAnalyzeOk("BOOLEAN");
TypeDefsAnalyzeOk("TINYINT");
TypeDefsAnalyzeOk("SMALLINT");
TypeDefsAnalyzeOk("INT", "INTEGER");
TypeDefsAnalyzeOk("BIGINT");
TypeDefsAnalyzeOk("FLOAT");
TypeDefsAnalyzeOk("DOUBLE", "REAL");
TypeDefsAnalyzeOk("STRING");
TypeDefsAnalyzeOk("CHAR(1)", "CHAR(20)");
TypeDefsAnalyzeOk("BINARY");
TypeDefsAnalyzeOk("DECIMAL");
TypeDefsAnalyzeOk("TIMESTAMP");
// Test decimal.
TypeDefsAnalyzeOk("DECIMAL");
TypeDefsAnalyzeOk("DECIMAL(1)");
TypeDefsAnalyzeOk("DECIMAL(12, 7)");
TypeDefsAnalyzeOk("DECIMAL(38)");
TypeDefsAnalyzeOk("DECIMAL(38, 1)");
TypeDefsAnalyzeOk("DECIMAL(38, 38)");
TypeDefAnalysisError("DECIMAL(1, 10)",
"Decimal scale (10) must be <= precision (1).");
TypeDefAnalysisError("DECIMAL(0, 0)",
"Decimal precision must be greater than 0.");
TypeDefAnalysisError("DECIMAL(39, 0)",
"Decimal precision must be <= 38.");
// Test complex types.
TypeDefsAnalyzeOk("ARRAY<BIGINT>");
TypeDefsAnalyzeOk("MAP<TINYINT, DOUBLE>");
TypeDefsAnalyzeOk("STRUCT<f:TINYINT>");
TypeDefsAnalyzeOk("STRUCT<a:TINYINT, b:BIGINT, c:DOUBLE>");
TypeDefsAnalyzeOk("STRUCT<a:TINYINT COMMENT 'x', b:BIGINT, c:DOUBLE COMMENT 'y'>");
// Map keys can't be complex types.
TypeDefAnalysisError("map<array<int>, int>",
"Map type cannot have a complex-typed key: MAP<ARRAY<INT>,INT>");
// Duplicate struct-field name.
TypeDefAnalysisError("STRUCT<f1: int, f2: string, f1: float>",
"Duplicate field name 'f1' in struct 'STRUCT<f1:INT,f2:STRING,f1:FLOAT>'");
// Invalid struct-field name.
TypeDefAnalysisError("STRUCT<`???`: int>",
"Invalid struct field name: ???");
}
@Test
public void TestUseDb() throws AnalysisException {
AnalyzesOk("use functional");
AnalysisError("use db_does_not_exist", "Database does not exist: db_does_not_exist");
}
@Test
public void TestUseStatement() {
Assert.assertTrue(AnalyzesOk("USE functional") instanceof UseStmt);
}
@Test
public void TestDescribe() throws AnalysisException {
AnalyzesOk("describe formatted functional.alltypes");
AnalyzesOk("describe functional.alltypes");
AnalysisError("describe formatted nodb.alltypes",
"Database does not exist: nodb");
AnalysisError("describe functional.notbl",
"Table does not exist: functional.notbl");
}
@Test
public void TestShow() throws AnalysisException {
AnalyzesOk("show databases");
AnalyzesOk("show databases like '*pattern'");
AnalyzesOk("show data sources");
AnalyzesOk("show data sources like '*pattern'");
AnalyzesOk("show tables");
AnalyzesOk("show tables like '*pattern'");
for (String fnType: new String[]{"", "aggregate", "analytic"}) {
AnalyzesOk(String.format("show %s functions", fnType));
AnalyzesOk(String.format("show %s functions like '*pattern'", fnType));
AnalyzesOk(String.format("show %s functions in functional", fnType));
AnalyzesOk(String.format(
"show %s functions in functional like '*pattern'", fnType));
}
// Database doesn't exist.
AnalysisError("show functions in baddb", "Database does not exist: baddb");
AnalysisError("show functions in baddb like '*pattern'",
"Database does not exist: baddb");
}
@Test
public void TestShowFiles() throws AnalysisException {
// Test empty table
AnalyzesOk(String.format("show files in functional.emptytable"));
String[] partitions = new String[] { "", "partition(month=10, year=2010)" };
for (String partition: partitions) {
AnalyzesOk(String.format("show files in functional.alltypes %s", partition));
// Database/table doesn't exist.
AnalysisError(String.format("show files in baddb.alltypes %s", partition),
"Database does not exist: baddb");
AnalysisError(String.format("show files in functional.badtbl %s", partition),
"Table does not exist: functional.badtbl");
// Cannot show files on a non hdfs table.
AnalysisError(String.format("show files in functional.alltypes_view %s",
partition),
"SHOW FILES not applicable to a non hdfs table: functional.alltypes_view");
}
// Not a partition column.
AnalysisError("show files in functional.alltypes partition(year=2010,int_col=1)",
"Column 'int_col' is not a partition column in table: functional.alltypes");
// Not a valid column.
AnalysisError("show files in functional.alltypes partition(year=2010,day=1)",
"Partition column 'day' not found in table: functional.alltypes");
// Table is not partitioned.
AnalysisError("show files in functional.tinyinttable partition(int_col=1)",
"Table is not partitioned: functional.tinyinttable");
// Partition spec does not exist
AnalysisError("show files in functional.alltypes partition(year=2010,month=NULL)",
"Partition spec does not exist: (year=2010, month=NULL)");
}
@Test
public void TestShowStats() throws AnalysisException {
String[] statsQuals = new String[] {"table", "column"};
for (String qual : statsQuals) {
AnalyzesOk(String.format("show %s stats functional.alltypes", qual));
// Database/table doesn't exist.
AnalysisError(String.format("show %s stats baddb.alltypes", qual),
"Database does not exist: baddb");
AnalysisError(String.format("show %s stats functional.badtbl", qual),
"Table does not exist: functional.badtbl");
// Cannot show stats on a view.
AnalysisError(String.format("show %s stats functional.alltypes_view", qual),
String.format("SHOW %s STATS not applicable to a view: " +
"functional.alltypes_view", qual.toUpperCase()));
}
}
@Test
public void TestShowPartitions() throws AnalysisException {
AnalyzesOk("show partitions functional.alltypes");
AnalysisError("show partitions baddb.alltypes",
"Database does not exist: baddb");
AnalysisError("show partitions functional.badtbl",
"Table does not exist: functional.badtbl");
AnalysisError("show partitions functional.alltypesnopart",
"Table is not partitioned: functional.alltypesnopart");
AnalysisError("show partitions functional.view_view",
"SHOW PARTITIONS not applicable to a view: functional.view_view");
AnalysisError("show partitions functional_hbase.alltypes",
"SHOW PARTITIONS must target an HDFS table: functional_hbase.alltypes");
}
/**
* Validate if location path analysis issues proper warnings when directory
* permissions/existence checks fail.
*/
@Test
public void TestPermissionValidation() throws AnalysisException {
String location = "/test-warehouse/.tmp_" + UUID.randomUUID().toString();
Path parentPath = FileSystemUtil.createFullyQualifiedPath(new Path(location));
FileSystem fs = null;
try {
fs = parentPath.getFileSystem(FileSystemUtil.getConfiguration());
// Test location doesn't exist
AnalyzesOk(String.format("create table new_table (col INT) location '%s/new_table'",
location),
String.format("Path '%s' cannot be reached: Path does not exist.",
parentPath));
// Test localtion path with trailing slash.
AnalyzesOk(String.format("create table new_table (col INT) location " +
"'%s/new_table/'", location),
String.format("Path '%s' cannot be reached: Path does not exist.",
parentPath));
AnalyzesOk(String.format("create table new_table location '%s/new_table' " +
"as select 1, 1", location),
String.format("Path '%s' cannot be reached: Path does not exist.",
parentPath));
AnalyzesOk(String.format("create table new_table like functional.alltypes " +
"location '%s/new_table'", location),
String.format("Path '%s' cannot be reached: Path does not exist.",
parentPath));
AnalyzesOk(String.format("create database new_db location '%s/new_db'",
location),
String.format("Path '%s' cannot be reached: Path does not exist.",
parentPath));
fs.mkdirs(parentPath);
// Create a test data file for load data test
FSDataOutputStream out =
fs.create(new Path(parentPath, "test_loaddata/testdata.txt"));
out.close();
fs.setPermission(parentPath,
new FsPermission(FsAction.NONE, FsAction.NONE, FsAction.NONE));
// Test location exists but Impala doesn't have sufficient permission
AnalyzesOk(String.format("create data Source serverlog location " +
"'%s/foo.jar' class 'foo.Bar' API_VERSION 'V1'", location),
String.format("Impala does not have READ access to path '%s'", parentPath));
AnalyzesOk(String.format("create external table new_table (col INT) location " +
"'%s/new_table'", location),
String.format("Impala does not have READ_WRITE access to path '%s'",
parentPath));
AnalyzesOk(String.format("alter table functional.insert_string_partitioned " +
"add partition (s2='hello') location '%s/new_partition'", location),
String.format("Impala does not have READ_WRITE access to path '%s'",
parentPath));
AnalyzesOk(String.format("alter table functional.insert_string_partitioned " +
"partition(s2=NULL) set location '%s/new_part_loc'", location),
String.format("Impala does not have READ_WRITE access to path '%s'",
parentPath));
// Test location exists and Impala does have sufficient permission
fs.setPermission(parentPath,
new FsPermission(FsAction.READ_WRITE, FsAction.NONE, FsAction.NONE));
AnalyzesOk(String.format("create external table new_table (col INT) location " +
"'%s/new_table'", location));
} catch (IOException e) {
throw new AnalysisException(e.getMessage(), e);
} finally {
// Clean up
try {
if (fs != null && fs.exists(parentPath)) {
fs.delete(parentPath, true);
}
} catch (IOException e) {
// Ignore
}
}
}
}
|
fe/src/test/java/com/cloudera/impala/analysis/AnalyzeDDLTest.java
|
// Copyright (c) 2012 Cloudera, 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.cloudera.impala.analysis;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import junit.framework.Assert;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.junit.Test;
import com.cloudera.impala.catalog.CatalogException;
import com.cloudera.impala.catalog.DataSource;
import com.cloudera.impala.catalog.DataSourceTable;
import com.cloudera.impala.catalog.PrimitiveType;
import com.cloudera.impala.catalog.ScalarType;
import com.cloudera.impala.catalog.Type;
import com.cloudera.impala.common.AnalysisException;
import com.cloudera.impala.common.FileSystemUtil;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
public class AnalyzeDDLTest extends AnalyzerTest {
@Test
public void TestAlterTableAddDropPartition() throws CatalogException {
String[] addDrop = {"add if not exists", "drop if exists"};
for (String kw: addDrop) {
// Add different partitions for different column types
AnalyzesOk("alter table functional.alltypes " + kw +
" partition(year=2050, month=10)");
AnalyzesOk("alter table functional.alltypes " + kw +
" partition(month=10, year=2050)");
AnalyzesOk("alter table functional.insert_string_partitioned " + kw +
" partition(s2='1234')");
// Can't add/drop partitions to/from unpartitioned tables
AnalysisError("alter table functional.alltypesnopart " + kw + " partition (i=1)",
"Table is not partitioned: functional.alltypesnopart");
AnalysisError("alter table functional_hbase.alltypesagg " + kw +
" partition (i=1)", "Table is not partitioned: functional_hbase.alltypesagg");
// Duplicate partition key name
AnalysisError("alter table functional.alltypes " + kw +
" partition(year=2050, year=2051)", "Duplicate partition key name: year");
// Not a partition column
AnalysisError("alter table functional.alltypes " + kw +
" partition(year=2050, int_col=1)",
"Column 'int_col' is not a partition column in table: functional.alltypes");
// NULL partition keys
AnalyzesOk("alter table functional.alltypes " + kw +
" partition(year=NULL, month=1)");
AnalyzesOk("alter table functional.alltypes " + kw +
" partition(year=NULL, month=NULL)");
AnalyzesOk("alter table functional.alltypes " + kw +
" partition(year=ascii(null), month=ascii(NULL))");
// Empty string partition keys
AnalyzesOk("alter table functional.insert_string_partitioned " + kw +
" partition(s2='')");
// Arbitrary exprs as partition key values. Constant exprs are ok.
AnalyzesOk("alter table functional.alltypes " + kw +
" partition(year=-1, month=cast((10+5*4) as INT))");
// Arbitrary exprs as partition key values. Non-constant exprs should fail.
AnalysisError("alter table functional.alltypes " + kw +
" partition(year=2050, month=int_col)",
"Non-constant expressions are not supported as static partition-key values " +
"in 'month=int_col'.");
AnalysisError("alter table functional.alltypes " + kw +
" partition(year=cast(int_col as int), month=12)",
"Non-constant expressions are not supported as static partition-key values " +
"in 'year=CAST(int_col AS INT)'.");
// Not a valid column
AnalysisError("alter table functional.alltypes " + kw +
" partition(year=2050, blah=1)",
"Partition column 'blah' not found in table: functional.alltypes");
// Data types don't match
AnalysisError(
"alter table functional.insert_string_partitioned " + kw +
" partition(s2=1234)",
"Value of partition spec (column=s2) has incompatible type: 'SMALLINT'. " +
"Expected type: 'STRING'.");
// Loss of precision
AnalysisError(
"alter table functional.alltypes " + kw +
" partition(year=100000000000, month=10)",
"Partition key value may result in loss of precision.\nWould need to cast" +
" '100000000000' to 'INT' for partition column: year");
// Table/Db does not exist
AnalysisError("alter table db_does_not_exist.alltypes " + kw +
" partition (i=1)", "Database does not exist: db_does_not_exist");
AnalysisError("alter table functional.table_does_not_exist " + kw +
" partition (i=1)", "Table does not exist: functional.table_does_not_exist");
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view " + kw +
" partition(year=2050, month=10)",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
AnalysisError("alter table functional.alltypes_datasource " + kw +
" partition(year=2050, month=10)",
"ALTER TABLE not allowed on a table produced by a data source: " +
"functional.alltypes_datasource");
}
// IF NOT EXISTS properly checks for partition existence
AnalyzesOk("alter table functional.alltypes add " +
"partition(year=2050, month=10)");
AnalysisError("alter table functional.alltypes add " +
"partition(year=2010, month=10)",
"Partition spec already exists: (year=2010, month=10).");
AnalyzesOk("alter table functional.alltypes add if not exists " +
" partition(year=2010, month=10)");
AnalyzesOk("alter table functional.alltypes add if not exists " +
" partition(year=2010, month=10) location " +
"'/test-warehouse/alltypes/year=2010/month=10'");
// IF EXISTS properly checks for partition existence
AnalyzesOk("alter table functional.alltypes drop " +
"partition(year=2010, month=10)");
AnalysisError("alter table functional.alltypes drop " +
"partition(year=2050, month=10)",
"Partition spec does not exist: (year=2050, month=10).");
AnalyzesOk("alter table functional.alltypes drop if exists " +
"partition(year=2050, month=10)");
// Caching ops
AnalyzesOk("alter table functional.alltypes add " +
"partition(year=2050, month=10) cached in 'testPool'");
AnalyzesOk("alter table functional.alltypes add " +
"partition(year=2050, month=10) cached in 'testPool' with replication = 10");
AnalyzesOk("alter table functional.alltypes add " +
"partition(year=2050, month=10) uncached");
AnalysisError("alter table functional.alltypes add " +
"partition(year=2050, month=10) cached in 'badPool'",
"The specified cache pool does not exist: badPool");
// Valid URIs.
AnalyzesOk("alter table functional.alltypes add " +
" partition(year=2050, month=10) location " +
"'/test-warehouse/alltypes/year=2010/month=10'");
AnalyzesOk("alter table functional.alltypes add " +
" partition(year=2050, month=10) location " +
"'hdfs://localhost:20500/test-warehouse/alltypes/year=2010/month=10'");
AnalyzesOk("alter table functional.alltypes add " +
" partition(year=2050, month=10) location " +
"'s3n://bucket/test-warehouse/alltypes/year=2010/month=10'");
AnalyzesOk("alter table functional.alltypes add " +
" partition(year=2050, month=10) location " +
"'file:///test-warehouse/alltypes/year=2010/month=10'");
// Invalid URIs.
AnalysisError("alter table functional.alltypes add " +
" partition(year=2050, month=10) location " +
"'foofs://bar/test-warehouse/alltypes/year=2010/month=10'",
"No FileSystem for scheme: foofs");
AnalysisError("alter table functional.alltypes add " +
" partition(year=2050, month=10) location ' '",
"URI path cannot be empty.");
}
@Test
public void TestAlterTableAddReplaceColumns() throws AnalysisException {
AnalyzesOk("alter table functional.alltypes add columns (new_col int)");
AnalyzesOk("alter table functional.alltypes add columns (c1 string comment 'hi')");
AnalyzesOk("alter table functional.alltypes add columns (c struct<f1:int>)");
AnalyzesOk(
"alter table functional.alltypes replace columns (c1 int comment 'c', c2 int)");
AnalyzesOk("alter table functional.alltypes replace columns (c array<string>)");
// Column name must be unique for add
AnalysisError("alter table functional.alltypes add columns (int_col int)",
"Column already exists: int_col");
// Add a column with same name as a partition column
AnalysisError("alter table functional.alltypes add columns (year int)",
"Column name conflicts with existing partition column: year");
// Invalid column name.
AnalysisError("alter table functional.alltypes add columns (`???` int)",
"Invalid column/field name: ???");
AnalysisError("alter table functional.alltypes replace columns (`???` int)",
"Invalid column/field name: ???");
// Replace should not throw an error if the column already exists
AnalyzesOk("alter table functional.alltypes replace columns (int_col int)");
// It is not possible to replace a partition column
AnalysisError("alter table functional.alltypes replace columns (Year int)",
"Column name conflicts with existing partition column: year");
// Duplicate column names
AnalysisError("alter table functional.alltypes add columns (c1 int, c1 int)",
"Duplicate column name: c1");
AnalysisError("alter table functional.alltypes replace columns (c1 int, C1 int)",
"Duplicate column name: c1");
// Table/Db does not exist
AnalysisError("alter table db_does_not_exist.alltypes add columns (i int)",
"Database does not exist: db_does_not_exist");
AnalysisError("alter table functional.table_does_not_exist add columns (i int)",
"Table does not exist: functional.table_does_not_exist");
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view " +
"add columns (c1 string comment 'hi')",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
// Cannot ALTER TABLE produced by a data source.
AnalysisError("alter table functional.alltypes_datasource " +
"add columns (c1 string comment 'hi')",
"ALTER TABLE not allowed on a table produced by a data source: " +
"functional.alltypes_datasource");
// Cannot ALTER TABLE ADD/REPLACE COLUMNS on an HBase table.
AnalysisError("alter table functional_hbase.alltypes add columns (i int)",
"ALTER TABLE ADD|REPLACE COLUMNS not currently supported on HBase tables.");
}
@Test
public void TestAlterTableDropColumn() throws AnalysisException {
AnalyzesOk("alter table functional.alltypes drop column int_col");
AnalysisError("alter table functional.alltypes drop column no_col",
"Column 'no_col' does not exist in table: functional.alltypes");
AnalysisError("alter table functional.alltypes drop column year",
"Cannot drop partition column: year");
// Tables should always have at least 1 column
AnalysisError("alter table functional_seq_snap.bad_seq_snap drop column field",
"Cannot drop column 'field' from functional_seq_snap.bad_seq_snap. " +
"Tables must contain at least 1 column.");
// Table/Db does not exist
AnalysisError("alter table db_does_not_exist.alltypes drop column col1",
"Database does not exist: db_does_not_exist");
AnalysisError("alter table functional.table_does_not_exist drop column col1",
"Table does not exist: functional.table_does_not_exist");
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view drop column int_col",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
// Cannot ALTER TABLE produced by a data source.
AnalysisError("alter table functional.alltypes_datasource drop column int_col",
"ALTER TABLE not allowed on a table produced by a data source: " +
"functional.alltypes_datasource");
// Cannot ALTER TABLE DROP COLUMN on an HBase table.
AnalysisError("alter table functional_hbase.alltypes drop column int_col",
"ALTER TABLE DROP COLUMN not currently supported on HBase tables.");
}
@Test
public void TestAlterTableChangeColumn() throws AnalysisException {
// Rename a column
AnalyzesOk("alter table functional.alltypes change column int_col int_col2 int");
// Rename and change the datatype
AnalyzesOk("alter table functional.alltypes change column int_col c2 string");
AnalyzesOk(
"alter table functional.alltypes change column int_col c2 map<int, string>");
// Change only the datatype
AnalyzesOk("alter table functional.alltypes change column int_col int_col tinyint");
// Add a comment to a column.
AnalyzesOk("alter table functional.alltypes change int_col int_col int comment 'c'");
AnalysisError("alter table functional.alltypes change column no_col c1 int",
"Column 'no_col' does not exist in table: functional.alltypes");
AnalysisError("alter table functional.alltypes change column year year int",
"Cannot modify partition column: year");
AnalysisError(
"alter table functional.alltypes change column int_col Tinyint_col int",
"Column already exists: Tinyint_col");
// Invalid column name.
AnalysisError("alter table functional.alltypes change column int_col `???` int",
"Invalid column/field name: ???");
// Table/Db does not exist
AnalysisError("alter table db_does_not_exist.alltypes change c1 c2 int",
"Database does not exist: db_does_not_exist");
AnalysisError("alter table functional.table_does_not_exist change c1 c2 double",
"Table does not exist: functional.table_does_not_exist");
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view " +
"change column int_col int_col2 int",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
// Cannot ALTER TABLE produced by a data source.
AnalysisError("alter table functional.alltypes_datasource " +
"change column int_col int_col2 int",
"ALTER TABLE not allowed on a table produced by a data source: " +
"functional.alltypes_datasource");
// Cannot ALTER TABLE CHANGE COLUMN on an HBase table.
AnalysisError("alter table functional_hbase.alltypes CHANGE COLUMN int_col i int",
"ALTER TABLE CHANGE COLUMN not currently supported on HBase tables.");
}
@Test
public void TestAlterTableSet() throws AnalysisException {
AnalyzesOk("alter table functional.alltypes set fileformat sequencefile");
AnalyzesOk("alter table functional.alltypes set location '/a/b'");
AnalyzesOk("alter table functional.alltypes set tblproperties('a'='1')");
AnalyzesOk("alter table functional.alltypes set serdeproperties('a'='2')");
AnalyzesOk("alter table functional.alltypes PARTITION (Year=2010, month=11) " +
"set location '/a/b'");
AnalyzesOk("alter table functional.alltypes PARTITION (month=11, year=2010) " +
"set fileformat parquetfile");
AnalyzesOk("alter table functional.stringpartitionkey PARTITION " +
"(string_col='partition1') set fileformat parquet");
AnalyzesOk("alter table functional.stringpartitionkey PARTITION " +
"(string_col='PaRtiTion1') set location '/a/b/c'");
AnalyzesOk("alter table functional.alltypes PARTITION (year=2010, month=11) " +
"set tblproperties('a'='1')");
AnalyzesOk("alter table functional.alltypes PARTITION (year=2010, month=11) " +
"set serdeproperties ('a'='2')");
// Arbitrary exprs as partition key values. Constant exprs are ok.
AnalyzesOk("alter table functional.alltypes PARTITION " +
"(year=cast(100*20+10 as INT), month=cast(2+9 as INT)) " +
"set fileformat sequencefile");
AnalyzesOk("alter table functional.alltypes PARTITION " +
"(year=cast(100*20+10 as INT), month=cast(2+9 as INT)) " +
"set location '/a/b'");
// Arbitrary exprs as partition key values. Non-constant exprs should fail.
AnalysisError("alter table functional.alltypes PARTITION " +
"(Year=2050, month=int_col) set fileformat sequencefile",
"Non-constant expressions are not supported as static partition-key " +
"values in 'month=int_col'.");
AnalysisError("alter table functional.alltypes PARTITION " +
"(Year=2050, month=int_col) set location '/a/b'",
"Non-constant expressions are not supported as static partition-key " +
"values in 'month=int_col'.");
// Partition spec does not exist
AnalysisError("alter table functional.alltypes PARTITION (year=2014, month=11) " +
"set location '/a/b'",
"Partition spec does not exist: (year=2014, month=11)");
AnalysisError("alter table functional.alltypes PARTITION (year=2014, month=11) " +
"set tblproperties('a'='1')",
"Partition spec does not exist: (year=2014, month=11)");
AnalysisError("alter table functional.alltypes PARTITION (year=2010) " +
"set tblproperties('a'='1')",
"Items in partition spec must exactly match the partition columns " +
"in the table definition: functional.alltypes (1 vs 2)");
AnalysisError("alter table functional.alltypes PARTITION (year=2010, year=2010) " +
"set location '/a/b'",
"Duplicate partition key name: year");
AnalysisError("alter table functional.alltypes PARTITION (month=11, year=2014) " +
"set fileformat sequencefile",
"Partition spec does not exist: (month=11, year=2014)");
AnalysisError("alter table functional.alltypesnopart PARTITION (month=1) " +
"set fileformat sequencefile",
"Table is not partitioned: functional.alltypesnopart");
AnalysisError("alter table functional.alltypesnopart PARTITION (month=1) " +
"set location '/a/b/c'",
"Table is not partitioned: functional.alltypesnopart");
AnalysisError("alter table functional.stringpartitionkey PARTITION " +
"(string_col='partition2') set location '/a/b'",
"Partition spec does not exist: (string_col='partition2')");
AnalysisError("alter table functional.stringpartitionkey PARTITION " +
"(string_col='partition2') set fileformat sequencefile",
"Partition spec does not exist: (string_col='partition2')");
AnalysisError("alter table functional.alltypes PARTITION " +
"(year=cast(10*20+10 as INT), month=cast(5*3 as INT)) " +
"set location '/a/b'",
"Partition spec does not exist: " +
"(year=CAST(10 * 20 + 10 AS INT), month=CAST(5 * 3 AS INT))");
AnalysisError("alter table functional.alltypes PARTITION " +
"(year=cast(10*20+10 as INT), month=cast(5*3 as INT)) " +
"set fileformat sequencefile",
"Partition spec does not exist: " +
"(year=CAST(10 * 20 + 10 AS INT), month=CAST(5 * 3 AS INT))");
// Table/Db does not exist
AnalysisError("alter table db_does_not_exist.alltypes set fileformat sequencefile",
"Database does not exist: db_does_not_exist");
AnalysisError("alter table functional.table_does_not_exist set fileformat rcfile",
"Table does not exist: functional.table_does_not_exist");
AnalysisError("alter table db_does_not_exist.alltypes set location '/a/b'",
"Database does not exist: db_does_not_exist");
AnalysisError("alter table functional.table_does_not_exist set location '/a/b'",
"Table does not exist: functional.table_does_not_exist");
AnalysisError("alter table functional.no_tbl partition(i=1) set location '/a/b'",
"Table does not exist: functional.no_tbl");
AnalysisError("alter table no_db.alltypes partition(i=1) set fileformat textfile",
"Database does not exist: no_db");
// Valid location
AnalyzesOk("alter table functional.alltypes set location " +
"'hdfs://localhost:20500/test-warehouse/a/b'");
AnalyzesOk("alter table functional.alltypes set location " +
"'s3n://bucket/test-warehouse/a/b'");
AnalyzesOk("alter table functional.alltypes set location " +
"'file:///test-warehouse/a/b'");
// Invalid location
AnalysisError("alter table functional.alltypes set location 'test/warehouse'",
"URI path must be absolute: test/warehouse");
AnalysisError("alter table functional.alltypes set location 'blah:///warehouse/'",
"No FileSystem for scheme: blah");
AnalysisError("alter table functional.alltypes set location ''",
"URI path cannot be empty.");
AnalysisError("alter table functional.alltypes set location ' '",
"URI path cannot be empty.");
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view set fileformat sequencefile",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
// Cannot ALTER TABLE produced by a data source.
AnalysisError("alter table functional.alltypes_datasource set fileformat parquet",
"ALTER TABLE not allowed on a table produced by a data source: " +
"functional.alltypes_datasource");
// Cannot ALTER TABLE SET on an HBase table.
AnalysisError("alter table functional_hbase.alltypes set tblproperties('a'='b')",
"ALTER TABLE SET not currently supported on HBase tables.");
}
@Test
public void TestAlterTableSetCached() {
// Positive cases
AnalyzesOk("alter table functional.alltypesnopart set cached in 'testPool'");
AnalyzesOk("alter table functional.alltypes set cached in 'testPool'");
AnalyzesOk("alter table functional.alltypes partition(year=2010, month=12) " +
"set cached in 'testPool'");
// Replication factor
AnalyzesOk("alter table functional.alltypes set cached in 'testPool' " +
"with replication = 10");
AnalyzesOk("alter table functional.alltypes partition(year=2010, month=12) " +
"set cached in 'testPool' with replication = 4");
AnalysisError("alter table functional.alltypes set cached in 'testPool' " +
"with replication = 0",
"Cache replication factor must be between 0 and Short.MAX_VALUE");
AnalysisError("alter table functional.alltypes set cached in 'testPool' " +
"with replication = 90000",
"Cache replication factor must be between 0 and Short.MAX_VALUE");
// Attempt to alter a table that is not backed by HDFS.
AnalysisError("alter table functional_hbase.alltypesnopart set cached in 'testPool'",
"ALTER TABLE SET not currently supported on HBase tables.");
AnalysisError("alter table functional.view_view set cached in 'testPool'",
"ALTER TABLE not allowed on a view: functional.view_view");
AnalysisError("alter table functional.alltypes set cached in 'badPool'",
"The specified cache pool does not exist: badPool");
AnalysisError("alter table functional.alltypes partition(year=2010, month=12) " +
"set cached in 'badPool'", "The specified cache pool does not exist: badPool");
// Attempt to uncache a table that is not cached. Should be a no-op.
AnalyzesOk("alter table functional.alltypes set uncached");
AnalyzesOk("alter table functional.alltypes partition(year=2010, month=12) " +
"set uncached");
// Attempt to cache a table that is already cached. Should be a no-op.
AnalyzesOk("alter table functional.alltypestiny set cached in 'testPool'");
AnalyzesOk("alter table functional.alltypestiny partition(year=2009, month=1) " +
"set cached in 'testPool'");
// Change location of a cached table/partition
AnalysisError("alter table functional.alltypestiny set location '/tmp/tiny'",
"Target table is cached, please uncache before changing the location using: " +
"ALTER TABLE functional.alltypestiny SET UNCACHED");
AnalysisError("alter table functional.alltypestiny partition (year=2009,month=1) " +
"set location '/test-warehouse/new_location'",
"Target partition is cached, please uncache before changing the location " +
"using: ALTER TABLE functional.alltypestiny PARTITION (year=2009, month=1) " +
"SET UNCACHED");
// Table/db/partition do not exist
AnalysisError("alter table baddb.alltypestiny set cached in 'testPool'",
"Database does not exist: baddb");
AnalysisError("alter table functional.badtbl set cached in 'testPool'",
"Table does not exist: functional.badtbl");
AnalysisError("alter table functional.alltypestiny partition(year=9999, month=1) " +
"set cached in 'testPool'",
"Partition spec does not exist: (year=9999, month=1).");
}
@Test
public void TestAlterTableRename() throws AnalysisException {
AnalyzesOk("alter table functional.alltypes rename to new_alltypes");
AnalyzesOk("alter table functional.alltypes rename to functional.new_alltypes");
AnalysisError("alter table functional.alltypes rename to functional.alltypes",
"Table already exists: functional.alltypes");
AnalysisError("alter table functional.alltypes rename to functional.alltypesagg",
"Table already exists: functional.alltypesagg");
AnalysisError("alter table functional.table_does_not_exist rename to new_table",
"Table does not exist: functional.table_does_not_exist");
AnalysisError("alter table db_does_not_exist.alltypes rename to new_table",
"Database does not exist: db_does_not_exist");
// Invalid database/table name.
AnalysisError("alter table functional.alltypes rename to `???`.new_table",
"Invalid database name: ???");
AnalysisError("alter table functional.alltypes rename to functional.`%^&`",
"Invalid table/view name: %^&");
AnalysisError(
"alter table functional.alltypes rename to db_does_not_exist.new_table",
"Database does not exist: db_does_not_exist");
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view rename to new_alltypes",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
// It should be okay to rename an HBase table.
AnalyzesOk("alter table functional_hbase.alltypes rename to new_alltypes");
// It should be okay to rename a table produced by a data source.
AnalyzesOk("alter table functional.alltypes_datasource rename to new_datasrc_tbl");
}
@Test
public void TestAlterView() {
// View-definition references a table.
AnalyzesOk("alter view functional.alltypes_view as " +
"select * from functional.alltypesagg");
// View-definition references a view.
AnalyzesOk("alter view functional.alltypes_view as " +
"select * from functional.alltypes_view");
// View-definition resulting in Hive-style auto-generated column names.
AnalyzesOk("alter view functional.alltypes_view as " +
"select trim('abc'), 17 * 7");
// Cannot ALTER VIEW a table.
AnalysisError("alter view functional.alltypes as " +
"select * from functional.alltypesagg",
"ALTER VIEW not allowed on a table: functional.alltypes");
AnalysisError("alter view functional_hbase.alltypesagg as " +
"select * from functional.alltypesagg",
"ALTER VIEW not allowed on a table: functional_hbase.alltypesagg");
// Target database does not exist.
AnalysisError("alter view baddb.alltypes_view as " +
"select * from functional.alltypesagg",
"Database does not exist: baddb");
// Target view does not exist.
AnalysisError("alter view functional.badview as " +
"select * from functional.alltypesagg",
"Table does not exist: functional.badview");
// View-definition statement fails to analyze. Database does not exist.
AnalysisError("alter view functional.alltypes_view as " +
"select * from baddb.alltypesagg",
"Database does not exist: baddb");
// View-definition statement fails to analyze. Table does not exist.
AnalysisError("alter view functional.alltypes_view as " +
"select * from functional.badtable",
"Table does not exist: functional.badtable");
// Duplicate column name.
AnalysisError("alter view functional.alltypes_view as " +
"select * from functional.alltypessmall a inner join " +
"functional.alltypessmall b on a.id = b.id",
"Duplicate column name: id");
// Invalid column name.
AnalysisError("alter view functional.alltypes_view as select 'abc' as `???`",
"Invalid column/field name: ???");
}
@Test
public void TestAlterViewRename() throws AnalysisException {
AnalyzesOk("alter view functional.alltypes_view rename to new_view");
AnalyzesOk("alter view functional.alltypes_view rename to functional.new_view");
AnalysisError("alter view functional.alltypes_view rename to functional.alltypes",
"Table already exists: functional.alltypes");
AnalysisError("alter view functional.alltypes_view rename to functional.alltypesagg",
"Table already exists: functional.alltypesagg");
AnalysisError("alter view functional.view_does_not_exist rename to new_view",
"Table does not exist: functional.view_does_not_exist");
AnalysisError("alter view db_does_not_exist.alltypes_view rename to new_view",
"Database does not exist: db_does_not_exist");
AnalysisError("alter view functional.alltypes_view " +
"rename to db_does_not_exist.new_view",
"Database does not exist: db_does_not_exist");
// Invalid database/table name.
AnalysisError("alter view functional.alltypes_view rename to `???`.new_view",
"Invalid database name: ???");
AnalysisError("alter view functional.alltypes_view rename to functional.`%^&`",
"Invalid table/view name: %^&");
// Cannot ALTER VIEW a able.
AnalysisError("alter view functional.alltypes rename to new_alltypes",
"ALTER VIEW not allowed on a table: functional.alltypes");
}
void checkComputeStatsStmt(String stmt) throws AnalysisException {
ParseNode parseNode = AnalyzesOk(stmt);
assertTrue(parseNode instanceof ComputeStatsStmt);
ComputeStatsStmt parsedStmt = (ComputeStatsStmt)parseNode;
AnalyzesOk(parsedStmt.getTblStatsQuery());
AnalyzesOk(parsedStmt.getColStatsQuery());
}
@Test
public void TestComputeStats() throws AnalysisException {
// Analyze the stmt itself as well as the generated child queries.
checkComputeStatsStmt("compute stats functional.alltypes");
checkComputeStatsStmt("compute stats functional_hbase.alltypes");
// Test that complex-typed columns are ignored.
checkComputeStatsStmt("compute stats functional.allcomplextypes");
// Cannot compute stats on a database.
AnalysisError("compute stats tbl_does_not_exist",
"Table does not exist: default.tbl_does_not_exist");
// Cannot compute stats on a view.
AnalysisError("compute stats functional.alltypes_view",
"COMPUTE STATS not supported for view functional.alltypes_view");
AnalyzesOk("compute stats functional_avro_snap.alltypes");
// Test mismatched column definitions and Avro schema (HIVE-6308, IMPALA-867).
// See testdata/avro_schema_resolution/create_table.sql for the CREATE TABLE stmts.
// Mismatched column type is ok because the conflict is resolved in favor of
// the type in the column definition list in the CREATE TABLE.
AnalyzesOk("compute stats functional_avro_snap.alltypes_type_mismatch");
// Missing column definition is ok because the schema mismatch is resolved
// in the CREATE TABLE.
AnalyzesOk("compute stats functional_avro_snap.alltypes_missing_coldef");
// Extra column definition is ok because the schema mismatch is resolved
// in the CREATE TABLE.
AnalyzesOk("compute stats functional_avro_snap.alltypes_extra_coldef");
// Mismatched column name (tables were created by Hive).
AnalysisError("compute stats functional_avro_snap.schema_resolution_test",
"Cannot COMPUTE STATS on Avro table 'schema_resolution_test' because its " +
"column definitions do not match those in the Avro schema.\nDefinition of " +
"column 'col1' of type 'string' does not match the Avro-schema column " +
"'boolean1' of type 'BOOLEAN' at position '0'.\nPlease re-create the table " +
"with column definitions, e.g., using the result of 'SHOW CREATE TABLE'");
// No column definitions were given at all. This case is broken in Hive (HIVE-6308),
// but works when such a table is created through Impala.
AnalysisError("compute stats functional_avro_snap.alltypes_no_coldef",
"Cannot COMPUTE STATS on Avro table 'alltypes_no_coldef' because its column " +
"definitions do not match those in the Avro schema.\nMissing column " +
"definition corresponding to Avro-schema column 'id' of type 'INT' at " +
"position '0'.\nPlease re-create the table with column definitions, e.g., " +
"using the result of 'SHOW CREATE TABLE'");
}
@Test
public void TestComputeIncrementalStats() throws AnalysisException {
checkComputeStatsStmt("compute incremental stats functional.alltypes");
checkComputeStatsStmt(
"compute incremental stats functional.alltypes partition(year=2010, month=10)");
AnalysisError(
"compute incremental stats functional.alltypes partition(year=9999, month=10)",
"Partition spec does not exist: (year=9999, month=10)");
AnalysisError(
"compute incremental stats functional.alltypes partition(year=2010)",
"Items in partition spec must exactly match the partition columns in the table " +
"definition: functional.alltypes (1 vs 2)");
AnalysisError(
"compute incremental stats functional.alltypes partition(year=2010, month)",
"Syntax error");
// Test that NULL partitions generates a valid query
checkComputeStatsStmt("compute incremental stats functional.alltypesagg " +
"partition(year=2010, month=1, day=NULL)");
AnalysisError("compute incremental stats functional_hbase.alltypes " +
"partition(year=2010, month=1)", "COMPUTE INCREMENTAL ... PARTITION not " +
"supported for non-HDFS table functional_hbase.alltypes");
AnalysisError("compute incremental stats functional.view_view",
"COMPUTE STATS not supported for view functional.view_view");
}
@Test
public void TestDropIncrementalStats() throws AnalysisException {
AnalyzesOk(
"drop incremental stats functional.alltypes partition(year=2010, month=10)");
AnalysisError(
"drop incremental stats functional.alltypes partition(year=9999, month=10)",
"Partition spec does not exist: (year=9999, month=10)");
}
@Test
public void TestDropStats() throws AnalysisException {
AnalyzesOk("drop stats functional.alltypes");
// Table does not exist
AnalysisError("drop stats tbl_does_not_exist",
"Table does not exist: default.tbl_does_not_exist");
// Database does not exist
AnalysisError("drop stats no_db.no_tbl",
"Database does not exist: no_db");
AnalysisError("drop stats functional.alltypes partition(year=2010, month=10)",
"Syntax error");
AnalysisError("drop stats functional.alltypes partition(year, month)",
"Syntax error");
}
@Test
public void TestDrop() throws AnalysisException {
AnalyzesOk("drop database functional");
AnalyzesOk("drop table functional.alltypes");
AnalyzesOk("drop view functional.alltypes_view");
// If the database does not exist, and the user hasn't specified "IF EXISTS",
// an analysis error should be thrown
AnalysisError("drop database db_does_not_exist",
"Database does not exist: db_does_not_exist");
AnalysisError("drop table db_does_not_exist.alltypes",
"Database does not exist: db_does_not_exist");
AnalysisError("drop view db_does_not_exist.alltypes_view",
"Database does not exist: db_does_not_exist");
// Invalid name reports non-existence instead of invalidity.
AnalysisError("drop database `???`",
"Database does not exist: ???");
AnalysisError("drop table functional.`%^&`",
"Table does not exist: functional.%^&");
AnalysisError("drop view functional.`@#$%`",
"Table does not exist: functional.@#$%");
// If the database exist but the table doesn't, and the user hasn't specified
// "IF EXISTS", an analysis error should be thrown
AnalysisError("drop table functional.badtable",
"Table does not exist: functional.badtable");
AnalysisError("drop view functional.badview",
"Table does not exist: functional.badview");
// No error is thrown if the user specifies IF EXISTS
AnalyzesOk("drop database if exists db_does_not_exist");
// No error is thrown if the database does not exist
AnalyzesOk("drop table if exists db_does_not_exist.alltypes");
AnalyzesOk("drop view if exists db_does_not_exist.alltypes");
// No error is thrown if the database table does not exist and IF EXISTS
// is true
AnalyzesOk("drop table if exists functional.notbl");
AnalyzesOk("drop view if exists functional.notbl");
// Cannot drop a view with DROP TABLE.
AnalysisError("drop table functional.alltypes_view",
"DROP TABLE not allowed on a view: functional.alltypes_view");
// Cannot drop a table with DROP VIEW.
AnalysisError("drop view functional.alltypes",
"DROP VIEW not allowed on a table: functional.alltypes");
}
@Test
public void TestCreateDataSource() {
final String DATA_SOURCE_NAME = "TestDataSource1";
final DataSource DATA_SOURCE = new DataSource(DATA_SOURCE_NAME, "/foo.jar",
"foo.Bar", "V1");
catalog_.addDataSource(DATA_SOURCE);
AnalyzesOk("CREATE DATA SOURCE IF NOT EXISTS " + DATA_SOURCE_NAME +
" LOCATION '/foo.jar' CLASS 'foo.Bar' API_VERSION 'V1'");
AnalyzesOk("CREATE DATA SOURCE IF NOT EXISTS " + DATA_SOURCE_NAME.toLowerCase() +
" LOCATION '/foo.jar' CLASS 'foo.Bar' API_VERSION 'V1'");
AnalyzesOk("CREATE DATA SOURCE IF NOT EXISTS " + DATA_SOURCE_NAME +
" LOCATION 'hdfs://localhost:20500/foo.jar' CLASS 'foo.Bar' API_VERSION 'V1'");
AnalyzesOk("CREATE DATA SOURCE foo LOCATION '/' CLASS '' API_VERSION 'v1'");
AnalyzesOk("CREATE DATA SOURCE foo LOCATION '/foo.jar' CLASS 'com.bar.Foo' " +
"API_VERSION 'V1'");
AnalyzesOk("CREATE DATA SOURCE foo LOCATION '/FOO.jar' CLASS 'COM.BAR.FOO' " +
"API_VERSION 'v1'");
AnalyzesOk("CREATE DATA SOURCE foo LOCATION \"/foo.jar\" CLASS \"com.bar.Foo\" " +
"API_VERSION \"V1\"");
AnalyzesOk("CREATE DATA SOURCE foo LOCATION '/x/foo@hi_^!#.jar' " +
"CLASS 'com.bar.Foo' API_VERSION 'V1'");
AnalyzesOk("CREATE DATA SOURCE foo LOCATION 'hdfs://localhost:20500/a/b/foo.jar' " +
"CLASS 'com.bar.Foo' API_VERSION 'V1'");
AnalyzesOk("CREATE DATA SOURCE foo LOCATION 's3n://bucket/a/b/foo.jar' " +
"CLASS 'com.bar.Foo' API_VERSION 'V1'");
AnalysisError("CREATE DATA SOURCE foo LOCATION 'blah://localhost:20500/foo.jar' " +
"CLASS 'com.bar.Foo' API_VERSION 'V1'",
"No FileSystem for scheme: blah");
AnalysisError("CREATE DATA SOURCE " + DATA_SOURCE_NAME + " LOCATION '/foo.jar' " +
"CLASS 'foo.Bar' API_VERSION 'V1'",
"Data source already exists: " + DATA_SOURCE_NAME.toLowerCase());
AnalysisError("CREATE DATA SOURCE foo LOCATION '/foo.jar' " +
"CLASS 'foo.Bar' API_VERSION 'V2'", "Invalid API version: 'V2'");
}
@Test
public void TestCreateDb() throws AnalysisException {
AnalyzesOk("create database some_new_database");
AnalysisError("create database functional", "Database already exists: functional");
AnalyzesOk("create database if not exists functional");
// Invalid database name,
AnalysisError("create database `%^&`", "Invalid database name: %^&");
// Valid URIs.
AnalyzesOk("create database new_db location " +
"'/test-warehouse/new_db'");
AnalyzesOk("create database new_db location " +
"'hdfs://localhost:50200/test-warehouse/new_db'");
AnalyzesOk("create database new_db location " +
"'s3n://bucket/test-warehouse/new_db'");
// Invalid URI.
AnalysisError("create database new_db location " +
"'blah://bucket/test-warehouse/new_db'",
"No FileSystem for scheme: blah");
}
@Test
public void TestCreateTableLikeFile() throws AnalysisException {
// check that we analyze all of the CREATE TABLE options
AnalyzesOk("create table if not exists newtbl_DNE like parquet "
+ "'/test-warehouse/schemas/alltypestiny.parquet'");
AnalyzesOk("create table newtbl_DNE like parquet "
+ "'/test-warehouse/schemas/zipcode_incomes.parquet'");
AnalyzesOk("create table default.newtbl_DNE like parquet "
+ "'/test-warehouse/schemas/zipcode_incomes.parquet'");
AnalyzesOk("create table newtbl_DNE like parquet "
+ "'/test-warehouse/schemas/zipcode_incomes.parquet' STORED AS PARQUET");
AnalyzesOk("create external table newtbl_DNE like parquet "
+ "'/test-warehouse/schemas/zipcode_incomes.parquet' STORED AS PARQUET");
AnalyzesOk("create table if not exists functional.zipcode_incomes like parquet "
+ "'/test-warehouse/schemas/zipcode_incomes.parquet'");
AnalyzesOk("create table if not exists newtbl_DNE like parquet "
+ "'/test-warehouse/schemas/zipcode_incomes.parquet'");
AnalyzesOk("create table if not exists newtbl_DNE like parquet "
+ "'/test-warehouse/schemas/decimal.parquet'");
// check we error in the same situations as standard create table
AnalysisError("create table functional.zipcode_incomes like parquet "
+ "'/test-warehouse/schemas/zipcode_incomes.parquet'",
"Table already exists: functional.zipcode_incomes");
AnalysisError("create table database_DNE.newtbl_DNE like parquet "
+ "'/test-warehouse/schemas/zipcode_incomes.parquet'",
"Database does not exist: database_DNE");
// check invalid paths
AnalysisError("create table if not exists functional.zipcode_incomes like parquet "
+ "'/test-warehouse'",
"Cannot infer schema, path is not a file: hdfs://localhost:20500/test-warehouse");
AnalysisError("create table newtbl_DNE like parquet 'foobar'",
"URI path must be absolute: foobar");
AnalysisError("create table newtbl_DNE like parquet '/not/a/file/path'",
"Cannot infer schema, path is not a file: "
+ "hdfs://localhost:20500/not/a/file/path");
AnalysisError("create table if not exists functional.zipcode_incomes like parquet "
+ "'file:///tmp/foobar'",
"Cannot infer schema, path is not a file: file:/tmp/foobar");
// check valid paths with bad file contents
AnalysisError("create table database_DNE.newtbl_DNE like parquet "
+ "'/test-warehouse/zipcode_incomes_rc/000000_0'",
"File is not a parquet file: "
+ "hdfs://localhost:20500/test-warehouse/zipcode_incomes_rc/000000_0");
// this is a decimal file without annotations
AnalysisError("create table if not exists functional.zipcode_incomes like parquet "
+ "'/test-warehouse/schemas/malformed_decimal_tiny.parquet'",
"Unsupported parquet type FIXED_LEN_BYTE_ARRAY for field c1");
// this has structures, maps, and arrays
AnalysisError("create table table_DNE like parquet "
+ "'/test-warehouse/schemas/unsupported.parquet'",
"Unsupported parquet type for field strct");
AnalysisError("create table table_DNE like parquet "
+ "'/test-warehouse/schemas/map.parquet'",
"Unsupported parquet type for field mp");
AnalysisError("create table table_DNE like parquet "
+ "'/test-warehouse/schemas/array.parquet'",
"Unsupported parquet type for field lst");
AnalysisError("create table table_DNE like parquet "
+ "'/test-warehouse/schemas/struct.parquet'",
"Unsupported parquet type for field strct");
}
@Test
public void TestCreateTableAsSelect() throws AnalysisException {
// Constant select.
AnalyzesOk("create table newtbl as select 1+2, 'abc'");
// Select from partitioned and unpartitioned tables using different
// queries.
AnalyzesOk("create table newtbl stored as textfile " +
"as select * from functional.jointbl");
AnalyzesOk("create table newtbl stored as parquetfile " +
"as select * from functional.alltypes");
AnalyzesOk("create table newtbl stored as parquet " +
"as select * from functional.alltypes");
AnalyzesOk("create table newtbl as select int_col from functional.alltypes");
AnalyzesOk("create table functional.newtbl " +
"as select count(*) as CNT from functional.alltypes");
AnalyzesOk("create table functional.tbl as select a.* from functional.alltypes a " +
"join functional.alltypes b on (a.int_col=b.int_col) limit 1000");
// Caching operations
AnalyzesOk("create table functional.newtbl cached in 'testPool'" +
" as select count(*) as CNT from functional.alltypes");
AnalyzesOk("create table functional.newtbl uncached" +
" as select count(*) as CNT from functional.alltypes");
// Table already exists with and without IF NOT EXISTS
AnalysisError("create table functional.alltypes as select 1",
"Table already exists: functional.alltypes");
AnalyzesOk("create table if not exists functional.alltypes as select 1");
// Database does not exist
AnalysisError("create table db_does_not_exist.new_table as select 1",
"Database does not exist: db_does_not_exist");
// Analysis errors in the SELECT statement
AnalysisError("create table newtbl as select * from tbl_does_not_exist",
"Table does not exist: default.tbl_does_not_exist");
AnalysisError("create table newtbl as select 1 as c1, 2 as c1",
"Duplicate column name: c1");
// Unsupported file formats
AnalysisError("create table foo stored as sequencefile as select 1",
"CREATE TABLE AS SELECT does not support (SEQUENCEFILE) file format. " +
"Supported formats are: (PARQUET, TEXTFILE)");
AnalysisError("create table foo stored as RCFILE as select 1",
"CREATE TABLE AS SELECT does not support (RCFILE) file format. " +
"Supported formats are: (PARQUET, TEXTFILE)");
// CTAS with a WITH clause and inline view (IMPALA-1100)
AnalyzesOk("create table test_with as with with_1 as (select 1 as int_col from " +
"functional.alltypes as t1 right join (select 1 as int_col from " +
"functional.alltypestiny as t1) as t2 on t2.int_col = t1.int_col) " +
"select * from with_1 limit 10");
}
@Test
public void TestCreateTableLike() throws AnalysisException {
AnalyzesOk("create table if not exists functional.new_tbl like functional.alltypes");
AnalyzesOk("create table functional.like_view like functional.view_view");
AnalyzesOk(
"create table if not exists functional.alltypes like functional.alltypes");
AnalysisError("create table functional.alltypes like functional.alltypes",
"Table already exists: functional.alltypes");
AnalysisError("create table functional.new_table like functional.tbl_does_not_exist",
"Table does not exist: functional.tbl_does_not_exist");
AnalysisError("create table functional.new_table like db_does_not_exist.alltypes",
"Database does not exist: db_does_not_exist");
// Invalid database name.
AnalysisError("create table `???`.new_table like functional.alltypes",
"Invalid database name: ???");
// Invalid table/view name.
AnalysisError("create table functional.`^&*` like functional.alltypes",
"Invalid table/view name: ^&*");
// Invalid source database/table name reports non-existence instead of invalidity.
AnalysisError("create table functional.foo like `???`.alltypes",
"Database does not exist: ???");
AnalysisError("create table functional.foo like functional.`%^&`",
"Table does not exist: functional.%^&");
// Valid URI values.
AnalyzesOk("create table tbl like functional.alltypes location " +
"'/test-warehouse/new_table'");
AnalyzesOk("create table tbl like functional.alltypes location " +
"'hdfs://localhost:20500/test-warehouse/new_table'");
// 'file' scheme does not take an authority, so file:/// is equivalent to file://
// and file:/.
AnalyzesOk("create table tbl like functional.alltypes location " +
"'file:///test-warehouse/new_table'");
AnalyzesOk("create table tbl like functional.alltypes location " +
"'file://test-warehouse/new_table'");
AnalyzesOk("create table tbl like functional.alltypes location " +
"'file:/test-warehouse/new_table'");
AnalyzesOk("create table tbl like functional.alltypes location " +
"'s3n://bucket/test-warehouse/new_table'");
// Invalid URI values.
AnalysisError("create table tbl like functional.alltypes location " +
"'foofs://test-warehouse/new_table'",
"No FileSystem for scheme: foofs");
AnalysisError("create table functional.baz like functional.alltypes location ' '",
"URI path cannot be empty.");
}
@Test
public void TestCreateTable() throws AnalysisException {
AnalyzesOk("create table functional.new_table (i int)");
AnalyzesOk("create table if not exists functional.alltypes (i int)");
AnalysisError("create table functional.alltypes",
"Table already exists: functional.alltypes");
AnalysisError("create table functional.alltypes (i int)",
"Table already exists: functional.alltypes");
AnalyzesOk("create table functional.new_table (i int) row format delimited fields " +
"terminated by '|'");
AnalyzesOk("create table new_table (i int) PARTITIONED BY (d decimal)");
AnalyzesOk("create table new_table (i int) PARTITIONED BY (d decimal(3,1))");
AnalyzesOk("create table new_table(d1 decimal, d2 decimal(10), d3 decimal(5, 2))");
AnalysisError("create table new_table (i int) PARTITIONED BY (d decimal(40,1))",
"Decimal precision must be <= 38.");
AnalyzesOk("create table new_table(s1 varchar(1), s2 varchar(32672))");
AnalysisError("create table new_table(s1 varchar(0))",
"Varchar size must be > 0. Size is too small: 0.");
AnalysisError("create table new_table(s1 varchar(65356))",
"Varchar size must be <= 65355. Size is too large: 65356.");
AnalysisError("create table new_table(s1 char(0))",
"Char size must be > 0. Size is too small: 0.");
AnalysisError("create table new_table(s1 Char(256))",
"Char size must be <= 255. Size is too large: 256.");
AnalyzesOk("create table new_table (i int) PARTITIONED BY (s varchar(3))");
AnalyzesOk("create table functional.new_table (c char(250))");
AnalyzesOk("create table new_table (i int) PARTITIONED BY (c char(3))");
// Supported file formats. Exclude Avro since it is tested separately.
String [] fileFormats =
{"TEXTFILE", "SEQUENCEFILE", "PARQUET", "PARQUETFILE", "RCFILE"};
for (String format: fileFormats) {
AnalyzesOk(String.format("create table new_table (i int) " +
"partitioned by (d decimal) comment 'c' stored as %s", format));
// No column definitions.
AnalysisError(String.format("create table new_table " +
"partitioned by (d decimal) comment 'c' stored as %s", format),
"Table requires at least 1 column");
}
// Note: Backslashes need to be escaped twice - once for Java and once for Impala.
// For example, if this were a real query the value '\' would be stored in the
// metastore for the ESCAPED BY field.
AnalyzesOk("create table functional.new_table (i int) row format delimited fields " +
"terminated by '\\t' escaped by '\\\\' lines terminated by '\\n'");
AnalyzesOk("create table functional.new_table (i int) row format delimited fields " +
"terminated by '\\001' escaped by '\\002' lines terminated by '\\n'");
AnalyzesOk("create table functional.new_table (i int) row format delimited fields " +
"terminated by '-2' escaped by '-3' lines terminated by '\\n'");
AnalyzesOk("create table functional.new_table (i int) row format delimited fields " +
"terminated by '-128' escaped by '127' lines terminated by '40'");
AnalysisError("create table functional.new_table (i int) row format delimited " +
"fields terminated by '-2' escaped by '128' lines terminated by '\\n'",
"ESCAPED BY values and LINE/FIELD terminators must be specified as a single " +
"character or as a decimal value in the range [-128:127]: 128");
AnalysisError("create table functional.new_table (i int) row format delimited " +
"fields terminated by '-2' escaped by '127' lines terminated by '255'",
"ESCAPED BY values and LINE/FIELD terminators must be specified as a single " +
"character or as a decimal value in the range [-128:127]: 255");
AnalysisError("create table functional.new_table (i int) row format delimited " +
"fields terminated by '-129' escaped by '127' lines terminated by '\\n'",
"ESCAPED BY values and LINE/FIELD terminators must be specified as a single " +
"character or as a decimal value in the range [-128:127]: -129");
AnalysisError("create table functional.new_table (i int) row format delimited " +
"fields terminated by '||' escaped by '\\\\' lines terminated by '\\n'",
"ESCAPED BY values and LINE/FIELD terminators must be specified as a single " +
"character or as a decimal value in the range [-128:127]: ||");
AnalysisError("create table db_does_not_exist.new_table (i int)",
"Database does not exist: db_does_not_exist");
AnalysisError("create table new_table (i int, I string)",
"Duplicate column name: I");
AnalysisError("create table new_table (c1 double, col2 int, c1 double, c4 string)",
"Duplicate column name: c1");
AnalysisError("create table new_table (i int, s string) PARTITIONED BY (i int)",
"Duplicate column name: i");
AnalysisError("create table new_table (i int) PARTITIONED BY (C int, c2 int, c int)",
"Duplicate column name: c");
// Unsupported partition-column types.
AnalysisError("create table new_table (i int) PARTITIONED BY (t timestamp)",
"Type 'TIMESTAMP' is not supported as partition-column type in column: t");
AnalysisError("create table new_table (i int) PARTITIONED BY (d date)",
"Type 'DATE' is not supported as partition-column type in column: d");
AnalysisError("create table new_table (i int) PARTITIONED BY (d datetime)",
"Type 'DATETIME' is not supported as partition-column type in column: d");
// Caching ops
AnalyzesOk("create table cached_tbl(i int) partitioned by(j int) " +
"cached in 'testPool'");
AnalyzesOk("create table cached_tbl(i int) partitioned by(j int) uncached");
AnalyzesOk("create table cached_tbl(i int) partitioned by(j int) " +
"location '/test-warehouse/' cached in 'testPool'");
AnalyzesOk("create table cached_tbl(i int) partitioned by(j int) " +
"location '/test-warehouse/' uncached");
// Invalid database name.
AnalysisError("create table `???`.new_table (x int) PARTITIONED BY (y int)",
"Invalid database name: ???");
// Invalid table/view name.
AnalysisError("create table functional.`^&*` (x int) PARTITIONED BY (y int)",
"Invalid table/view name: ^&*");
// Invalid column names.
AnalysisError("create table new_table (`???` int) PARTITIONED BY (i int)",
"Invalid column/field name: ???");
AnalysisError("create table new_table (i int) PARTITIONED BY (`^&*` int)",
"Invalid column/field name: ^&*");
// Valid URI values.
AnalyzesOk("create table tbl (i int) location '/test-warehouse/new_table'");
AnalyzesOk("create table tbl (i int) location " +
"'hdfs://localhost:20500/test-warehouse/new_table'");
AnalyzesOk("create table tbl (i int) location " +
"'file:///test-warehouse/new_table'");
AnalyzesOk("create table tbl (i int) location " +
"'s3n://bucket/test-warehouse/new_table'");
AnalyzesOk("ALTER TABLE functional_seq_snap.alltypes SET LOCATION " +
"'file://test-warehouse/new_table'");
// Invalid URI values.
AnalysisError("create table functional.foo (x int) location " +
"'foofs://test-warehouse/new_table'",
"No FileSystem for scheme: foofs");
AnalysisError("create table functional.foo (x int) location " +
"' '", "URI path cannot be empty.");
AnalysisError("ALTER TABLE functional_seq_snap.alltypes SET LOCATION " +
"'foofs://test-warehouse/new_table'",
"No FileSystem for scheme: foofs");
AnalysisError("ALTER TABLE functional_seq_snap.alltypes SET LOCATION " +
"' '", "URI path cannot be empty.");
// Create table PRODUCED BY DATA SOURCE
final String DATA_SOURCE_NAME = "TestDataSource1";
catalog_.addDataSource(new DataSource(DATA_SOURCE_NAME, "/foo.jar",
"foo.Bar", "V1"));
AnalyzesOk("CREATE TABLE DataSrcTable1 (x int) PRODUCED BY DATA SOURCE " +
DATA_SOURCE_NAME);
AnalyzesOk("CREATE TABLE DataSrcTable1 (x int) PRODUCED BY DATA SOURCE " +
DATA_SOURCE_NAME.toLowerCase());
AnalyzesOk("CREATE TABLE DataSrcTable1 (x int) PRODUCED BY DATA SOURCE " +
DATA_SOURCE_NAME + "(\"\")");
AnalyzesOk("CREATE TABLE DataSrcTable1 (a tinyint, b smallint, c int, d bigint, " +
"e float, f double, g boolean, h string) PRODUCED BY DATA SOURCE " +
DATA_SOURCE_NAME);
AnalysisError("CREATE TABLE DataSrcTable1 (x int) PRODUCED BY DATA SOURCE " +
"not_a_data_src(\"\")", "Data source does not exist");
for (Type t: Type.getSupportedTypes()) {
PrimitiveType type = t.getPrimitiveType();
if (DataSourceTable.isSupportedPrimitiveType(type) || t.isNull()) continue;
String typeSpec = type.name();
if (type == PrimitiveType.CHAR || type == PrimitiveType.DECIMAL ||
type == PrimitiveType.VARCHAR) {
typeSpec += "(10)";
}
AnalysisError("CREATE TABLE DataSrcTable1 (x " + typeSpec + ") PRODUCED " +
"BY DATA SOURCE " + DATA_SOURCE_NAME,
"Tables produced by an external data source do not support the column type: " +
type.name());
}
}
@Test
public void TestCreateAvroTest() {
String alltypesSchemaLoc =
"hdfs:///test-warehouse/avro_schemas/functional/alltypes.json";
// Analysis of Avro schemas. Column definitions match the Avro schema exactly.
// Note: Avro does not have a tinyint and smallint type.
AnalyzesOk(String.format(
"create table foo_avro (id int, bool_col boolean, tinyint_col int, " +
"smallint_col int, int_col int, bigint_col bigint, float_col float," +
"double_col double, date_string_col string, string_col string, " +
"timestamp_col timestamp) with serdeproperties ('avro.schema.url'='%s')" +
"stored as avro", alltypesSchemaLoc));
AnalyzesOk(String.format(
"create table foo_avro (id int, bool_col boolean, tinyint_col int, " +
"smallint_col int, int_col int, bigint_col bigint, float_col float," +
"double_col double, date_string_col string, string_col string, " +
"timestamp_col timestamp) stored as avro tblproperties ('avro.schema.url'='%s')",
alltypesSchemaLoc));
AnalyzesOk("create table foo_avro (string1 string) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\": \"string1\", \"type\": \"string\"}]}')");
// No column definitions.
AnalyzesOk(String.format(
"create table foo_avro with serdeproperties ('avro.schema.url'='%s')" +
"stored as avro", alltypesSchemaLoc));
AnalyzesOk(String.format(
"create table foo_avro stored as avro tblproperties ('avro.schema.url'='%s')",
alltypesSchemaLoc));
AnalyzesOk("create table foo_avro stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\": \"string1\", \"type\": \"string\"}]}')");
// Analysis of Avro schemas. Column definitions do not match Avro schema.
AnalyzesOk(String.format(
"create table foo_avro (id int) with serdeproperties ('avro.schema.url'='%s')" +
"stored as avro", alltypesSchemaLoc),
"Ignoring column definitions in favor of Avro schema.\n" +
"The Avro schema has 11 column(s) but 1 column definition(s) were given.");
AnalyzesOk(String.format(
"create table foo_avro (bool_col boolean, string_col string) " +
"stored as avro tblproperties ('avro.schema.url'='%s')",
alltypesSchemaLoc),
"Ignoring column definitions in favor of Avro schema.\n" +
"The Avro schema has 11 column(s) but 2 column definition(s) were given.");
AnalyzesOk("create table foo_avro (string1 string) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\": \"string1\", \"type\": \"string\"}," +
"{\"name\": \"string2\", \"type\": \"string\"}]}')",
"Ignoring column definitions in favor of Avro schema.\n" +
"The Avro schema has 2 column(s) but 1 column definition(s) were given.");
// Mismatched name.
AnalyzesOk(String.format(
"create table foo_avro (id int, bool_col boolean, tinyint_col int, " +
"smallint_col int, bad_int_col int, bigint_col bigint, float_col float," +
"double_col double, date_string_col string, string_col string, " +
"timestamp_col timestamp) with serdeproperties ('avro.schema.url'='%s')" +
"stored as avro", alltypesSchemaLoc),
"Ignoring column definitions in favor of Avro schema due to a mismatched " +
"column name at position 5.\n" +
"Column definition: bad_int_col INT\n" +
"Avro schema column: int_col INT");
// Mismatched type.
AnalyzesOk(String.format(
"create table foo_avro (id int, bool_col boolean, tinyint_col int, " +
"smallint_col int, int_col int, bigint_col bigint, float_col float," +
"double_col bigint, date_string_col string, string_col string, " +
"timestamp_col timestamp) stored as avro tblproperties ('avro.schema.url'='%s')",
alltypesSchemaLoc),
"Ignoring column definitions in favor of Avro schema due to a mismatched " +
"column type at position 8.\n" +
"Column definition: double_col BIGINT\n" +
"Avro schema column: double_col DOUBLE");
// No Avro schema specified for Avro format table.
AnalysisError("create table foo_avro (i int) stored as avro",
"No Avro schema provided in SERDEPROPERTIES or TBLPROPERTIES for table: " +
"default.foo_avro");
AnalysisError("create table foo_avro (i int) stored as avro tblproperties ('a'='b')",
"No Avro schema provided in SERDEPROPERTIES or TBLPROPERTIES for table: " +
"default.foo_avro");
AnalysisError("create table foo_avro stored as avro tblproperties ('a'='b')",
"No Avro schema provided in SERDEPROPERTIES or TBLPROPERTIES for table: "+
"default.foo_avro");
// Invalid schema URL
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.url'='schema.avsc')",
"Invalid avro.schema.url: schema.avsc. Path does not exist.");
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.url'='hdfs://invalid*host/schema.avsc')",
"Invalid avro.schema.url: hdfs://invalid*host/schema.avsc. " +
"Incomplete HDFS URI, no host: hdfs://invalid*host/schema.avsc");
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.url'='foo://bar/schema.avsc')",
"Invalid avro.schema.url: foo://bar/schema.avsc. No FileSystem for scheme: foo");
// Decimal parsing
AnalyzesOk("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\":\"value\",\"type\":{\"type\":\"bytes\", " +
"\"logicalType\":\"decimal\",\"precision\":5,\"scale\":2}}]}')");
// Scale not required (defaults to zero).
AnalyzesOk("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\":\"value\",\"type\":{\"type\":\"bytes\", " +
"\"logicalType\":\"decimal\",\"precision\":5}}]}')");
// Precision is always required
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\":\"value\",\"type\":{\"type\":\"bytes\", " +
"\"logicalType\":\"decimal\",\"scale\":5}}]}')",
"Error parsing Avro schema for table 'default.foo_avro': " +
"No 'precision' property specified for 'decimal' logicalType");
// Precision/Scale must be positive integers
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\":\"value\",\"type\":{\"type\":\"bytes\", " +
"\"logicalType\":\"decimal\",\"scale\":5, \"precision\":-20}}]}')",
"Error parsing Avro schema for table 'default.foo_avro': " +
"Invalid decimal 'precision' property value: -20");
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\":\"value\",\"type\":{\"type\":\"bytes\", " +
"\"logicalType\":\"decimal\",\"scale\":-1, \"precision\":20}}]}')",
"Error parsing Avro schema for table 'default.foo_avro': " +
"Invalid decimal 'scale' property value: -1");
// Invalid schema (bad JSON - missing opening bracket for "field" array)
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": {\"name\": \"string1\", \"type\": \"string\"}]}')",
"Error parsing Avro schema for table 'default.foo_avro': " +
"org.codehaus.jackson.JsonParseException: Unexpected close marker ']': "+
"expected '}'");
// Unsupported types
// Array
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\": \"string1\", \"type\": \"string\"}," +
"{\"name\": \"list1\", \"type\": {\"type\":\"array\", \"items\": \"int\"}}]}')",
"Error parsing Avro schema for table 'default.foo_avro': " +
"Unsupported type 'array' of column 'list1'");
// Map
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\": \"string1\", \"type\": \"string\"}," +
"{\"name\": \"map1\", \"type\": {\"type\":\"map\", \"values\": \"int\"}}]}')",
"Error parsing Avro schema for table 'default.foo_avro': " +
"Unsupported type 'map' of column 'map1'");
// Union
AnalysisError("create table foo_avro (i int) stored as avro tblproperties " +
"('avro.schema.literal'='{\"name\": \"my_record\", \"type\": \"record\", " +
"\"fields\": [{\"name\": \"string1\", \"type\": \"string\"}," +
"{\"name\": \"union1\", \"type\": [\"float\", \"boolean\"]}]}')",
"Error parsing Avro schema for table 'default.foo_avro': " +
"Unsupported type 'union' of column 'union1'");
// TODO: Add COLLECTION ITEMS TERMINATED BY and MAP KEYS TERMINATED BY clauses.
// Test struct complex type.
AnalyzesOk("create table functional.new_table (" +
"a struct<f1: int, f2: string, f3: timestamp, f4: boolean>, " +
"b struct<f1: struct<f11: int>, f2: struct<f21: struct<f22: string>>>, " +
"c struct<f1: map<int, string>, f2: array<bigint>>," +
"d struct<f1: struct<f11: map<int, string>, f12: array<bigint>>>)");
// Test array complex type.
AnalyzesOk("create table functional.new_table (" +
"a array<int>, b array<timestamp>, c array<string>, d array<boolean>, " +
"e array<array<int>>, f array<array<array<string>>>, " +
"g array<struct<f1: int, f2: string>>, " +
"h array<map<string,int>>)");
// Test map complex type.
AnalyzesOk("create table functional.new_table (" +
"a map<string, int>, b map<timestamp, boolean>, c map<bigint, float>, " +
"d array<array<int>>, e array<array<array<string>>>, " +
"f array<struct<f1: int, f2: string>>," +
"g array<map<string,int>>)");
// Cannot partition by a complex column.
AnalysisError("create table functional.new_table (i int) " +
"partitioned by (x array<int>)",
"Type 'ARRAY<INT>' is not supported as partition-column type in column: x");
AnalysisError("create table functional.new_table (i int) " +
"partitioned by (x map<int,int>)",
"Type 'MAP<INT,INT>' is not supported as partition-column type in column: x");
AnalysisError("create table functional.new_table (i int) " +
"partitioned by (x struct<f1:int>)",
"Type 'STRUCT<f1:INT>' is not supported as partition-column type in column: x");
}
@Test
public void TestCreateView() throws AnalysisException {
AnalyzesOk(
"create view foo_new as select int_col, string_col from functional.alltypes");
AnalyzesOk("create view functional.foo as select * from functional.alltypes");
AnalyzesOk("create view if not exists foo as select * from functional.alltypes");
AnalyzesOk("create view foo (a, b) as select int_col, string_col " +
"from functional.alltypes");
AnalyzesOk("create view functional.foo (a, b) as select int_col x, double_col y " +
"from functional.alltypes");
// View can have complex-typed columns.
AnalyzesOk("create view functional.foo (a, b, c) as " +
"select int_array_col, int_map_col, int_struct_col " +
"from functional.allcomplextypes");
// Creating a view on a view is ok (alltypes_view is a view on alltypes).
AnalyzesOk("create view foo as select * from functional.alltypes_view");
AnalyzesOk("create view foo (aaa, bbb) as select * from functional.complex_view");
// Create a view resulting in Hive-style auto-generated column names.
AnalyzesOk("create view foo as select trim('abc'), 17 * 7");
// Creating a view on an HBase table is ok.
AnalyzesOk("create view foo as select * from functional_hbase.alltypesagg");
// Complex view definition with joins and aggregates.
AnalyzesOk("create view foo (cnt) as " +
"select count(distinct x.int_col) from functional.alltypessmall x " +
"inner join functional.alltypessmall y on (x.id = y.id) group by x.bigint_col");
// Test different query-statement types as view definition.
AnalyzesOk("create view foo (a, b) as values(1, 'a'), (2, 'b')");
AnalyzesOk("create view foo (a, b) as select 1, 'a' union all select 2, 'b'");
// Mismatching number of columns in column definition and view-definition statement.
AnalysisError("create view foo (a) as select int_col, string_col " +
"from functional.alltypes",
"Column-definition list has fewer columns (1) than the " +
"view-definition query statement returns (2).");
AnalysisError("create view foo (a, b, c) as select int_col " +
"from functional.alltypes",
"Column-definition list has more columns (3) than the " +
"view-definition query statement returns (1).");
// Duplicate columns in the view-definition statement.
AnalysisError("create view foo as select * from functional.alltypessmall a " +
"inner join functional.alltypessmall b on a.id = b.id",
"Duplicate column name: id");
// Duplicate columns in the column definition.
AnalysisError("create view foo (a, b, a) as select int_col, int_col, int_col " +
"from functional.alltypes",
"Duplicate column name: a");
// Invalid database/view/column names.
AnalysisError("create view `???`.new_view as select 1, 2, 3",
"Invalid database name: ???");
AnalysisError("create view `^%&` as select 1, 2, 3",
"Invalid table/view name: ^%&");
AnalysisError("create view foo as select 1 as `???`",
"Invalid column/field name: ???");
AnalysisError("create view foo(`%^&`) as select 1",
"Invalid column/field name: %^&");
// Table/view already exists.
AnalysisError("create view functional.alltypes as " +
"select * from functional.alltypessmall ",
"Table already exists: functional.alltypes");
// Target database does not exist.
AnalysisError("create view wrongdb.test as " +
"select * from functional.alltypessmall ",
"Database does not exist: wrongdb");
// Source database does not exist,
AnalysisError("create view foo as " +
"select * from wrongdb.alltypessmall ",
"Database does not exist: wrongdb");
// Source table does not exist,
AnalysisError("create view foo as " +
"select * from wrongdb.alltypessmall ",
"Database does not exist: wrongdb");
// Analysis error in view-definition statement.
AnalysisError("create view foo as " +
"select int_col from functional.alltypessmall union all " +
"select string_col from functional.alltypes",
"Incompatible return types 'INT' and 'STRING' of exprs " +
"'int_col' and 'string_col'.");
// View with a subquery
AnalyzesOk("create view test_view_with_subquery as " +
"select * from functional.alltypestiny t where exists " +
"(select * from functional.alltypessmall s where s.id = t.id)");
}
@Test
public void TestUdf() throws AnalysisException {
final String symbol =
"'_Z8IdentityPN10impala_udf15FunctionContextERKNS_10BooleanValE'";
final String udfSuffix = " LOCATION '/test-warehouse/libTestUdfs.so' " +
"SYMBOL=" + symbol;
final String udfSuffixIr = " LOCATION '/test-warehouse/test-udfs.ll' " +
"SYMBOL=" + symbol;
final String hdfsPath = "hdfs://localhost:20500/test-warehouse/libTestUdfs.so";
AnalyzesOk("create function foo() RETURNS int" + udfSuffix);
AnalyzesOk("create function foo(int, int, string) RETURNS int" + udfSuffix);
// Try some fully qualified function names
AnalyzesOk("create function functional.B() RETURNS int" + udfSuffix);
AnalyzesOk("create function functional.B1() RETURNS int" + udfSuffix);
AnalyzesOk("create function functional.`B1C`() RETURNS int" + udfSuffix);
// Name with underscore
AnalyzesOk("create function A_B() RETURNS int" + udfSuffix);
// Locations for all the udfs types.
AnalyzesOk("create function foo() RETURNS int LOCATION " +
"'/test-warehouse/libTestUdfs.so' " +
"SYMBOL='_Z8IdentityPN10impala_udf15FunctionContextERKNS_10BooleanValE'");
AnalysisError("create function foo() RETURNS int LOCATION " +
"'/test-warehouse/libTestUdfs.ll' " +
"SYMBOL='_Z8IdentityPN10impala_udf15FunctionContextERKNS_10BooleanValE'",
"Could not load binary: /test-warehouse/libTestUdfs.ll");
AnalyzesOk("create function foo() RETURNS int LOCATION " +
"'/test-warehouse/test-udfs.ll' " +
"SYMBOL='_Z8IdentityPN10impala_udf15FunctionContextERKNS_10BooleanValE'");
AnalyzesOk("create function foo(int) RETURNS int LOCATION " +
"'/test-warehouse/test-udfs.ll' SYMBOL='Identity'");
AnalyzesOk("create function foo() RETURNS int LOCATION " +
"'/test-warehouse/libTestUdfs.SO' " +
"SYMBOL='_Z8IdentityPN10impala_udf15FunctionContextERKNS_10BooleanValE'");
AnalyzesOk("create function foo() RETURNS int LOCATION " +
"'/test-warehouse/hive-exec.jar' SYMBOL='a'");
// Test hive UDFs for unsupported types
AnalysisError("create function foo() RETURNS timestamp LOCATION '/a.jar'",
"Hive UDFs that use TIMESTAMP are not yet supported.");
AnalysisError("create function foo(timestamp) RETURNS int LOCATION '/a.jar'",
"Hive UDFs that use TIMESTAMP are not yet supported.");
AnalysisError("create function foo() RETURNS decimal LOCATION '/a.jar'",
"Hive UDFs that use DECIMAL are not yet supported.");
AnalysisError("create function foo(Decimal) RETURNS int LOCATION '/a.jar'",
"Hive UDFs that use DECIMAL are not yet supported.");
AnalysisError("create function foo(char(5)) RETURNS int LOCATION '/a.jar'",
"UDFs that use CHAR are not yet supported.");
AnalysisError("create function foo(varchar(5)) RETURNS int LOCATION '/a.jar'",
"UDFs that use VARCHAR are not yet supported.");
AnalysisError("create function foo() RETURNS CHAR(5) LOCATION '/a.jar'",
"UDFs that use CHAR are not yet supported.");
AnalysisError("create function foo() RETURNS VARCHAR(5) LOCATION '/a.jar'",
"UDFs that use VARCHAR are not yet supported.");
AnalysisError("create function foo() RETURNS CHAR(5)" + udfSuffix,
"UDFs that use CHAR are not yet supported.");
AnalysisError("create function foo() RETURNS VARCHAR(5)" + udfSuffix,
"UDFs that use VARCHAR are not yet supported.");
AnalysisError("create function foo(CHAR(5)) RETURNS int" + udfSuffix,
"UDFs that use CHAR are not yet supported.");
AnalysisError("create function foo(VARCHAR(5)) RETURNS int" + udfSuffix,
"UDFs that use VARCHAR are not yet supported.");
AnalyzesOk("create function foo() RETURNS decimal" + udfSuffix);
AnalyzesOk("create function foo() RETURNS decimal(38,10)" + udfSuffix);
AnalyzesOk("create function foo(Decimal, decimal(10, 2)) RETURNS int" + udfSuffix);
AnalysisError("create function foo() RETURNS decimal(100)" + udfSuffix,
"Decimal precision must be <= 38.");
AnalysisError("create function foo(Decimal(2, 3)) RETURNS int" + udfSuffix,
"Decimal scale (3) must be <= precision (2).");
// Varargs
AnalyzesOk("create function foo(INT...) RETURNS int" + udfSuffix);
// Prepare/Close functions
AnalyzesOk("create function foo() returns int" + udfSuffix
+ " prepare_fn='ValidateOpenPrepare'" + " close_fn='ValidateOpenClose'");
AnalyzesOk("create function foo() returns int" + udfSuffixIr
+ " prepare_fn='ValidateOpenPrepare'" + " close_fn='ValidateOpenClose'");
AnalyzesOk("create function foo() returns int" + udfSuffixIr
+ " prepare_fn='_Z19ValidateOpenPreparePN10impala_udf15FunctionContextENS0_18FunctionStateScopeE'"
+ " close_fn='_Z17ValidateOpenClosePN10impala_udf15FunctionContextENS0_18FunctionStateScopeE'");
AnalysisError("create function foo() returns int" + udfSuffix + " prepare_fn=''",
"Could not find symbol ''");
AnalysisError("create function foo() returns int" + udfSuffix + " close_fn=''",
"Could not find symbol ''");
AnalysisError("create function foo() returns int" + udfSuffix +
" prepare_fn='FakePrepare'",
"Could not find function FakePrepare(impala_udf::FunctionContext*, "+
"impala_udf::FunctionContext::FunctionStateScope) in: ");
// Try to create a function with the same name as a builtin
AnalysisError("create function sin(double) RETURNS double" + udfSuffix,
"Function cannot have the same name as a builtin: sin");
AnalysisError("create function sin() RETURNS double" + udfSuffix,
"Function cannot have the same name as a builtin: sin");
// Try to create with a bad location
AnalysisError("create function foo() RETURNS int LOCATION 'bad-location' SYMBOL='c'",
"URI path must be absolute: bad-location");
AnalysisError("create function foo() RETURNS int LOCATION " +
"'blah://localhost:50200/bad-location' SYMBOL='c'",
"No FileSystem for scheme: blah");
AnalysisError("create function foo() RETURNS int LOCATION " +
"'file:///foo.jar' SYMBOL='c'",
"Could not load binary: file:///foo.jar");
// Try creating udfs with unknown extensions
AnalysisError("create function foo() RETURNS int LOCATION '/binary' SYMBOL='a'",
"Unknown binary type: '/binary'. Binary must end in .jar, .so or .ll");
AnalysisError("create function foo() RETURNS int LOCATION '/binary.a' SYMBOL='a'",
"Unknown binary type: '/binary.a'. Binary must end in .jar, .so or .ll");
AnalysisError("create function foo() RETURNS int LOCATION '/binary.so.' SYMBOL='a'",
"Unknown binary type: '/binary.so.'. Binary must end in .jar, .so or .ll");
// Try with missing symbol
AnalysisError("create function foo() RETURNS int LOCATION '/binary.so'",
"Argument 'SYMBOL' must be set.");
// Try with symbols missing in binary and symbols
AnalysisError("create function foo() RETURNS int LOCATION '/blah.so' " +
"SYMBOL='ab'", "Could not load binary: /blah.so");
AnalysisError("create function foo() RETURNS int LOCATION '/binary.JAR' SYMBOL='a'",
"Could not load binary: /binary.JAR");
AnalysisError("create function foo() RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " +
"SYMBOL='b'", "Could not find function b() in: " + hdfsPath);
AnalysisError("create function foo() RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " +
"SYMBOL=''", "Could not find symbol ''");
AnalysisError("create function foo() RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " +
"SYMBOL='_ZAB'",
"Could not find symbol '_ZAB' in: " + hdfsPath);
// Infer the fully mangled symbol from the signature
AnalyzesOk("create function foo() RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='NoArgs'");
// We can't get the return type so any of those will match
AnalyzesOk("create function foo() RETURNS double " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='NoArgs'");
// The part the user specifies is case sensitive
AnalysisError("create function foo() RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='noArgs'",
"Could not find function noArgs() in: " + hdfsPath);
// Types no longer match
AnalysisError("create function foo(int) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='NoArgs'",
"Could not find function NoArgs(INT) in: " + hdfsPath);
// Check we can match identity for all types
AnalyzesOk("create function identity(boolean) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='Identity'");
AnalyzesOk("create function identity(tinyint) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='Identity'");
AnalyzesOk("create function identity(smallint) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='Identity'");
AnalyzesOk("create function identity(int) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='Identity'");
AnalyzesOk("create function identity(bigint) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='Identity'");
AnalyzesOk("create function identity(float) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='Identity'");
AnalyzesOk("create function identity(double) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='Identity'");
AnalyzesOk("create function identity(string) RETURNS int " +
"LOCATION '/test-warehouse/libTestUdfs.so' " + "SYMBOL='Identity'");
AnalyzesOk("create function all_types_fn(string, boolean, tinyint, " +
"smallint, int, bigint, float, double, decimal) returns int " +
"location '/test-warehouse/libTestUdfs.so' symbol='AllTypes'");
// Try creating functions with illegal function names.
AnalysisError("create function 123A() RETURNS int" + udfSuffix,
"Function cannot start with a digit: 123a");
AnalysisError("create function A.`1A`() RETURNS int" + udfSuffix,
"Function cannot start with a digit: 1a");
AnalysisError("create function A.`ABC-D`() RETURNS int" + udfSuffix,
"Function names must be all alphanumeric or underscore. Invalid name: abc-d");
AnalysisError("create function baddb.f() RETURNS int" + udfSuffix,
"Database does not exist: baddb");
// Try creating functions with unsupported return/arg types.
AnalysisError("create function f() RETURNS array<int>" + udfSuffix,
"Type 'ARRAY<INT>' is not supported in UDFs/UDAs.");
AnalysisError("create function f(map<string,int>) RETURNS int" + udfSuffix,
"Type 'MAP<STRING,INT>' is not supported in UDFs/UDAs.");
AnalysisError("create function f() RETURNS struct<f:int>" + udfSuffix,
"Type 'STRUCT<f:INT>' is not supported in UDFs/UDAs.");
// Try dropping functions.
AnalyzesOk("drop function if exists foo()");
AnalysisError("drop function foo()", "Function does not exist: foo()");
AnalyzesOk("drop function if exists a.foo()");
AnalysisError("drop function a.foo()", "Database does not exist: a");
AnalyzesOk("drop function if exists foo()");
AnalyzesOk("drop function if exists foo(int...)");
AnalyzesOk("drop function if exists foo(double, int...)");
// Add functions default.TestFn(), default.TestFn(double), default.TestFn(String...),
addTestFunction("TestFn", new ArrayList<ScalarType>(), false);
addTestFunction("TestFn", Lists.newArrayList(Type.DOUBLE), false);
addTestFunction("TestFn", Lists.newArrayList(Type.STRING), true);
AnalysisError("create function TestFn() RETURNS INT " + udfSuffix,
"Function already exists: testfn()");
AnalysisError("create function TestFn(double) RETURNS INT " + udfSuffix,
"Function already exists: testfn(DOUBLE)");
// Fn(Double) and Fn(Double...) should be a conflict.
AnalysisError("create function TestFn(double...) RETURNS INT" + udfSuffix,
"Function already exists: testfn(DOUBLE)");
AnalysisError("create function TestFn(double) RETURNS INT" + udfSuffix,
"Function already exists: testfn(DOUBLE)");
// Add default.TestFn(int, int)
addTestFunction("TestFn", Lists.newArrayList(Type.INT, Type.INT), false);
AnalyzesOk("drop function TestFn(int, int)");
AnalysisError("drop function TestFn(int, int, int)",
"Function does not exist: testfn(INT, INT, INT)");
// Fn(String...) was already added.
AnalysisError("create function TestFn(String) RETURNS INT" + udfSuffix,
"Function already exists: testfn(STRING...)");
AnalysisError("create function TestFn(String...) RETURNS INT" + udfSuffix,
"Function already exists: testfn(STRING...)");
AnalysisError("create function TestFn(String, String) RETURNS INT" + udfSuffix,
"Function already exists: testfn(STRING...)");
AnalyzesOk("create function TestFn(String, String, Int) RETURNS INT" + udfSuffix);
// Check function overloading.
AnalyzesOk("create function TestFn(int) RETURNS INT " + udfSuffix);
// Create a function with the same signature in a different db
AnalyzesOk("create function functional.TestFn() RETURNS INT " + udfSuffix);
AnalyzesOk("drop function TestFn()");
AnalyzesOk("drop function TestFn(double)");
AnalyzesOk("drop function TestFn(string...)");
AnalysisError("drop function TestFn(double...)",
"Function does not exist: testfn(DOUBLE...)");
AnalysisError("drop function TestFn(int)", "Function does not exist: testfn(INT)");
AnalysisError(
"drop function functional.TestFn()", "Function does not exist: testfn()");
AnalysisError("create function f() returns int " + udfSuffix +
"init_fn='a'", "Optional argument 'INIT_FN' should not be set");
AnalysisError("create function f() returns int " + udfSuffix +
"serialize_fn='a'", "Optional argument 'SERIALIZE_FN' should not be set");
AnalysisError("create function f() returns int " + udfSuffix +
"merge_fn='a'", "Optional argument 'MERGE_FN' should not be set");
AnalysisError("create function f() returns int " + udfSuffix +
"finalize_fn='a'", "Optional argument 'FINALIZE_FN' should not be set");
}
@Test
public void TestUda() throws AnalysisException {
final String loc = " LOCATION '/test-warehouse/libTestUdas.so' ";
final String hdfsLoc = "hdfs://localhost:20500/test-warehouse/libTestUdas.so";
AnalyzesOk("create aggregate function foo(int) RETURNS int" + loc +
"UPDATE_FN='AggUpdate'");
AnalyzesOk("create aggregate function foo(int) RETURNS int" + loc +
"UPDATE_FN='AggUpdate' INIT_FN='AggInit'");
AnalyzesOk("create aggregate function foo(int) RETURNS int" + loc +
"UPDATE_FN='AggUpdate' INIT_FN='AggInit' MERGE_FN='AggMerge'");
AnalysisError("create aggregate function foo(int) RETURNS int" + loc +
"UPDATE_FN='AggUpdate' INIT_FN='AGgInit'",
"Could not find function AGgInit() returns INT in: " + hdfsLoc);
AnalyzesOk("create aggregate function foo(int, int) RETURNS int" + loc +
"UPDATE_FN='AggUpdate'");
AnalyzesOk("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='AggUpdate'");
// TODO: remove these when the BE can execute them
AnalysisError("create aggregate function foo(int...) RETURNS int" + loc,
"UDAs with varargs are not yet supported.");
AnalysisError("create aggregate function "
+ "foo(int, int, int, int, int, int, int , int, int) "
+ "RETURNS int" + loc,
"UDAs with more than 8 arguments are not yet supported.");
// Check that CHAR and VARCHAR are not valid UDA argument or return types
String symbols =
" UPDATE_FN='_Z9AggUpdatePN10impala_udf15FunctionContextERKNS_6IntValEPS2_' " +
"INIT_FN='_Z7AggInitPN10impala_udf15FunctionContextEPNS_6IntValE' " +
"MERGE_FN='_Z8AggMergePN10impala_udf15FunctionContextERKNS_6IntValEPS2_'";
AnalysisError("create aggregate function foo(CHAR(5)) RETURNS int" + loc + symbols,
"UDAs with CHAR arguments are not yet supported.");
AnalysisError("create aggregate function foo(VARCHAR(5)) RETURNS int" + loc + symbols,
"UDAs with VARCHAR arguments are not yet supported.");
AnalysisError("create aggregate function foo(int) RETURNS CHAR(5)" + loc + symbols,
"UDAs with CHAR return type are not yet supported.");
AnalysisError("create aggregate function foo(int) RETURNS VARCHAR(5)" + loc + symbols,
"UDAs with VARCHAR return type are not yet supported.");
// Specify the complete symbol. If the user does this, we can't guess the
// other function names.
// TODO: think about these error messages more. Perhaps they can be made
// more actionable.
AnalysisError("create aggregate function foo(int) RETURNS int" + loc +
"UPDATE_FN='_Z9AggUpdatePN10impala_udf15FunctionContextERKNS_6IntValEPS2_'",
"Could not infer symbol for init() function.");
AnalysisError("create aggregate function foo(int) RETURNS int" + loc +
"UPDATE_FN='_Z9AggUpdatePN10impala_udf15FunctionContextERKNS_6IntValEPS2_' " +
"INIT_FN='_Z7AggInitPN10impala_udf15FunctionContextEPNS_6IntValE'",
"Could not infer symbol for merge() function.");
AnalyzesOk("create aggregate function foo(int) RETURNS int" + loc +
"UPDATE_FN='_Z9AggUpdatePN10impala_udf15FunctionContextERKNS_6IntValEPS2_' " +
"INIT_FN='_Z7AggInitPN10impala_udf15FunctionContextEPNS_6IntValE' " +
"MERGE_FN='_Z8AggMergePN10impala_udf15FunctionContextERKNS_6IntValEPS2_'");
// Try with intermediate type
// TODO: this is currently not supported. Remove these tests and re-enable
// the commented out ones when we do.
AnalyzesOk("create aggregate function foo(int) RETURNS int " +
"INTERMEDIATE int" + loc + "UPDATE_FN='AggUpdate'");
AnalysisError("create aggregate function foo(int) RETURNS int " +
"INTERMEDIATE double" + loc + "UPDATE_FN='AggUpdate'",
"UDAs with an intermediate type, DOUBLE, that is different from the " +
"return type, INT, are currently not supported.");
AnalysisError("create aggregate function foo(int) RETURNS int " +
"INTERMEDIATE char(10)" + loc + "UPDATE_FN='AggUpdate'",
"UDAs with an intermediate type, CHAR(10), that is different from the " +
"return type, INT, are currently not supported.");
AnalysisError("create aggregate function foo(int) RETURNS int " +
"INTERMEDIATE decimal(10)" + loc + "UPDATE_FN='AggUpdate'",
"UDAs with an intermediate type, DECIMAL(10,0), that is different from the " +
"return type, INT, are currently not supported.");
AnalysisError("create aggregate function foo(int) RETURNS int " +
"INTERMEDIATE decimal(40)" + loc + "UPDATE_FN='AggUpdate'",
"Decimal precision must be <= 38.");
//AnalyzesOk("create aggregate function foo(int) RETURNS int " +
// "INTERMEDIATE CHAR(10)" + loc + "UPDATE_FN='AggUpdate'");
//AnalysisError("create aggregate function foo(int) RETURNS int " +
// "INTERMEDIATE CHAR(10)" + loc + "UPDATE_FN='Agg' INIT_FN='AggInit' " +
// "MERGE_FN='AggMerge'" ,
// "Finalize() is required for this UDA.");
//AnalyzesOk("create aggregate function foo(int) RETURNS int " +
// "INTERMEDIATE CHAR(10)" + loc + "UPDATE_FN='Agg' INIT_FN='AggInit' " +
// "MERGE_FN='AggMerge' FINALIZE_FN='AggFinalize'");
// Udf only arguments must not be set.
AnalysisError("create aggregate function foo(int) RETURNS int" + loc + "SYMBOL='Bad'",
"Optional argument 'SYMBOL' should not be set.");
// Invalid char(0) type.
AnalysisError("create aggregate function foo(int) RETURNS int " +
"INTERMEDIATE CHAR(0) LOCATION '/foo.so' UPDATE_FN='b'",
"Char size must be > 0. Size is too small: 0.");
AnalysisError("create aggregate function foo() RETURNS int" + loc,
"UDAs must take at least one argument.");
AnalysisError("create aggregate function foo(int) RETURNS int LOCATION " +
"'/foo.jar' UPDATE_FN='b'", "Java UDAs are not supported.");
// Try creating functions with unsupported return/arg types.
AnalysisError("create aggregate function foo(string, double) RETURNS array<int> " +
loc + "UPDATE_FN='AggUpdate'",
"Type 'ARRAY<INT>' is not supported in UDFs/UDAs.");
AnalysisError("create aggregate function foo(map<string,int>) RETURNS int " +
loc + "UPDATE_FN='AggUpdate'",
"Type 'MAP<STRING,INT>' is not supported in UDFs/UDAs.");
AnalysisError("create aggregate function foo(int) RETURNS struct<f:int> " +
loc + "UPDATE_FN='AggUpdate'",
"Type 'STRUCT<f:INT>' is not supported in UDFs/UDAs.");
// Test missing .ll file. TODO: reenable when we can run IR UDAs
AnalysisError("create aggregate function foo(int) RETURNS int LOCATION " +
"'/foo.ll' UPDATE_FN='Fn'", "IR UDAs are not yet supported.");
//AnalysisError("create aggregate function foo(int) RETURNS int LOCATION " +
// "'/foo.ll' UPDATE_FN='Fn'", "Could not load binary: /foo.ll");
//AnalysisError("create aggregate function foo(int) RETURNS int LOCATION " +
// "'/foo.ll' UPDATE_FN='_ZABCD'", "Could not load binary: /foo.ll");
// Test cases where the UPDATE_FN doesn't contain "Update" in which case the user has
// to explicitly specify the other functions.
AnalysisError("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg'", "Could not infer symbol for init() function.");
AnalysisError("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg' INIT_FN='AggInit'",
"Could not infer symbol for merge() function.");
AnalyzesOk("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg' INIT_FN='AggInit' MERGE_FN='AggMerge'");
AnalyzesOk("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg' INIT_FN='AggInit' MERGE_FN='AggMerge' " +
"SERIALIZE_FN='AggSerialize'");
AnalyzesOk("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg' INIT_FN='AggInit' MERGE_FN='AggMerge' " +
"SERIALIZE_FN='AggSerialize' FINALIZE_FN='AggFinalize'");
// Serialize and Finalize have the same signature, make sure that's possible.
AnalyzesOk("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='AggUpdate' SERIALIZE_FN='AggSerialize' FINALIZE_FN='AggSerialize'");
AnalyzesOk("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='AggUpdate' SERIALIZE_FN='AggFinalize' FINALIZE_FN='AggFinalize'");
// If you don't specify the full symbol, we look for it in the binary. This should
// prevent mismatched names by accident.
AnalysisError("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='AggUpdate' INIT_FN='AggSerialize'",
"Could not find function AggSerialize() returns STRING in: " + hdfsLoc);
// If you specify a mangled name, we just check it exists.
// TODO: we should be able to validate better. This is almost certainly going
// to crash everything.
AnalyzesOk("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='AggUpdate' "+
"INIT_FN='_Z12AggSerializePN10impala_udf15FunctionContextERKNS_6IntValE'");
AnalysisError("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='AggUpdate' INIT_FN='_ZAggSerialize'",
"Could not find symbol '_ZAggSerialize' in: " + hdfsLoc);
// Tests for checking the symbol exists
AnalysisError("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg2Update'",
"Could not find function Agg2Init() returns STRING in: " + hdfsLoc);
AnalysisError("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg2Update' INIT_FN='AggInit'",
"Could not find function Agg2Merge(STRING) returns STRING in: " + hdfsLoc);
AnalyzesOk("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg2Update' INIT_FN='AggInit' MERGE_FN='AggMerge'");
AnalysisError("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg2Update' INIT_FN='AggInit' MERGE_FN='BadFn'",
"Could not find function BadFn(STRING) returns STRING in: " + hdfsLoc);
AnalysisError("create aggregate function foo(string, double) RETURNS string" + loc +
"UPDATE_FN='Agg2Update' INIT_FN='AggInit' MERGE_FN='AggMerge' "+
"FINALIZE_FN='not there'",
"Could not find function not there(STRING) in: " + hdfsLoc);
}
/**
* Wraps the given typeDefs in a CREATE TABLE stmt and runs AnalyzesOk().
* Also tests that the type is analyzes correctly in ARRAY, MAP, and STRUCT types.
*/
private void TypeDefsAnalyzeOk(String... typeDefs) {
for (String typeDefStr: typeDefs) {
ParseNode stmt = AnalyzesOk(String.format("CREATE TABLE t (i %s)", typeDefStr));
AnalyzesOk(String.format("CREATE TABLE t (i ARRAY<%s>)", typeDefStr));
AnalyzesOk(String.format("CREATE TABLE t (i STRUCT<f:%s>)", typeDefStr));
Preconditions.checkState(stmt instanceof CreateTableStmt);
CreateTableStmt createTableStmt = (CreateTableStmt) stmt;
Type t = createTableStmt.getColumnDefs().get(0).getType();
// If the given type is complex, don't use it as a map key.
if (t.isComplexType()) {
AnalyzesOk(String.format(
"CREATE TABLE t (i MAP<int, %s>)", typeDefStr, typeDefStr));
} else {
AnalyzesOk(String.format(
"CREATE TABLE t (i MAP<%s, %s>)", typeDefStr, typeDefStr));
}
}
}
/**
* Wraps the given typeDefs in a CREATE TABLE stmt and asserts that the type def
* failed to analyze with the given error message.
*/
private void TypeDefAnalysisError(String typeDef, String expectedError) {
AnalysisError(String.format("CREATE TABLE t (i %s)", typeDef), expectedError);
}
@Test
public void TestTypes() {
// Test primitive types.
TypeDefsAnalyzeOk("BOOLEAN");
TypeDefsAnalyzeOk("TINYINT");
TypeDefsAnalyzeOk("SMALLINT");
TypeDefsAnalyzeOk("INT", "INTEGER");
TypeDefsAnalyzeOk("BIGINT");
TypeDefsAnalyzeOk("FLOAT");
TypeDefsAnalyzeOk("DOUBLE", "REAL");
TypeDefsAnalyzeOk("STRING");
TypeDefsAnalyzeOk("CHAR(1)", "CHAR(20)");
TypeDefsAnalyzeOk("BINARY");
TypeDefsAnalyzeOk("DECIMAL");
TypeDefsAnalyzeOk("TIMESTAMP");
// Test decimal.
TypeDefsAnalyzeOk("DECIMAL");
TypeDefsAnalyzeOk("DECIMAL(1)");
TypeDefsAnalyzeOk("DECIMAL(12, 7)");
TypeDefsAnalyzeOk("DECIMAL(38)");
TypeDefsAnalyzeOk("DECIMAL(38, 1)");
TypeDefsAnalyzeOk("DECIMAL(38, 38)");
TypeDefAnalysisError("DECIMAL(1, 10)",
"Decimal scale (10) must be <= precision (1).");
TypeDefAnalysisError("DECIMAL(0, 0)",
"Decimal precision must be greater than 0.");
TypeDefAnalysisError("DECIMAL(39, 0)",
"Decimal precision must be <= 38.");
// Test complex types.
TypeDefsAnalyzeOk("ARRAY<BIGINT>");
TypeDefsAnalyzeOk("MAP<TINYINT, DOUBLE>");
TypeDefsAnalyzeOk("STRUCT<f:TINYINT>");
TypeDefsAnalyzeOk("STRUCT<a:TINYINT, b:BIGINT, c:DOUBLE>");
TypeDefsAnalyzeOk("STRUCT<a:TINYINT COMMENT 'x', b:BIGINT, c:DOUBLE COMMENT 'y'>");
// Map keys can't be complex types.
TypeDefAnalysisError("map<array<int>, int>",
"Map type cannot have a complex-typed key: MAP<ARRAY<INT>,INT>");
// Duplicate struct-field name.
TypeDefAnalysisError("STRUCT<f1: int, f2: string, f1: float>",
"Duplicate field name 'f1' in struct 'STRUCT<f1:INT,f2:STRING,f1:FLOAT>'");
// Invalid struct-field name.
TypeDefAnalysisError("STRUCT<`???`: int>",
"Invalid struct field name: ???");
}
@Test
public void TestUseDb() throws AnalysisException {
AnalyzesOk("use functional");
AnalysisError("use db_does_not_exist", "Database does not exist: db_does_not_exist");
}
@Test
public void TestUseStatement() {
Assert.assertTrue(AnalyzesOk("USE functional") instanceof UseStmt);
}
@Test
public void TestDescribe() throws AnalysisException {
AnalyzesOk("describe formatted functional.alltypes");
AnalyzesOk("describe functional.alltypes");
AnalysisError("describe formatted nodb.alltypes",
"Database does not exist: nodb");
AnalysisError("describe functional.notbl",
"Table does not exist: functional.notbl");
}
@Test
public void TestShow() throws AnalysisException {
AnalyzesOk("show databases");
AnalyzesOk("show databases like '*pattern'");
AnalyzesOk("show data sources");
AnalyzesOk("show data sources like '*pattern'");
AnalyzesOk("show tables");
AnalyzesOk("show tables like '*pattern'");
for (String fnType: new String[]{"", "aggregate", "analytic"}) {
AnalyzesOk(String.format("show %s functions", fnType));
AnalyzesOk(String.format("show %s functions like '*pattern'", fnType));
AnalyzesOk(String.format("show %s functions in functional", fnType));
AnalyzesOk(String.format(
"show %s functions in functional like '*pattern'", fnType));
}
// Database doesn't exist.
AnalysisError("show functions in baddb", "Database does not exist: baddb");
AnalysisError("show functions in baddb like '*pattern'",
"Database does not exist: baddb");
}
@Test
public void TestShowFiles() throws AnalysisException {
// Test empty table
AnalyzesOk(String.format("show files in functional.emptytable"));
String[] partitions = new String[] { "", "partition(month=10, year=2010)" };
for (String partition: partitions) {
AnalyzesOk(String.format("show files in functional.alltypes %s", partition));
// Database/table doesn't exist.
AnalysisError(String.format("show files in baddb.alltypes %s", partition),
"Database does not exist: baddb");
AnalysisError(String.format("show files in functional.badtbl %s", partition),
"Table does not exist: functional.badtbl");
// Cannot show files on a non hdfs table.
AnalysisError(String.format("show files in functional.alltypes_view %s",
partition),
"SHOW FILES not applicable to a non hdfs table: functional.alltypes_view");
}
// Not a partition column.
AnalysisError("show files in functional.alltypes partition(year=2010,int_col=1)",
"Column 'int_col' is not a partition column in table: functional.alltypes");
// Not a valid column.
AnalysisError("show files in functional.alltypes partition(year=2010,day=1)",
"Partition column 'day' not found in table: functional.alltypes");
// Table is not partitioned.
AnalysisError("show files in functional.tinyinttable partition(int_col=1)",
"Table is not partitioned: functional.tinyinttable");
// Partition spec does not exist
AnalysisError("show files in functional.alltypes partition(year=2010,month=NULL)",
"Partition spec does not exist: (year=2010, month=NULL)");
}
@Test
public void TestShowStats() throws AnalysisException {
String[] statsQuals = new String[] {"table", "column"};
for (String qual : statsQuals) {
AnalyzesOk(String.format("show %s stats functional.alltypes", qual));
// Database/table doesn't exist.
AnalysisError(String.format("show %s stats baddb.alltypes", qual),
"Database does not exist: baddb");
AnalysisError(String.format("show %s stats functional.badtbl", qual),
"Table does not exist: functional.badtbl");
// Cannot show stats on a view.
AnalysisError(String.format("show %s stats functional.alltypes_view", qual),
String.format("SHOW %s STATS not applicable to a view: " +
"functional.alltypes_view", qual.toUpperCase()));
}
}
@Test
public void TestShowPartitions() throws AnalysisException {
AnalyzesOk("show partitions functional.alltypes");
AnalysisError("show partitions baddb.alltypes",
"Database does not exist: baddb");
AnalysisError("show partitions functional.badtbl",
"Table does not exist: functional.badtbl");
AnalysisError("show partitions functional.alltypesnopart",
"Table is not partitioned: functional.alltypesnopart");
AnalysisError("show partitions functional.view_view",
"SHOW PARTITIONS not applicable to a view: functional.view_view");
AnalysisError("show partitions functional_hbase.alltypes",
"SHOW PARTITIONS must target an HDFS table: functional_hbase.alltypes");
}
/**
* Validate if location path analysis issues proper warnings when directory
* permissions/existence checks fail.
*/
@Test
public void TestPermissionValidation() throws AnalysisException {
String location = "/test-warehouse/.tmp_" + UUID.randomUUID().toString();
Path parentPath = FileSystemUtil.createFullyQualifiedPath(new Path(location));
FileSystem fs = null;
try {
fs = parentPath.getFileSystem(FileSystemUtil.getConfiguration());
// Test location doesn't exist
AnalyzesOk(String.format("create table new_table (col INT) location '%s/new_table'",
location),
String.format("Path '%s' cannot be reached: Path does not exist.",
parentPath));
// Test localtion path with trailing slash.
AnalyzesOk(String.format("create table new_table (col INT) location " +
"'%s/new_table/'", location),
String.format("Path '%s' cannot be reached: Path does not exist.",
parentPath));
AnalyzesOk(String.format("create table new_table location '%s/new_table' " +
"as select 1, 1", location),
String.format("Path '%s' cannot be reached: Path does not exist.",
parentPath));
AnalyzesOk(String.format("create table new_table like functional.alltypes " +
"location '%s/new_table'", location),
String.format("Path '%s' cannot be reached: Path does not exist.",
parentPath));
AnalyzesOk(String.format("create database new_db location '%s/new_db'",
location),
String.format("Path '%s' cannot be reached: Path does not exist.",
parentPath));
fs.mkdirs(parentPath);
// Create a test data file for load data test
FSDataOutputStream out =
fs.create(new Path(parentPath, "test_loaddata/testdata.txt"));
out.close();
fs.setPermission(parentPath,
new FsPermission(FsAction.NONE, FsAction.NONE, FsAction.NONE));
// Test location exists but Impala doesn't have sufficient permission
AnalyzesOk(String.format("create data Source serverlog location " +
"'%s/foo.jar' class 'foo.Bar' API_VERSION 'V1'", location),
String.format("Impala does not have READ access to path '%s'", parentPath));
AnalyzesOk(String.format("create external table new_table (col INT) location " +
"'%s/new_table'", location),
String.format("Impala does not have READ_WRITE access to path '%s'",
parentPath));
AnalyzesOk(String.format("alter table functional.insert_string_partitioned " +
"add partition (s2='hello') location '%s/new_partition'", location),
String.format("Impala does not have READ_WRITE access to path '%s'",
parentPath));
AnalyzesOk(String.format("alter table functional.insert_string_partitioned " +
"partition(s2=NULL) set location '%s/new_part_loc'", location),
String.format("Impala does not have READ_WRITE access to path '%s'",
parentPath));
// Test location exists and Impala does have sufficient permission
fs.setPermission(parentPath,
new FsPermission(FsAction.READ_WRITE, FsAction.NONE, FsAction.NONE));
AnalyzesOk(String.format("create external table new_table (col INT) location " +
"'%s/new_table'", location));
} catch (IOException e) {
throw new AnalysisException(e.getMessage(), e);
} finally {
// Clean up
try {
if (fs != null && fs.exists(parentPath)) {
fs.delete(parentPath, true);
}
} catch (IOException e) {
// Ignore
}
}
}
}
|
Temporarily remove test for guarding against HIVE-6308.
After we have generated a new snapshot, I will restore the proper
testing with: http://gerrit.cloudera.org:8080/180
Change-Id: Ida8593b5692d0898ecfa936850d9e2e194138d08
|
fe/src/test/java/com/cloudera/impala/analysis/AnalyzeDDLTest.java
|
Temporarily remove test for guarding against HIVE-6308.
|
|
Java
|
apache-2.0
|
f5d7b9417126a19ba7695458b93fcb687579fd5f
| 0
|
Pushpalanka/carbon-identity,Pushpalanka/carbon-identity,Pushpalanka/carbon-identity
|
/*
* Copyright (c) 2005, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.identity.sso.saml.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.equinox.http.helper.ContextPathServletAdaptor;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.http.HttpService;
import org.wso2.carbon.identity.authenticator.saml2.sso.common.Util;
import org.wso2.carbon.identity.base.IdentityConstants;
import org.wso2.carbon.identity.core.util.IdentityIOStreamUtils;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.sso.saml.SAMLSSOConstants;
import org.wso2.carbon.identity.sso.saml.SSOServiceProviderConfigManager;
import org.wso2.carbon.identity.sso.saml.admin.FileBasedConfigManager;
import org.wso2.carbon.identity.sso.saml.servlet.SAMLSSOProviderServlet;
import org.wso2.carbon.identity.sso.saml.util.SAMLSSOUtil;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.ConfigurationContextService;
import javax.servlet.Servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* @scr.component name="identity.sso.saml.component" immediate="true"
* @scr.reference name="registry.service"
* interface="org.wso2.carbon.registry.core.service.RegistryService"
* cardinality="1..1" policy="dynamic" bind="setRegistryService"
* unbind="unsetRegistryService"
* @scr.reference name="config.context.service"
* interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1"
* policy="dynamic" bind="setConfigurationContextService"
* unbind="unsetConfigurationContextService"
* @scr.reference name="user.realmservice.default" interface="org.wso2.carbon.user.core.service.RealmService"
* cardinality="1..1" policy="dynamic" bind="setRealmService"
* unbind="unsetRealmService"
* @scr.reference name="osgi.httpservice" interface="org.osgi.service.http.HttpService"
* cardinality="1..1" policy="dynamic" bind="setHttpService"
* unbind="unsetHttpService"
*/
public class IdentitySAMLSSOServiceComponent {
private static Log log = LogFactory.getLog(IdentitySAMLSSOServiceComponent.class);
private static int defaultSingleLogoutRetryCount = 5;
private static long defaultSingleLogoutRetryInterval = 60000;
private static String ssoRedirectPage = null;
public static String getSsoRedirectHtml() {
return ssoRedirectPage;
}
protected void activate(ComponentContext ctxt) {
SAMLSSOUtil.setBundleContext(ctxt.getBundleContext());
HttpService httpService = SAMLSSOUtil.getHttpService();
// Register SAML SSO servlet
Servlet samlSSOServlet = new ContextPathServletAdaptor(new SAMLSSOProviderServlet(),
SAMLSSOConstants.SAMLSSO_URL);
try {
httpService.registerServlet(SAMLSSOConstants.SAMLSSO_URL, samlSSOServlet, null, null);
} catch (Exception e) {
String errMsg = "Error when registering SAML SSO Servlet via the HttpService.";
log.error(errMsg, e);
throw new RuntimeException(errMsg, e);
}
// Register a SSOServiceProviderConfigManager object as an OSGi Service
ctxt.getBundleContext().registerService(SSOServiceProviderConfigManager.class.getName(),
SSOServiceProviderConfigManager.getInstance(), null);
String redirectHtmlPath = null;
FileInputStream fis = null;
try {
IdentityUtil.populateProperties();
SAMLSSOUtil.setSingleLogoutRetryCount(Integer.parseInt(
IdentityUtil.getProperty(IdentityConstants.ServerConfig.SINGLE_LOGOUT_RETRY_COUNT)));
SAMLSSOUtil.setSingleLogoutRetryInterval(Long.parseLong(IdentityUtil.getProperty(
IdentityConstants.ServerConfig.SINGLE_LOGOUT_RETRY_INTERVAL)));
SAMLSSOUtil.setResponseBuilder(IdentityUtil.getProperty("SSOService.SAMLSSOResponseBuilder"));
SAMLSSOUtil.setIdPInitSSOAuthnRequestValidator(IdentityUtil.getProperty("SSOService.IdPInitSSOAuthnRequestValidator"));
SAMLSSOUtil.setSPInitSSOAuthnRequestValidator(IdentityUtil.getProperty("SSOService.SPInitSSOAuthnRequestValidator"));
if (log.isDebugEnabled()) {
log.debug("IdPInitSSOAuthnRequestValidator is set to " +
IdentityUtil.getProperty("SSOService.IdPInitSSOAuthnRequestValidator"));
log.debug("SPInitSSOAuthnRequestValidator is set to " +
IdentityUtil.getProperty("SSOService.SPInitSSOAuthnRequestValidator"));
log.debug("Single logout retry count is set to " + SAMLSSOUtil.getSingleLogoutRetryCount());
log.debug("Single logout retry interval is set to " +
SAMLSSOUtil.getSingleLogoutRetryInterval() + " in seconds.");
}
redirectHtmlPath = CarbonUtils.getCarbonHome() + File.separator + "repository"
+ File.separator + "resources" + File.separator + "identity" + File.separator + "pages" + File.separator + "samlsso_response.html";
fis = new FileInputStream(new File(redirectHtmlPath));
ssoRedirectPage = new Scanner(fis, "UTF-8").useDelimiter("\\A").next();
log.debug("samlsso_response.html " + ssoRedirectPage);
FileBasedConfigManager.getInstance().addServiceProviders();
Util.initSSOConfigParams();
if (log.isDebugEnabled()) {
log.debug("Identity SAML SSO bundle is activated");
}
} catch (FileNotFoundException e) {
if (log.isDebugEnabled()) {
log.debug("Failed to find SAML SSO response page in : " + redirectHtmlPath);
}
} catch (Throwable e) {
SAMLSSOUtil.setSingleLogoutRetryCount(defaultSingleLogoutRetryCount);
SAMLSSOUtil.setSingleLogoutRetryInterval(defaultSingleLogoutRetryInterval);
if (log.isDebugEnabled()) {
log.debug("Failed to load the single logout retry count and interval values." +
" Default values for retry count: " + defaultSingleLogoutRetryCount +
" and interval: " + defaultSingleLogoutRetryInterval + " will be used.", e);
}
} finally {
IdentityIOStreamUtils.closeInputStream(fis);
}
}
protected void deactivate(ComponentContext ctxt) {
SAMLSSOUtil.setBundleContext(null);
if (log.isDebugEnabled()) {
log.info("Identity SAML SSO bundle is deactivated");
}
}
protected void setRegistryService(RegistryService registryService) {
if (log.isDebugEnabled()) {
log.debug("RegistryService set in Identity SAML SSO bundle");
}
try {
SAMLSSOUtil.setRegistryService(registryService);
} catch (Throwable e) {
log.error("Failed to get a reference to the Registry in SAML SSO bundle", e);
}
}
protected void unsetRegistryService(RegistryService registryService) {
if (log.isDebugEnabled()) {
log.debug("RegistryService unset in SAML SSO bundle");
}
SAMLSSOUtil.setRegistryService(null);
}
protected void setRealmService(RealmService realmService) {
if (log.isDebugEnabled()) {
log.debug("Realm Service is set in the SAML SSO bundle");
}
SAMLSSOUtil.setRealmService(realmService);
}
protected void unsetRealmService(RealmService realmService) {
if (log.isDebugEnabled()) {
log.debug("Realm Service is set in the SAML SSO bundle");
}
SAMLSSOUtil.setRegistryService(null);
}
protected void setConfigurationContextService(ConfigurationContextService configCtxService) {
if (log.isDebugEnabled()) {
log.debug("Configuration Context Service is set in the SAML SSO bundle");
}
SAMLSSOUtil.setConfigCtxService(configCtxService);
}
protected void unsetConfigurationContextService(ConfigurationContextService configCtxService) {
if (log.isDebugEnabled()) {
log.debug("Configuration Context Service is unset in the SAML SSO bundle");
}
SAMLSSOUtil.setConfigCtxService(null);
}
protected void setHttpService(HttpService httpService) {
if (log.isDebugEnabled()) {
log.debug("HTTP Service is set in the SAML SSO bundle");
}
SAMLSSOUtil.setHttpService(httpService);
}
protected void unsetHttpService(HttpService httpService) {
if (log.isDebugEnabled()) {
log.debug("HTTP Service is unset in the SAML SSO bundle");
}
SAMLSSOUtil.setHttpService(null);
}
}
|
components/sso-saml/org.wso2.carbon.identity.sso.saml/src/main/java/org/wso2/carbon/identity/sso/saml/internal/IdentitySAMLSSOServiceComponent.java
|
/*
* Copyright (c) 2005, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.identity.sso.saml.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.equinox.http.helper.ContextPathServletAdaptor;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.http.HttpService;
import org.wso2.carbon.identity.authenticator.saml2.sso.common.Util;
import org.wso2.carbon.identity.base.IdentityConstants;
import org.wso2.carbon.identity.core.util.IdentityIOStreamUtils;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.sso.saml.SAMLSSOConstants;
import org.wso2.carbon.identity.sso.saml.SSOServiceProviderConfigManager;
import org.wso2.carbon.identity.sso.saml.admin.FileBasedConfigManager;
import org.wso2.carbon.identity.sso.saml.servlet.SAMLSSOProviderServlet;
import org.wso2.carbon.identity.sso.saml.util.SAMLSSOUtil;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.ConfigurationContextService;
import javax.servlet.Servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* @scr.component name="identity.sso.saml.component" immediate="true"
* @scr.reference name="registry.service"
* interface="org.wso2.carbon.registry.core.service.RegistryService"
* cardinality="1..1" policy="dynamic" bind="setRegistryService"
* unbind="unsetRegistryService"
* @scr.reference name="config.context.service"
* interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1"
* policy="dynamic" bind="setConfigurationContextService"
* unbind="unsetConfigurationContextService"
* @scr.reference name="user.realmservice.default" interface="org.wso2.carbon.user.core.service.RealmService"
* cardinality="1..1" policy="dynamic" bind="setRealmService"
* unbind="unsetRealmService"
* @scr.reference name="osgi.httpservice" interface="org.osgi.service.http.HttpService"
* cardinality="1..1" policy="dynamic" bind="setHttpService"
* unbind="unsetHttpService"
*/
public class IdentitySAMLSSOServiceComponent {
private static Log log = LogFactory.getLog(IdentitySAMLSSOServiceComponent.class);
private static int defaultSingleLogoutRetryCount = 5;
private static long defaultSingleLogoutRetryInterval = 60000;
private static String ssoRedirectPage = null;
public static String getSsoRedirectHtml() {
return ssoRedirectPage;
}
protected void activate(ComponentContext ctxt) {
SAMLSSOUtil.setBundleContext(ctxt.getBundleContext());
HttpService httpService = SAMLSSOUtil.getHttpService();
// Register SAML SSO servlet
Servlet samlSSOServlet = new ContextPathServletAdaptor(new SAMLSSOProviderServlet(),
SAMLSSOConstants.SAMLSSO_URL);
try {
httpService.registerServlet(SAMLSSOConstants.SAMLSSO_URL, samlSSOServlet, null, null);
} catch (Exception e) {
String errMsg = "Error when registering SAML SSO Servlet via the HttpService.";
log.error(errMsg, e);
throw new RuntimeException(errMsg, e);
}
// Register a SSOServiceProviderConfigManager object as an OSGi Service
ctxt.getBundleContext().registerService(SSOServiceProviderConfigManager.class.getName(),
SSOServiceProviderConfigManager.getInstance(), null);
String redirectHtmlPath = null;
FileInputStream fis = null;
try {
IdentityUtil.populateProperties();
SAMLSSOUtil.setSingleLogoutRetryCount(Integer.parseInt(
IdentityUtil.getProperty(IdentityConstants.ServerConfig.SINGLE_LOGOUT_RETRY_COUNT)));
SAMLSSOUtil.setSingleLogoutRetryInterval(Long.parseLong(IdentityUtil.getProperty(
IdentityConstants.ServerConfig.SINGLE_LOGOUT_RETRY_INTERVAL)));
SAMLSSOUtil.setResponseBuilder(IdentityUtil.getProperty("SSOService.SAMLSSOResponseBuilder"));
SAMLSSOUtil.setIdPInitSSOAuthnRequestValidator(IdentityUtil.getProperty("SSOService.IdPInitSSOAuthnRequestValidator"));
SAMLSSOUtil.setSPInitSSOAuthnRequestValidator(IdentityUtil.getProperty("SSOService.SPInitSSOAuthnRequestValidator"));
log.debug("Single logout retry count is set to " + SAMLSSOUtil.getSingleLogoutRetryCount());
log.debug("Single logout retry interval is set to " +
SAMLSSOUtil.getSingleLogoutRetryInterval() + " in seconds.");
redirectHtmlPath = CarbonUtils.getCarbonHome() + File.separator + "repository"
+ File.separator + "resources" + File.separator + "identity" + File.separator + "pages" + File.separator + "samlsso_response.html";
fis = new FileInputStream(new File(redirectHtmlPath));
ssoRedirectPage = new Scanner(fis, "UTF-8").useDelimiter("\\A").next();
log.debug("samlsso_response.html " + ssoRedirectPage);
FileBasedConfigManager.getInstance().addServiceProviders();
Util.initSSOConfigParams();
if (log.isDebugEnabled()) {
log.info("Identity SAML SSO bundle is activated");
}
} catch (FileNotFoundException e) {
if (log.isDebugEnabled()) {
log.debug("Failed to find SAML SSO response page in : " + redirectHtmlPath);
}
} catch (Throwable e) {
SAMLSSOUtil.setSingleLogoutRetryCount(defaultSingleLogoutRetryCount);
SAMLSSOUtil.setSingleLogoutRetryInterval(defaultSingleLogoutRetryInterval);
if (log.isDebugEnabled()) {
log.debug("Failed to load the single logout retry count and interval values." +
" Default values for retry count: " + defaultSingleLogoutRetryCount +
" and interval: " + defaultSingleLogoutRetryInterval + " will be used.", e);
}
} finally {
IdentityIOStreamUtils.closeInputStream(fis);
}
}
protected void deactivate(ComponentContext ctxt) {
SAMLSSOUtil.setBundleContext(null);
if (log.isDebugEnabled()) {
log.info("Identity SAML SSO bundle is deactivated");
}
}
protected void setRegistryService(RegistryService registryService) {
if (log.isDebugEnabled()) {
log.debug("RegistryService set in Identity SAML SSO bundle");
}
try {
SAMLSSOUtil.setRegistryService(registryService);
} catch (Throwable e) {
log.error("Failed to get a reference to the Registry in SAML SSO bundle", e);
}
}
protected void unsetRegistryService(RegistryService registryService) {
if (log.isDebugEnabled()) {
log.debug("RegistryService unset in SAML SSO bundle");
}
SAMLSSOUtil.setRegistryService(null);
}
protected void setRealmService(RealmService realmService) {
if (log.isDebugEnabled()) {
log.debug("Realm Service is set in the SAML SSO bundle");
}
SAMLSSOUtil.setRealmService(realmService);
}
protected void unsetRealmService(RealmService realmService) {
if (log.isDebugEnabled()) {
log.debug("Realm Service is set in the SAML SSO bundle");
}
SAMLSSOUtil.setRegistryService(null);
}
protected void setConfigurationContextService(ConfigurationContextService configCtxService) {
if (log.isDebugEnabled()) {
log.debug("Configuration Context Service is set in the SAML SSO bundle");
}
SAMLSSOUtil.setConfigCtxService(configCtxService);
}
protected void unsetConfigurationContextService(ConfigurationContextService configCtxService) {
if (log.isDebugEnabled()) {
log.debug("Configuration Context Service is unset in the SAML SSO bundle");
}
SAMLSSOUtil.setConfigCtxService(null);
}
protected void setHttpService(HttpService httpService) {
if (log.isDebugEnabled()) {
log.debug("HTTP Service is set in the SAML SSO bundle");
}
SAMLSSOUtil.setHttpService(httpService);
}
protected void unsetHttpService(HttpService httpService) {
if (log.isDebugEnabled()) {
log.debug("HTTP Service is unset in the SAML SSO bundle");
}
SAMLSSOUtil.setHttpService(null);
}
}
|
improving logs
|
components/sso-saml/org.wso2.carbon.identity.sso.saml/src/main/java/org/wso2/carbon/identity/sso/saml/internal/IdentitySAMLSSOServiceComponent.java
|
improving logs
|
|
Java
|
apache-2.0
|
bbb16fdb61087ac5b8cb5614a7e9aa1c42d507cd
| 0
|
dichengsiyu/LightMe,dichengsiyu/LightMe
|
package com.hellodev.lightme.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import com.hellodev.lightme.FlashApp;
import com.hellodev.lightme.FlashController;
import com.hellodev.lightme.receiver.SystemReceiver;
import com.hellodev.lightme.util.MLisenseMangaer;
import com.hellodev.lightme.util.MPreferenceManager;
import com.hellodev.lightme.util.ShakeDetector;
import com.hellodev.lightme.util.MLisenseMangaer.OnLisenseStateChangeListener;
import com.hellodev.lightme.util.ShakeDetector.OnShakeListener;
import com.hellodev.lightme.view.KeyguardPanelManager;
import com.hellodev.lightme.view.LauncherPanelManager;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Vibrator;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
public class PanelService extends Service implements OnShakeListener, OnLisenseStateChangeListener {
private final static String TAG = "ControlService";
public static final String CONTROL_TYPE_KEY = "control_type";
public static final int CONTROL_TYPE_DEFAULT = 0;
public static final int CONTROL_TYPE_START = 1;
public static final int CONTROL_TYPE_STOP = 2;
public static final int CONTROL_TYPE_SCREEN_OFF = 3;
public static final int CONTROL_TYPE_SCREEN_ON = 4;
public static final int CONTROL_TYPE_USER_PRESENT = 5;
public final static String ACTION_LAUNCHER = "hellodev.service.action.LAUNCHER";
public final static String ACTION_KEYGUARD = "hellodev.service.action.KEYGUARD";
public final static String ACTION_PANEL_SERVICE = "hellodev.service.action.PANEL_SERVICE";
private LauncherPanelManager mLauncherPanelManager;
private KeyguardPanelManager mKeyguardPanelManager;
private Timer mLauncherRefreshTimer;
private LauncherRefreshTask mLauncherRefreshTask;
private ActivityManager mActivityManager;
private Vibrator mVibrator;
private SystemReceiver mSystemReceiver;
private MPreferenceManager mPrefsManager;
private ShakeDetector mShakeDetector;
private TelephonyManager mTelephonyManager;
private PhoneStateListener mPhoneStateListener;
private KeyguardManager mKeyguardManager;
private Handler mHandler = new Handler();
private FlashController flashController;
private boolean isKeyguardServiceAlive, isLauncherServiceAlive;
private boolean isHomeLastInterval = false;
private MLisenseMangaer lisenseManager;
@Override
public void onCreate() {
super.onCreate();
Context appContext = FlashApp.getContext();
flashController = FlashController.getInstance();
mPrefsManager = MPreferenceManager.getInstance();
mActivityManager = (ActivityManager) appContext
.getSystemService(Context.ACTIVITY_SERVICE);
mVibrator = (Vibrator) appContext
.getSystemService(Context.VIBRATOR_SERVICE);
isKeyguardServiceAlive = isLauncherServiceAlive = false;
mLauncherRefreshTimer = new Timer();
mShakeDetector = new ShakeDetector(appContext);
mShakeDetector.registerOnShakeListener(this);
mKeyguardManager = (KeyguardManager) appContext
.getSystemService(Context.KEYGUARD_SERVICE);
//这个只在锁屏界面才需要监听
mPhoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state,
String incomingNumber) {
if(state == TelephonyManager.CALL_STATE_IDLE) {
mKeyguardPanelManager.showPanel();
if (mPrefsManager.isKeyguardShockEnable())
mShakeDetector.start();//FIXME需要测试
} else if(state == TelephonyManager.CALL_STATE_RINGING) {
mKeyguardPanelManager.hidePanel();
if (mPrefsManager.isKeyguardShockEnable())
mShakeDetector.stop();
}
super.onCallStateChanged(state, incomingNumber);
}
};
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "onStartCommand()");
if (intent != null) {
String action = intent.getAction();
int controlType = intent.getIntExtra(CONTROL_TYPE_KEY,
CONTROL_TYPE_DEFAULT);
if (CONTROL_TYPE_START == controlType)
handleStart(action);
else if (CONTROL_TYPE_STOP == controlType)
handleStop(action);
else if (controlType == CONTROL_TYPE_SCREEN_ON)
handleScreenOn();
else if (controlType == CONTROL_TYPE_SCREEN_OFF)
handleScreenOff();
else if (controlType == CONTROL_TYPE_USER_PRESENT)
handleUserPresent();
} else {
Log.v(TAG, "onStartCommand() restart after kill");
handleStart(ACTION_PANEL_SERVICE);
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
releaseData();
}
private void releaseData() {
stopLauncherPanel();
stopKeyguardPanel();
flashController = null;
mActivityManager = null;
mVibrator = null;
mSystemReceiver = null;
mPrefsManager = null;
//关闭监听
if(mTelephonyManager != null) {
mTelephonyManager.listen(mPhoneStateListener
, PhoneStateListener.LISTEN_NONE);
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
/*
* 调用时机 1. 重启的时候:BootComplete 2. 设置:SettingActivity
*
* * 需要根据preference值,因为可能是重启时的调用
*/
private void handleStart(String action) {
if (!isLauncherServiceAlive && !isKeyguardServiceAlive) {
Log.v(TAG, "start receiver");
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
mSystemReceiver = new SystemReceiver();
FlashApp.getContext().registerReceiver(mSystemReceiver, filter);
//foreground
startForeground(1, new Notification());
}
if (ACTION_LAUNCHER.equals(action))
startLauncherPanel();
else if (ACTION_KEYGUARD.equals(action))
startKeyguardPanel();
else {
if (mPrefsManager.isLauncherPanelShown())
startLauncherPanel();
if (mPrefsManager.isKeyguardPanelShown())
startKeyguardPanel();
}
}
/*
* 调用时机 1. 设置 * 覆盖安装之后service没有起来,没有执行过start,这个时候不能执行unregisterReceiver
*/
private void handleStop(String action) {
if (ACTION_LAUNCHER.equals(action))
stopLauncherPanel();
else if (ACTION_KEYGUARD.equals(action))
stopKeyguardPanel();
else {
// 暂时未使用
stopLauncherPanel();
stopKeyguardPanel();
}
if (!isLauncherServiceAlive && !isKeyguardServiceAlive) {
if (mSystemReceiver != null)
FlashApp.getContext().unregisterReceiver(mSystemReceiver);
mSystemReceiver = null;
stopForeground(true);
stopSelf();
}
}
/*
* 调用时机: 1. 屏幕点亮的时候:(仍然处在锁屏幕) 2. 呼吸灯上滑解锁的时候:(发生在user_present之后)
*
* 不在锁屏都关闭:电话的时候判断状态 * 如果在锁屏界面则打开锁屏panel
* 如果lisense过期,关闭Keyguard
*
* 如果在锁屏界面才监听电话
*/
private void handleScreenOn() {
// initLisense();
if (!isKeyguardScreen()) {
if (isKeyguardServiceAlive)
mKeyguardPanelManager.hidePanel();
} else {
if (isKeyguardServiceAlive) {
if(isTelephoneCalling()) {
mKeyguardPanelManager.hidePanel();
} else {
mKeyguardPanelManager.showPanel();//灭屏、亮屏都show
if (mPrefsManager.isKeyguardShockEnable())
mShakeDetector.start();
}
//锁屏界面需要监听电话状态
mTelephonyManager.listen(mPhoneStateListener
, PhoneStateListener.LISTEN_CALL_STATE);
}
}
//FIXME 需要优化的策略,原则1. 尽量节省资源 2. 不要影响效果
if(!flashController.isFlashOn()) {
flashController.initCameraSync();
}
}
/*
* 调用时机: 1. 灭屏的时候 2. 通话的时候
*
* * 灭屏幕的时候是否会被杀掉,杀掉之后的处理方式
*/
private void handleScreenOff() {
if (isLauncherServiceAlive && !isTelephoneCalling()) {
mLauncherRefreshTask.cancelSelf();
hideLauncherPanel();
}
if (isKeyguardServiceAlive) {
mShakeDetector.stop();
if (!isTelephoneCalling())
mKeyguardPanelManager.showPanel();
//关闭监听
if(mTelephonyManager != null) {
mTelephonyManager.listen(mPhoneStateListener
, PhoneStateListener.LISTEN_NONE);
}
}
//FIXME 需要优化的策略
if(!flashController.isFlashOn()) {
flashController.releaseCamera();
}
}
/*
* 调用时机: 1. 解锁的时候:先screen_on再user_present 2.
* 直接滑动呼吸灯解锁:先user_present再screen_on
*
* * 覆盖安装会kill掉process,不会调用onDestroy,service也不会自动重启
*/
private void handleUserPresent() {
if (isKeyguardServiceAlive) {
mKeyguardPanelManager.hidePanel();
if (mPrefsManager.isKeyguardShockEnable())
mShakeDetector.stop();
//关闭监听
if(mTelephonyManager != null) {
mTelephonyManager.listen(mPhoneStateListener
, PhoneStateListener.LISTEN_NONE);
}
}
startLauncherRefreshTask(0, 1000);
}
private void startLauncherPanel() {
if (!isLauncherServiceAlive) {
isLauncherServiceAlive = true;
if (mLauncherPanelManager == null)
mLauncherPanelManager = new LauncherPanelManager();
if (!isKeyguardScreen()) {
// 如果覆盖安装了,这个时候启动LauncherPanel不应该开始轮询,而应该等到user_present的时候
startLauncherRefreshTask(0, 1000);
}
}
}
private void stopLauncherPanel() {
if (isLauncherServiceAlive) {
isLauncherServiceAlive = false;
mLauncherRefreshTask.cancelSelf();
// closePanel
mLauncherPanelManager.closePanel();
mLauncherPanelManager = null;
// stopService
}
}
/*
* 如果lisense过期,关闭Launcher
*/
private void requestShowLauncherPanel() {
// 当前界面是桌面,且没有悬浮窗显示,则创建悬浮窗。postRunnable的原因是因为timerTask
mHandler.post(new Runnable() {
@Override
public void run() {
if (isLauncherServiceAlive) {
showLauncherPanel();
}
}
});
}
// 灭屏幕的时候应该是cancel掉任务,present的时候应该是show那个view,ok了之后启动桌面轮询task
private void requestHideLauncherPanel() {
// 当前界面不是桌面,且有悬浮窗显示,则移除悬浮窗。
mHandler.post(new Runnable() {
@Override
public void run() {
if (isLauncherServiceAlive) {
hideLauncherPanel();
}
}
});
}
private void showLauncherPanel() {
mLauncherPanelManager.showPanel();
isHomeLastInterval = true;
}
private void hideLauncherPanel() {
mLauncherPanelManager.hidePanel();
isHomeLastInterval = false;
}
/*
* 调用时机: 1. 打开设置项 2. 开机启动的时候
*/
private void startKeyguardPanel() {
if (isKeyguardServiceAlive == false) {
if (mKeyguardPanelManager == null)
mKeyguardPanelManager = new KeyguardPanelManager();
isKeyguardServiceAlive = true;
}
}
/*
* 调用时机 1. 关闭设置项的时候 2.长按移除的时候
*/
private void stopKeyguardPanel() {
if (isKeyguardServiceAlive) {
isKeyguardServiceAlive = false;
mKeyguardPanelManager.closePanel();
mKeyguardPanelManager = null;
mShakeDetector.stop();
mShakeDetector.removeOnShakeListener(this);
}
}
private boolean isHome() {
List<RunningTaskInfo> tasks = mActivityManager.getRunningTasks(1);
return getHomes().contains(tasks.get(0).topActivity.getClassName());
}
private List<String> getHomes() {
List<String> names = new ArrayList<String>();
PackageManager packageManager = this.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(
intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo ri : resolveInfo) {
names.add(ri.activityInfo.name);
}
return names;
}
@Override
public void onShake() {
mVibrator.vibrate(200);
flashController.toggleFlash();
flashController.notifyFlashLevelChanged();//这是一个全局的操作,虽然现在只是keyguard在observer中
}
private boolean isTelephoneCalling() {
if (mTelephonyManager == null)
mTelephonyManager = (TelephonyManager) FlashApp.getContext()
.getSystemService(Context.TELEPHONY_SERVICE);
boolean calling = false;
int status = mTelephonyManager.getCallState();
if (status == TelephonyManager.CALL_STATE_OFFHOOK
|| status == TelephonyManager.CALL_STATE_RINGING) {
calling = true;
}
return calling;
}
private boolean isKeyguardScreen() {
return mKeyguardManager.isKeyguardLocked();
}
//FIXME 这个地方还是有闪动的情况
private void startLauncherRefreshTask(long delay, long period) {
if(mLauncherRefreshTask == null) {
mLauncherRefreshTask = new LauncherRefreshTask();
} else {
if(mLauncherRefreshTask.isRunning())
mLauncherRefreshTask.cancelSelf();
mLauncherRefreshTask = new LauncherRefreshTask();
}
mLauncherRefreshTimer.schedule(mLauncherRefreshTask, delay, period);
}
private class LauncherRefreshTask extends TimerTask {
boolean isLauncherTaskCanceledOrStoped = false;
@Override
public void run() {
if (isLauncherTaskCanceledOrStoped) {
requestHideLauncherPanel();
this.cancel();
} else {
boolean isHome = isHome();
if (isHome && isHomeLastInterval == false)
requestShowLauncherPanel();
else if(isHome == false && isHomeLastInterval == true)
requestHideLauncherPanel();
}
}
//isCurrent标记当前task是否需要被取代
void cancelSelf() {
isLauncherTaskCanceledOrStoped = true;
}
boolean isRunning() {
return !isLauncherTaskCanceledOrStoped;
}
}
private void initLisense() {
boolean purchased = flashController.isPurchased();
if(!purchased) {
lisenseManager = new MLisenseMangaer(this);
lisenseManager.bindRemoteService();
}
}
@Override
public void onRemoteServiceConnected() {
int lisenseState = lisenseManager.doRemoteCheck();
flashController.setLisenseState(lisenseState);
lisenseManager.unbindRemoteService();
if(flashController.islisenseEnable() == false) {
stopKeyguardPanel();
stopLauncherPanel();
}
}
@Override
public void onRemoteServiceDisconnected() {
lisenseManager = null;
}
}
|
src/com/hellodev/lightme/service/PanelService.java
|
package com.hellodev.lightme.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import com.hellodev.lightme.FlashApp;
import com.hellodev.lightme.FlashController;
import com.hellodev.lightme.receiver.SystemReceiver;
import com.hellodev.lightme.util.MLisenseMangaer;
import com.hellodev.lightme.util.MPreferenceManager;
import com.hellodev.lightme.util.ShakeDetector;
import com.hellodev.lightme.util.MLisenseMangaer.OnLisenseStateChangeListener;
import com.hellodev.lightme.util.ShakeDetector.OnShakeListener;
import com.hellodev.lightme.view.KeyguardPanelManager;
import com.hellodev.lightme.view.LauncherPanelManager;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Vibrator;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
public class PanelService extends Service implements OnShakeListener, OnLisenseStateChangeListener {
private final static String TAG = "ControlService";
public static final String CONTROL_TYPE_KEY = "control_type";
public static final int CONTROL_TYPE_DEFAULT = 0;
public static final int CONTROL_TYPE_START = 1;
public static final int CONTROL_TYPE_STOP = 2;
public static final int CONTROL_TYPE_SCREEN_OFF = 3;
public static final int CONTROL_TYPE_SCREEN_ON = 4;
public static final int CONTROL_TYPE_USER_PRESENT = 5;
public final static String ACTION_LAUNCHER = "hellodev.service.action.LAUNCHER";
public final static String ACTION_KEYGUARD = "hellodev.service.action.KEYGUARD";
public final static String ACTION_PANEL_SERVICE = "hellodev.service.action.PANEL_SERVICE";
private LauncherPanelManager mLauncherPanelManager;
private KeyguardPanelManager mKeyguardPanelManager;
private LauncherRefreshTimer mLaucherRefreshTimer;
private ActivityManager mActivityManager;
private Vibrator mVibrator;
private SystemReceiver mSystemReceiver;
private MPreferenceManager mPrefsManager;
private ShakeDetector mShakeDetector;
private TelephonyManager mTelephonyManager;
private PhoneStateListener mPhoneStateListener;
private KeyguardManager mKeyguardManager;
private Handler mHandler = new Handler();
private FlashController flashController;
private boolean isKeyguardServiceAlive, isLauncherServiceAlive;
private boolean isHomeLastInterval = false;
private MLisenseMangaer lisenseManager;
@Override
public void onCreate() {
super.onCreate();
Context appContext = FlashApp.getContext();
flashController = FlashController.getInstance();
mPrefsManager = MPreferenceManager.getInstance();
mActivityManager = (ActivityManager) appContext
.getSystemService(Context.ACTIVITY_SERVICE);
mVibrator = (Vibrator) appContext
.getSystemService(Context.VIBRATOR_SERVICE);
isKeyguardServiceAlive = isLauncherServiceAlive = false;
mLaucherRefreshTimer = new LauncherRefreshTimer(0, 1000);
mShakeDetector = new ShakeDetector(appContext);
mShakeDetector.registerOnShakeListener(this);
mKeyguardManager = (KeyguardManager) appContext
.getSystemService(Context.KEYGUARD_SERVICE);
//这个只在锁屏界面才需要监听
mPhoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state,
String incomingNumber) {
if(state == TelephonyManager.CALL_STATE_IDLE) {
mKeyguardPanelManager.showPanel();
if (mPrefsManager.isKeyguardShockEnable())
mShakeDetector.start();//FIXME需要测试
} else if(state == TelephonyManager.CALL_STATE_RINGING) {
mKeyguardPanelManager.hidePanel();
if (mPrefsManager.isKeyguardShockEnable())
mShakeDetector.stop();
}
super.onCallStateChanged(state, incomingNumber);
}
};
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "onStartCommand()");
if (intent != null) {
String action = intent.getAction();
int controlType = intent.getIntExtra(CONTROL_TYPE_KEY,
CONTROL_TYPE_DEFAULT);
if (CONTROL_TYPE_START == controlType)
handleStart(action);
else if (CONTROL_TYPE_STOP == controlType)
handleStop(action);
else if (controlType == CONTROL_TYPE_SCREEN_ON)
handleScreenOn();
else if (controlType == CONTROL_TYPE_SCREEN_OFF)
handleScreenOff();
else if (controlType == CONTROL_TYPE_USER_PRESENT)
handleUserPresent();
} else {
Log.v(TAG, "onStartCommand() restart after kill");
handleStart(ACTION_PANEL_SERVICE);
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
releaseData();
}
private void releaseData() {
stopLauncherPanel();
stopKeyguardPanel();
flashController = null;
mActivityManager = null;
mVibrator = null;
mSystemReceiver = null;
mPrefsManager = null;
//关闭监听
if(mTelephonyManager != null) {
mTelephonyManager.listen(mPhoneStateListener
, PhoneStateListener.LISTEN_NONE);
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
/*
* 调用时机 1. 重启的时候:BootComplete 2. 设置:SettingActivity
*
* * 需要根据preference值,因为可能是重启时的调用
*/
private void handleStart(String action) {
if (!isLauncherServiceAlive && !isKeyguardServiceAlive) {
Log.v(TAG, "start receiver");
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
mSystemReceiver = new SystemReceiver();
FlashApp.getContext().registerReceiver(mSystemReceiver, filter);
//foreground
startForeground(1, new Notification());
}
if (ACTION_LAUNCHER.equals(action))
startLauncherPanel();
else if (ACTION_KEYGUARD.equals(action))
startKeyguardPanel();
else {
if (mPrefsManager.isLauncherPanelShown())
startLauncherPanel();
if (mPrefsManager.isKeyguardPanelShown())
startKeyguardPanel();
}
}
/*
* 调用时机 1. 设置 * 覆盖安装之后service没有起来,没有执行过start,这个时候不能执行unregisterReceiver
*/
private void handleStop(String action) {
if (ACTION_LAUNCHER.equals(action))
stopLauncherPanel();
else if (ACTION_KEYGUARD.equals(action))
stopKeyguardPanel();
else {
// 暂时未使用
stopLauncherPanel();
stopKeyguardPanel();
}
if (!isLauncherServiceAlive && !isKeyguardServiceAlive) {
if (mSystemReceiver != null)
FlashApp.getContext().unregisterReceiver(mSystemReceiver);
mSystemReceiver = null;
stopForeground(true);
stopSelf();
}
}
/*
* 调用时机: 1. 屏幕点亮的时候:(仍然处在锁屏幕) 2. 呼吸灯上滑解锁的时候:(发生在user_present之后)
*
* 不在锁屏都关闭:电话的时候判断状态 * 如果在锁屏界面则打开锁屏panel
* 如果lisense过期,关闭Keyguard
*
* 如果在锁屏界面才监听电话
*/
private void handleScreenOn() {
// initLisense();
if (!isKeyguardScreen()) {
if (isKeyguardServiceAlive)
mKeyguardPanelManager.hidePanel();
} else {
if (isKeyguardServiceAlive) {
if(isTelephoneCalling()) {
mKeyguardPanelManager.hidePanel();
} else {
mKeyguardPanelManager.showPanel();//灭屏、亮屏都show
if (mPrefsManager.isKeyguardShockEnable())
mShakeDetector.start();
}
//锁屏界面需要监听电话状态
mTelephonyManager.listen(mPhoneStateListener
, PhoneStateListener.LISTEN_CALL_STATE);
}
}
//FIXME 需要优化的策略,原则1. 尽量节省资源 2. 不要影响效果
if(!flashController.isFlashOn()) {
flashController.initCameraSync();
}
}
/*
* 调用时机: 1. 灭屏的时候 2. 通话的时候
*
* * 灭屏幕的时候是否会被杀掉,杀掉之后的处理方式
*/
private void handleScreenOff() {
if (isLauncherServiceAlive && !isTelephoneCalling()) {
mLaucherRefreshTimer.cancelLauncherRefreshTask();
hideLauncherPanel();
}
if (isKeyguardServiceAlive) {
mShakeDetector.stop();
if (!isTelephoneCalling())
mKeyguardPanelManager.showPanel();
//关闭监听
if(mTelephonyManager != null) {
mTelephonyManager.listen(mPhoneStateListener
, PhoneStateListener.LISTEN_NONE);
}
}
//FIXME 需要优化的策略
if(!flashController.isFlashOn()) {
flashController.releaseCamera();
}
}
/*
* 调用时机: 1. 解锁的时候:先screen_on再user_present 2.
* 直接滑动呼吸灯解锁:先user_present再screen_on
*
* * 覆盖安装会kill掉process,不会调用onDestroy,service也不会自动重启
*/
private void handleUserPresent() {
if (isKeyguardServiceAlive) {
mKeyguardPanelManager.hidePanel();
if (mPrefsManager.isKeyguardShockEnable())
mShakeDetector.stop();
//关闭监听
if(mTelephonyManager != null) {
mTelephonyManager.listen(mPhoneStateListener
, PhoneStateListener.LISTEN_NONE);
}
}
mLaucherRefreshTimer.startLauncherRefreshTask();
}
private void startLauncherPanel() {
if (!isLauncherServiceAlive) {
isLauncherServiceAlive = true;
if (mLauncherPanelManager == null)
mLauncherPanelManager = new LauncherPanelManager();
if (!isKeyguardScreen()) {
// 如果覆盖安装了,这个时候启动LauncherPanel不应该开始轮询,而应该等到user_present的时候
mLaucherRefreshTimer.startLauncherRefreshTask();
}
}
}
private void stopLauncherPanel() {
if (isLauncherServiceAlive) {
isLauncherServiceAlive = false;
mLaucherRefreshTimer.cancelLauncherRefreshTask();
// closePanel
mLauncherPanelManager.closePanel();
mLauncherPanelManager = null;
// stopService
}
}
/*
* 如果lisense过期,关闭Launcher
*/
private void requestShowLauncherPanel() {
// 当前界面是桌面,且没有悬浮窗显示,则创建悬浮窗。postRunnable的原因是因为timerTask
mHandler.post(new Runnable() {
@Override
public void run() {
if (isLauncherServiceAlive) {
showLauncherPanel();
}
}
});
}
// 灭屏幕的时候应该是cancel掉任务,present的时候应该是show那个view,ok了之后启动桌面轮询task
private void requestHideLauncherPanel() {
// 当前界面不是桌面,且有悬浮窗显示,则移除悬浮窗。
mHandler.post(new Runnable() {
@Override
public void run() {
if (isLauncherServiceAlive) {
hideLauncherPanel();
}
}
});
}
private void showLauncherPanel() {
mLauncherPanelManager.showPanel();
isHomeLastInterval = true;
}
private void hideLauncherPanel() {
mLauncherPanelManager.hidePanel();
isHomeLastInterval = false;
}
/*
* 调用时机: 1. 打开设置项 2. 开机启动的时候
*/
private void startKeyguardPanel() {
if (isKeyguardServiceAlive == false) {
if (mKeyguardPanelManager == null)
mKeyguardPanelManager = new KeyguardPanelManager();
isKeyguardServiceAlive = true;
}
}
/*
* 调用时机 1. 关闭设置项的时候 2.长按移除的时候
*/
private void stopKeyguardPanel() {
if (isKeyguardServiceAlive) {
isKeyguardServiceAlive = false;
mKeyguardPanelManager.closePanel();
mKeyguardPanelManager = null;
mShakeDetector.stop();
mShakeDetector.removeOnShakeListener(this);
}
}
private boolean isHome() {
List<RunningTaskInfo> tasks = mActivityManager.getRunningTasks(1);
return getHomes().contains(tasks.get(0).topActivity.getClassName());
}
private List<String> getHomes() {
List<String> names = new ArrayList<String>();
PackageManager packageManager = this.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(
intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo ri : resolveInfo) {
names.add(ri.activityInfo.name);
}
return names;
}
@Override
public void onShake() {
mVibrator.vibrate(200);
flashController.toggleFlash();
flashController.notifyFlashLevelChanged();//这是一个全局的操作,虽然现在只是keyguard在observer中
}
private boolean isTelephoneCalling() {
if (mTelephonyManager == null)
mTelephonyManager = (TelephonyManager) FlashApp.getContext()
.getSystemService(Context.TELEPHONY_SERVICE);
boolean calling = false;
int status = mTelephonyManager.getCallState();
if (status == TelephonyManager.CALL_STATE_OFFHOOK
|| status == TelephonyManager.CALL_STATE_RINGING) {
calling = true;
}
return calling;
}
private boolean isKeyguardScreen() {
return mKeyguardManager.isKeyguardLocked();
}
private class LauncherRefreshTimer extends Timer {
private Object TASK_LOCK = new Object();
boolean isLauncherTaskCanceledOrStoped = false;
long delay;
long period;
public LauncherRefreshTimer(long delay, long period) {
this.delay = delay;
this.period = period;
isLauncherTaskCanceledOrStoped = false;
}
void startLauncherRefreshTask() {
synchronized (TASK_LOCK) {
if(isLauncherServiceAlive) {
isLauncherTaskCanceledOrStoped = false;
this.scheduleAtFixedRate(getLauncherRefreshTask(), delay, period);
}
}
}
void cancelLauncherRefreshTask() {
synchronized (TASK_LOCK) {
isLauncherTaskCanceledOrStoped = true;
}
}
private TimerTask getLauncherRefreshTask() {
return new TimerTask() {
@Override
public void run() {
synchronized (TASK_LOCK) {
if (isLauncherTaskCanceledOrStoped) {
requestHideLauncherPanel();
this.cancel();
} else {
boolean isHome = isHome();
if (isHome && isHomeLastInterval == false)
requestShowLauncherPanel();
else if(isHome == false && isHomeLastInterval == true)
requestHideLauncherPanel();
}
}
}
};
}
}
private void initLisense() {
boolean purchased = flashController.isPurchased();
if(!purchased) {
lisenseManager = new MLisenseMangaer(this);
lisenseManager.bindRemoteService();
}
}
@Override
public void onRemoteServiceConnected() {
int lisenseState = lisenseManager.doRemoteCheck();
flashController.setLisenseState(lisenseState);
lisenseManager.unbindRemoteService();
if(flashController.islisenseEnable() == false) {
stopKeyguardPanel();
stopLauncherPanel();
}
}
@Override
public void onRemoteServiceDisconnected() {
lisenseManager = null;
}
}
|
快速锁屏,再快速打开,原先的方式可能会导致refreshTask没有被正确终止,导致有多个task同时运行的情况。经过修改之后,会正确终止。但是会出现闪动的情况
|
src/com/hellodev/lightme/service/PanelService.java
|
快速锁屏,再快速打开,原先的方式可能会导致refreshTask没有被正确终止,导致有多个task同时运行的情况。经过修改之后,会正确终止。但是会出现闪动的情况
|
|
Java
|
apache-2.0
|
bd7e1c6a58e7cc271ed6ab84cd9586f2905d1804
| 0
|
dowrow/Practica1FAA,garnachod/Practica2FAA
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package datos;
import com.csvreader.CsvReader;
import java.util.ArrayList;
import java.util.Arrays;
import particionado.Particion;
public class Datos {
/* Lista de atributos del fichero */
private ArrayList<TiposDeAtributos> tipoAtributos;
/* Lista de nombres de los campos del fichero */
private ArrayList<String> nombreCampos;
/* Datos del fichero */
private Elemento datos[][];
/* Posibles clases */
private ArrayList<String> clases;
int nDatosCopiados = 0;
/*
* Constructor
* @param numDatos Número de filas que contiene el fichero
* @param tipos Tipos de columnas que contiene el fichero
*/
public Datos(int numDatos, ArrayList<TiposDeAtributos> tipos) {
this.tipoAtributos = tipos;
this.datos = new Elemento[numDatos][tipos.size()];
this.clases = new ArrayList<>();
}
public Datos extraeDatosTrain(Particion idx) {
return null;
}
public Datos extraeDatosTest(Particion idx) {
return null;
}
// 3 Filas: nº datos, nombres de campos, tipos de atributos [Nominal o Continuo]
// Resto de filas: Conjunto de datos, uno por fila y campos separados por comas
public static Datos cargaDeFichero(String nombreDeFichero) {
CsvReader ficheroCSV;
ArrayList<String> nombreCampos;
ArrayList<String> tiposString;
ArrayList<TiposDeAtributos> tipos = new ArrayList<>();
ArrayList<String> elementosString;
try {
ficheroCSV = new CsvReader(nombreDeFichero);
// Lee nº datos
ficheroCSV.readRecord();
int numFilas = Integer.parseInt(ficheroCSV.get(0));
// Lee nombres campos
ficheroCSV.readRecord();
nombreCampos = new ArrayList<>(Arrays.asList(ficheroCSV.getValues()));
// Lee tipos de atributos como cadenas
ficheroCSV.readRecord();
tiposString = new ArrayList<>(Arrays.asList(ficheroCSV.getValues()));
// Pasa cadenas a elementos de la enumeración
for (String cadena: tiposString) {
tipos.add(TiposDeAtributos.valueOf(cadena));
}
// Crea objeto a devolver
Datos objetoDatos = new Datos(numFilas, tipos);
objetoDatos.setNombreCampos(nombreCampos);
// Introducimos filas
while (ficheroCSV.readRecord()) {
// Leemos todos los elementos de una fila como cadenas
elementosString = new ArrayList<>(Arrays.asList(ficheroCSV.getValues()));
// Para cada cadena leída creamos un Elemento
// y lo introducimos en la matriz
int i=0;
Elemento elemCopy[] = new Elemento[objetoDatos.getTamColumn()];
for(String elementoString: elementosString){
TiposDeAtributos tipo = objetoDatos.getTipoAtributosAt(i);
Elemento elemento = ElementoFactory.crear(tipo, elementoString);
elemCopy[i] = elemento;
i++;
}
objetoDatos.addLineaDatos(elemCopy);
// Además, guardamos la clase (última columna)
String clase = elemCopy[elemCopy.length - 1].getValorNominal();
ArrayList<String> clasesObjeto = objetoDatos.getClases();
if (!clasesObjeto.contains(clase)) {
clasesObjeto.add(clase);
objetoDatos.setClases(clasesObjeto);
}
}
return objetoDatos;
} catch (Exception e) {
System.out.println("ERROR: " + e + " " + e.getLocalizedMessage() + " " + e.getMessage() + " " + e.getStackTrace());
return null;
}
}
/*
* GETTERS & SETTERS
*/
/**
* @return the tipoAtributos
*/
public ArrayList<TiposDeAtributos> getTipoAtributos() {
return this.tipoAtributos;
}
/**
* @return TiposDeAtributos en la posicion pasada por parametros
*/
public TiposDeAtributos getTipoAtributosAt(int position){
return this.tipoAtributos.get(position);
}
/**
* @param tipoAtributos the tipoAtributos to set
*/
public void setTipoAtributos(ArrayList<TiposDeAtributos> tipoAtributos) {
this.tipoAtributos = tipoAtributos;
}
/**
* @return the nombreCampos
*/
public ArrayList<String> getNombreCampos() {
return nombreCampos;
}
public int getTamColumn(){
return this.nombreCampos.size();
}
/**
* @param nombreCampos the nombreCampos to set
*/
public void setNombreCampos(ArrayList<String> nombreCampos) {
this.nombreCampos = nombreCampos;
}
public void addLineaDatos(Elemento elem[]){
int nDatos = this.nDatosCopiados;
for(int i = 0; i <elem.length; i++ ){
this.datos[nDatos][i] = elem[i];
}
this.nDatosCopiados++;
}
/**
* @return the datos
*/
public Elemento[][] getDatos() {
return datos;
}
/**
* @return the clases
*/
public ArrayList<String> getClases() {
return clases;
}
/**
* @param clases the clases to set
*/
public void setClases(ArrayList<String> clases) {
this.clases = clases;
}
}
|
Practica1FAA/src/datos/Datos.java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package datos;
import com.csvreader.CsvReader;
import java.util.ArrayList;
import java.util.Arrays;
import particionado.Particion;
public class Datos {
/* Lista de atributos del fichero */
private ArrayList<TiposDeAtributos> tipoAtributos;
/* Lista de nombres de los campos del fichero */
private ArrayList<String> nombreCampos;
/* Datos del fichero */
private Elemento datos[][];
/* Posibles clases */
private ArrayList<String> clases;
int nDatosCopiados = 0;
/*
* Constructor
* @param numDatos Número de filas que contiene el fichero
* @param tipos Tipos de columnas que contiene el fichero
*/
public Datos(int numDatos, ArrayList<TiposDeAtributos> tipos) {
this.tipoAtributos = tipos;
this.datos = new Elemento[numDatos][tipos.size()];
}
public Datos extraeDatosTrain(Particion idx) {
return null;
}
public Datos extraeDatosTest(Particion idx) {
return null;
}
// 3 Filas: nº datos, nombres de campos, tipos de atributos [Nominal o Continuo]
// Resto de filas: Conjunto de datos, uno por fila y campos separados por comas
public static Datos cargaDeFichero(String nombreDeFichero) {
CsvReader ficheroCSV;
ArrayList<String> nombreCampos;
ArrayList<String> tiposString;
ArrayList<TiposDeAtributos> tipos = new ArrayList<>();
ArrayList<String> elementosString;
try {
ficheroCSV = new CsvReader(nombreDeFichero);
// Lee nº datos
ficheroCSV.readRecord();
int numFilas = Integer.parseInt(ficheroCSV.get(0));
// Lee nombres campos
ficheroCSV.readRecord();
nombreCampos = new ArrayList<>(Arrays.asList(ficheroCSV.getValues()));
// Lee tipos de atributos como cadenas
ficheroCSV.readRecord();
tiposString = new ArrayList<>(Arrays.asList(ficheroCSV.getValues()));
// Pasa cadenas a elementos de la enumeración
for (String cadena: tiposString) {
tipos.add(TiposDeAtributos.valueOf(cadena));
}
// Crea objeto a devolver
Datos objetoDatos = new Datos(numFilas, tipos);
objetoDatos.setNombreCampos(nombreCampos);
// Introducimos filas
while (ficheroCSV.readRecord()) {
// Leemos todos los elementos de una fila como cadenas
elementosString = new ArrayList<>(Arrays.asList(ficheroCSV.getValues()));
// Para cada cadena leída creamos un Elemento
// y lo introducimos en la matriz
int i=0;
Elemento elemCopy[] = new Elemento[objetoDatos.getTamColumn()];
for(String elementoString: elementosString){
TiposDeAtributos tipo = objetoDatos.getTipoAtributosAt(i);
Elemento elemento = ElementoFactory.crear(tipo, elementoString);
elemCopy[i] = elemento;
i++;
}
objetoDatos.addLineaDatos(elemCopy);
// Además, guardamos la clase (última columna)
String clase = elemCopy[elemCopy.length - 1].getValorNominal();
if (!objetoDatos.clases.contains(clase))
objetoDatos.getClases().add(clase);
}
return objetoDatos;
} catch (Exception e) {
return null;
}
}
/*
* GETTERS & SETTERS
*/
/**
* @return the tipoAtributos
*/
public ArrayList<TiposDeAtributos> getTipoAtributos() {
return this.tipoAtributos;
}
/**
* @return TiposDeAtributos en la posicion pasada por parametros
*/
public TiposDeAtributos getTipoAtributosAt(int position){
return this.tipoAtributos.get(position);
}
/**
* @param tipoAtributos the tipoAtributos to set
*/
public void setTipoAtributos(ArrayList<TiposDeAtributos> tipoAtributos) {
this.tipoAtributos = tipoAtributos;
}
/**
* @return the nombreCampos
*/
public ArrayList<String> getNombreCampos() {
return nombreCampos;
}
public int getTamColumn(){
return this.nombreCampos.size();
}
/**
* @param nombreCampos the nombreCampos to set
*/
public void setNombreCampos(ArrayList<String> nombreCampos) {
this.nombreCampos = nombreCampos;
}
public void addLineaDatos(Elemento elem[]){
int nDatos = this.nDatosCopiados;
for(int i = 0; i <elem.length; i++ ){
this.datos[nDatos][i] = elem[i];
}
this.nDatosCopiados++;
}
/**
* @return the datos
*/
public Elemento[][] getDatos() {
return datos;
}
/**
* @return the clases
*/
public ArrayList<String> getClases() {
return clases;
}
}
|
Inicializado arraylist de clases x)
|
Practica1FAA/src/datos/Datos.java
|
Inicializado arraylist de clases x)
|
|
Java
|
apache-2.0
|
23ecf0a9778a8b24674fa0753812970910394eaf
| 0
|
ksokol/carldav
|
/*
* Copyright 2005-2006 Open Source Applications Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.unitedinternet.cosmo.dav.caldav;
import java.io.IOException;
import java.io.StringReader;
import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.data.ParserException;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.model.component.VTimeZone;
import org.unitedinternet.cosmo.calendar.util.CalendarBuilderDispenser;
import org.unitedinternet.cosmo.dav.CosmoDavException;
import org.unitedinternet.cosmo.dav.property.WebDavProperty;
/**
* Helper class for extracting a <code>VTimeZone</code> from an iCalendar
* object.
*/
public class TimeZoneExtractor {
/**
* Creates an instance of <code>VTimeZone</code> from an
* iCalendar string.
*
* The iCalendar string must include an enclosing VCALENDAR object
* and exactly one enclosed VTIMEZONE component. All components,
* properties and parameters are validated according to RFC 2445.
*
* @param ical the iCalendar string to parse
* @return the <code>VTimeZone</code> representing the extracted
* timezone, or <code>null</code> if the iCalendar string is
* <code>null</code>
* @throws CosmoDavException if the iCalendar string cannot be parsed or is
* not a valid iCalendar object containing a single VTIMEZONE component
*/
public static VTimeZone extract(String ical)
throws CosmoDavException {
Calendar calendar = extractInCalendar(ical);
if (calendar == null) {
return null;
}
return (VTimeZone) calendar.getComponent(Component.VTIMEZONE);
}
/**
* Creates an instance of <code>VTimeZone</code> from an
* iCalendar string.
*
* The iCalendar string must include an enclosing VCALENDAR object
* and exactly one enclosed VTIMEZONE component. All components,
* properties and parameters are validated according to RFC 2445.
*
* @param ical the iCalendar string to parse
* @return a <code>Calendar</code> containing a single
* <code>VTimeZone</code> representing the extracted timezone, or
* code>null</code> if the iCalendar string is <code>null</code>
* @throws CosmoDavException if the iCalendar string cannot be parsed or is
* not a valid iCalendar object containing a single VTIMEZONE component
*/
public static Calendar extractInCalendar(String ical)
throws CosmoDavException {
if (ical == null) {
return null;
}
Calendar calendar;
try {
CalendarBuilder builder =
CalendarBuilderDispenser.getCalendarBuilder();
calendar = builder.build(new StringReader(ical));
CalendarClientsAdapter.adaptTimezoneCalendarComponent(calendar);
calendar.validate(true);
} catch (IOException e) {
throw new CosmoDavException(e);
} catch (ParserException e) {
throw new InvalidCalendarDataException("Calendar object not parseable: " + e.getMessage());
} catch (ValidationException e) {
throw new InvalidCalendarDataException("Invalid calendar object: " + e.getMessage());
}
if (calendar.getComponents().size() > 1) {
throw new InvalidCalendarDataException("Calendar object contains more than one VTIMEZONE component");
}
VTimeZone vtz = (VTimeZone)
calendar.getComponent(Component.VTIMEZONE);
if (vtz == null) {
throw new InvalidCalendarDataException("Calendar object must contain a VTIMEZONE component");
}
return calendar;
}
}
|
src/main/java/org/unitedinternet/cosmo/dav/caldav/TimeZoneExtractor.java
|
/*
* Copyright 2005-2006 Open Source Applications Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.unitedinternet.cosmo.dav.caldav;
import java.io.IOException;
import java.io.StringReader;
import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.data.ParserException;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.model.component.VTimeZone;
import org.unitedinternet.cosmo.calendar.util.CalendarBuilderDispenser;
import org.unitedinternet.cosmo.dav.CosmoDavException;
import org.unitedinternet.cosmo.dav.property.WebDavProperty;
/**
* Helper class for extracting a <code>VTimeZone</code> from an iCalendar
* object.
*/
public class TimeZoneExtractor {
/**
* Creates an instance of <code>VTimeZone</code> from a
* DAV property value.
*
* The property value must be an iCalendar string. The further
* requirements for a valid time zone are as per
* {@link #extractTimeZone(String)}.
*
* @param prop the <code>WebDavProperty</code> containing the
* timezone
* @return a <code>Calendar</code> containing a single
* <code>VTimeZone</code> representing the extracted timezone, or
* <code>null</code> if the property or its value is <code>null</code>
* @throws CosmoDavException if the property value cannot be parsed or is not
* a valid iCalendar object containing a single VTIMEZONE component
*/
public static Calendar extract(WebDavProperty prop)
throws CosmoDavException {
if (prop == null) {
return null;
}
if (prop.getValue() == null) {
return null;
}
return extractInCalendar(prop.getValueText());
}
/**
* Creates an instance of <code>VTimeZone</code> from an
* iCalendar string.
*
* The iCalendar string must include an enclosing VCALENDAR object
* and exactly one enclosed VTIMEZONE component. All components,
* properties and parameters are validated according to RFC 2445.
*
* @param ical the iCalendar string to parse
* @return the <code>VTimeZone</code> representing the extracted
* timezone, or <code>null</code> if the iCalendar string is
* <code>null</code>
* @throws CosmoDavException if the iCalendar string cannot be parsed or is
* not a valid iCalendar object containing a single VTIMEZONE component
*/
public static VTimeZone extract(String ical)
throws CosmoDavException {
Calendar calendar = extractInCalendar(ical);
if (calendar == null) {
return null;
}
return (VTimeZone) calendar.getComponent(Component.VTIMEZONE);
}
/**
* Creates an instance of <code>VTimeZone</code> from an
* iCalendar string.
*
* The iCalendar string must include an enclosing VCALENDAR object
* and exactly one enclosed VTIMEZONE component. All components,
* properties and parameters are validated according to RFC 2445.
*
* @param ical the iCalendar string to parse
* @return a <code>Calendar</code> containing a single
* <code>VTimeZone</code> representing the extracted timezone, or
* code>null</code> if the iCalendar string is <code>null</code>
* @throws CosmoDavException if the iCalendar string cannot be parsed or is
* not a valid iCalendar object containing a single VTIMEZONE component
*/
public static Calendar extractInCalendar(String ical)
throws CosmoDavException {
if (ical == null) {
return null;
}
Calendar calendar;
try {
CalendarBuilder builder =
CalendarBuilderDispenser.getCalendarBuilder();
calendar = builder.build(new StringReader(ical));
CalendarClientsAdapter.adaptTimezoneCalendarComponent(calendar);
calendar.validate(true);
} catch (IOException e) {
throw new CosmoDavException(e);
} catch (ParserException e) {
throw new InvalidCalendarDataException("Calendar object not parseable: " + e.getMessage());
} catch (ValidationException e) {
throw new InvalidCalendarDataException("Invalid calendar object: " + e.getMessage());
}
if (calendar.getComponents().size() > 1) {
throw new InvalidCalendarDataException("Calendar object contains more than one VTIMEZONE component");
}
VTimeZone vtz = (VTimeZone)
calendar.getComponent(Component.VTIMEZONE);
if (vtz == null) {
throw new InvalidCalendarDataException("Calendar object must contain a VTIMEZONE component");
}
return calendar;
}
}
|
removed unused method extract(WebDavProperty) from TimeZoneExtractor
|
src/main/java/org/unitedinternet/cosmo/dav/caldav/TimeZoneExtractor.java
|
removed unused method extract(WebDavProperty) from TimeZoneExtractor
|
|
Java
|
apache-2.0
|
10c5decc1cb35285e11ef8c57e8f8b5d828c4ab4
| 0
|
sutaakar/drools,sutaakar/drools,reynoldsm88/drools,kedzie/drools-android,prabasn/drools,mrietveld/drools,jomarko/drools,lanceleverich/drools,ThiagoGarciaAlves/drools,ThomasLau/drools,prabasn/drools,liupugong/drools,jomarko/drools,romartin/drools,reynoldsm88/drools,jiripetrlik/drools,sotty/drools,sotty/drools,manstis/drools,liupugong/drools,292388900/drools,lanceleverich/drools,Buble1981/MyDroolsFork,ThiagoGarciaAlves/drools,romartin/drools,TonnyFeng/drools,mrrodriguez/drools,iambic69/drools,droolsjbpm/drools,jiripetrlik/drools,liupugong/drools,ChallenHB/drools,droolsjbpm/drools,rajashekharmunthakewill/drools,292388900/drools,amckee23/drools,mrietveld/drools,rajashekharmunthakewill/drools,lanceleverich/drools,Buble1981/MyDroolsFork,manstis/drools,jomarko/drools,292388900/drools,vinodkiran/drools,kedzie/drools-android,sotty/drools,amckee23/drools,liupugong/drools,jomarko/drools,lanceleverich/drools,kedzie/drools-android,prabasn/drools,pwachira/droolsexamples,iambic69/drools,jiripetrlik/drools,ngs-mtech/drools,amckee23/drools,mrietveld/drools,sotty/drools,droolsjbpm/drools,prabasn/drools,ChallenHB/drools,HHzzhz/drools,ThomasLau/drools,winklerm/drools,OnePaaS/drools,Buble1981/MyDroolsFork,OnePaaS/drools,kevinpeterson/drools,ngs-mtech/drools,mrietveld/drools,droolsjbpm/drools,ThomasLau/drools,OnePaaS/drools,jomarko/drools,TonnyFeng/drools,292388900/drools,jiripetrlik/drools,TonnyFeng/drools,ngs-mtech/drools,sutaakar/drools,romartin/drools,rajashekharmunthakewill/drools,romartin/drools,manstis/drools,mrrodriguez/drools,rajashekharmunthakewill/drools,rajashekharmunthakewill/drools,ChallenHB/drools,manstis/drools,vinodkiran/drools,Buble1981/MyDroolsFork,vinodkiran/drools,reynoldsm88/drools,iambic69/drools,mrietveld/drools,ngs-mtech/drools,mrrodriguez/drools,sutaakar/drools,HHzzhz/drools,amckee23/drools,jiripetrlik/drools,iambic69/drools,ChallenHB/drools,kedzie/drools-android,ThomasLau/drools,ThiagoGarciaAlves/drools,ThiagoGarciaAlves/drools,vinodkiran/drools,ThomasLau/drools,winklerm/drools,prabasn/drools,reynoldsm88/drools,HHzzhz/drools,kevinpeterson/drools,reynoldsm88/drools,mrrodriguez/drools,OnePaaS/drools,TonnyFeng/drools,mrrodriguez/drools,winklerm/drools,TonnyFeng/drools,manstis/drools,vinodkiran/drools,kevinpeterson/drools,292388900/drools,sotty/drools,romartin/drools,liupugong/drools,iambic69/drools,HHzzhz/drools,winklerm/drools,amckee23/drools,kevinpeterson/drools,kevinpeterson/drools,ngs-mtech/drools,droolsjbpm/drools,winklerm/drools,HHzzhz/drools,kedzie/drools-android,ChallenHB/drools,lanceleverich/drools,OnePaaS/drools,sutaakar/drools,ThiagoGarciaAlves/drools
|
package org.drools.workbench.models.guided.template.backend;
import org.drools.compiler.kie.builder.impl.FormatConversionResult;
import org.drools.compiler.kie.builder.impl.FormatConverter;
import org.drools.workbench.models.commons.backend.BaseConverter;
import org.drools.workbench.models.datamodel.oracle.PackageDataModelOracle;
import org.drools.workbench.models.datamodel.oracle.PackageDataModelOracle;
import org.drools.workbench.models.guided.template.shared.TemplateModel;
public class GuidedRuleTemplateConverter extends BaseConverter implements FormatConverter {
@Override
public FormatConversionResult convert( String name,
byte[] input ) {
String xml = new String( input );
TemplateModel model = (TemplateModel) BRDRTXMLPersistence.getInstance().unmarshal( xml, null );
String drl = new StringBuilder().append( BRDRTPersistence.getInstance().marshal( model ) ).toString();
return new FormatConversionResult( getDestinationName( name, model.hasDSLSentences() ), drl.getBytes() );
}
}
|
drools-workbench-models/drools-workbench-models-guided-template/src/main/java/org/drools/workbench/models/guided/template/backend/GuidedRuleTemplateConverter.java
|
package org.drools.workbench.models.guided.template.backend;
import org.drools.compiler.kie.builder.impl.FormatConversionResult;
import org.drools.compiler.kie.builder.impl.FormatConverter;
import org.drools.workbench.models.commons.backend.BaseConverter;
import org.drools.workbench.models.datamodel.oracle.PackageDataModelOracle;
import org.drools.workbench.models.datamodel.oracle.PackageDataModelOracle;
import org.drools.workbench.models.guided.template.shared.TemplateModel;
public class GuidedRuleTemplateConverter extends BaseConverter implements FormatConverter {
private final PackageDataModelOracle dmo;
public GuidedRuleTemplateConverter(final PackageDataModelOracle dmo) {
this.dmo = dmo;
}
@Override
public FormatConversionResult convert( String name,
byte[] input ) {
String xml = new String( input );
TemplateModel model = (TemplateModel) BRDRTXMLPersistence.getInstance().unmarshal( xml, dmo );
String drl = new StringBuilder().append( BRDRTPersistence.getInstance().marshal( model ) ).toString();
return new FormatConversionResult( getDestinationName( name, model.hasDSLSentences() ), drl.getBytes() );
}
}
|
BZ-1013214 - Guided Rule Template validation causes error
|
drools-workbench-models/drools-workbench-models-guided-template/src/main/java/org/drools/workbench/models/guided/template/backend/GuidedRuleTemplateConverter.java
|
BZ-1013214 - Guided Rule Template validation causes error
|
|
Java
|
apache-2.0
|
00ae0f9b9f67a09acaa91db6679ec57fa750a209
| 0
|
goettl79/mesos-plugin,infonova/mesos-plugin,goettl79/mesos-plugin,infonova/mesos-plugin
|
/*
* Copyright 2013 Twitter, Inc. and other contributors.
* 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.jenkinsci.plugins.mesos;
import hudson.EnvVars;
import hudson.Extension;
import hudson.init.InitMilestone;
import hudson.init.Initializer;
import hudson.model.*;
import hudson.model.Node.Mode;
import hudson.slaves.*;
import hudson.slaves.NodeProvisioner.PlannedNode;
import hudson.util.DescribableList;
import hudson.util.FormValidation;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import jenkins.model.Jenkins;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.mesos.MesosNativeLibrary;
import org.apache.mesos.Protos.ContainerInfo.DockerInfo.Network;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
public class MesosCloud extends Cloud {
private String nativeLibraryPath;
private String master;
private String description;
private String frameworkName;
private String slavesUser;
private String principal;
private String secret;
private final boolean checkpoint; // Set true to enable checkpointing. False by default.
private boolean onDemandRegistration; // If set true, this framework disconnects when there are no builds in the queue and re-registers when there are.
private String jenkinsURL;
private int provisioningThreshold;
private int provisioningCount = 0;
// Find the default values for these variables in
// src/main/resources/org/jenkinsci/plugins/mesos/MesosCloud/config.jelly.
private List<MesosSlaveInfo> slaveInfos;
private static String staticMaster;
private static final Logger LOGGER = Logger.getLogger(MesosCloud.class.getName());
private static volatile boolean nativeLibraryLoaded = false;
/**
* We want to start the Mesos scheduler as part of the initialization of Jenkins
* and after the cloud class values have been restored from persistence.If this is
* the very first time, this method will be NOOP as MesosCloud is not registered yet.
*/
@Initializer(after=InitMilestone.JOB_LOADED)
public static void init() {
Jenkins jenkins = Jenkins.getInstance();
List<Node> slaves = jenkins.getNodes();
// Turning the AUTOMATIC_SLAVE_LAUNCH flag off because the below slave removals
// causes computer launch in other slaves that have not been removed yet.
// To study how a slave removal updates the entire list, one can refer to
// Hudson NodeProvisioner class and follow this method chain removeNode() ->
// setNodes() -> updateComputerList() -> updateComputer().
Jenkins.AUTOMATIC_SLAVE_LAUNCH = false;
for (Node n : slaves) {
//Remove all slaves that were persisted when Jenkins shutdown.
if (n instanceof MesosSlave) {
((MesosSlave)n).terminate();
}
}
// Turn it back on for future real slaves.
Jenkins.AUTOMATIC_SLAVE_LAUNCH = true;
for (Cloud c : jenkins.clouds) {
if( c instanceof MesosCloud) {
// Register mesos framework on init, if on demand registration is not enabled.
if (!((MesosCloud) c).isOnDemandRegistration()) {
((MesosCloud)c).restartMesos();
}
}
}
}
@DataBoundConstructor
public MesosCloud(
String nativeLibraryPath,
String master,
String description,
String frameworkName,
String slavesUser,
String principal,
String secret,
List<MesosSlaveInfo> slaveInfos,
boolean checkpoint,
boolean onDemandRegistration,
String jenkinsURL,
int provisioningThreshold) throws NumberFormatException {
super("MesosCloud");
this.nativeLibraryPath = nativeLibraryPath;
this.master = master;
this.description = description;
this.frameworkName = frameworkName;
this.slavesUser = slavesUser;
this.principal = principal;
this.secret = secret;
this.slaveInfos = slaveInfos;
this.checkpoint = checkpoint;
this.onDemandRegistration = onDemandRegistration;
this.setJenkinsURL(jenkinsURL);
this.provisioningThreshold = provisioningThreshold;
if(!onDemandRegistration) {
JenkinsScheduler.SUPERVISOR_LOCK.lock();
try {
restartMesos();
} finally {
JenkinsScheduler.SUPERVISOR_LOCK.unlock();
}
}
}
// Since MesosCloud is used as a key to a Hashmap, we need to set equals/hashcode
// or lookups won't work if any fields are changed. Use master string as the key since
// the rest of this code assumes it is unique among the Cloud objects.
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MesosCloud that = (MesosCloud) o;
if (master != null ? !master.equals(that.master) : that.master != null) return false;
return true;
}
@Override
public int hashCode() {
return master != null ? master.hashCode() : 0;
}
public void restartMesos() {
if(!nativeLibraryLoaded) {
// First, we attempt to load the library from the given path.
// If unsuccessful, we attempt to load using 'MesosNativeLibrary.load()'.
try {
MesosNativeLibrary.load(nativeLibraryPath);
} catch (UnsatisfiedLinkError error) {
LOGGER.warning("Failed to load native Mesos library from '" + nativeLibraryPath +
"': " + error.getMessage());
MesosNativeLibrary.load();
}
nativeLibraryLoaded = true;
}
// Default to root URL in Jenkins global configuration.
String jenkinsRootURL = Jenkins.getInstance().getRootUrl();
// If 'jenkinsURL' parameter is provided in mesos plugin configuration, then that should take precedence.
if(StringUtils.isNotBlank(jenkinsURL)) {
jenkinsRootURL = expandJenkinsUrlWithEnvVars();
}
// Restart the scheduler if the master has changed or a scheduler is not up.
if (!master.equals(staticMaster) || !Mesos.getInstance(this).isSchedulerRunning()) {
if (!master.equals(staticMaster)) {
LOGGER.info("Mesos master changed, restarting the scheduler");
staticMaster = master;
} else {
LOGGER.info("Scheduler was down, restarting the scheduler");
}
Mesos.getInstance(this).stopScheduler();
Mesos.getInstance(this).startScheduler(jenkinsRootURL, this);
} else {
Mesos.getInstance(this).updateScheduler(jenkinsRootURL, this);
LOGGER.info("Mesos master has not changed, leaving the scheduler running");
}
}
private String expandJenkinsUrlWithEnvVars() {
Jenkins instance = Jenkins.getInstance();
DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties = instance.getGlobalNodeProperties();
if (globalNodeProperties == null) {
return jenkinsURL;
}
EnvironmentVariablesNodeProperty environmentVariablesNodeProperty = globalNodeProperties.get(EnvironmentVariablesNodeProperty.class);
if (environmentVariablesNodeProperty == null) {
return jenkinsURL;
}
EnvVars envVars = environmentVariablesNodeProperty.getEnvVars();
if (envVars != null) {
return StringUtils.defaultIfBlank(envVars.expand(this.jenkinsURL),instance.getRootUrl());
} else {
return jenkinsURL;
}
}
private boolean isThereAStuckItemInQueue(Label label) {
Jenkins jenkins = Jenkins.getInstance();
for (hudson.model.Queue.BuildableItem bi : jenkins.getQueue().getBuildableItems()) {
if (bi != null && bi.getAssignedLabel() != null) {
if (bi.getAssignedLabel().equals(label)) {
//if an item is longer than 1 Minute buildable in the queue, its count as stuck
if ((bi.buildableStartMilliseconds + TimeUnit.MINUTES.toMillis(1)) < System.currentTimeMillis()) {
return true;
}
}
}
}
return false;
}
public void resetProvisioningCount() {
provisioningCount = 0;
}
@Override
public Collection<PlannedNode> provision(Label label, int excessWorkload) {
final MesosSlaveInfo slaveInfo = getSlaveInfo(slaveInfos, label);
if (slaveInfo.isForceProvisioning()) {
if (isThereAStuckItemInQueue(label)) {
LOGGER.warning("There are Items waiting for more than 1 minute for a free slave executor for label " + label.getName());
LOGGER.info("Accepted Jenkins provisioning request for " + label.getName());
return provisionNodes(label, excessWorkload);
} else {
LOGGER.info("There are no stuck Items in the Queue, Jenkins provisioning request will be ignored");
}
} else {
return provisionNodes(label, excessWorkload);
}
return new ArrayList<PlannedNode>();
}
public int getAllIdleExecutorsCount() {
int count = 0;
Jenkins jenkins = Jenkins.getInstance();
for(Computer computer : jenkins.getComputers()) {
if(computer != null) {
if(computer instanceof MesosComputer) {
MesosSlave mesosSlave = ((MesosComputer) computer).getNode();
if(mesosSlave != null) {
if(this.equals(mesosSlave.getCloud())) {
if (computer.isOffline()) {
count++;
}
}
}
}
}
}
return count;
}
public Collection<PlannedNode> provisionNodes(Label label, int excessWorkload) {
List<PlannedNode> list = new ArrayList<PlannedNode>();
final MesosSlaveInfo slaveInfo = getSlaveInfo(slaveInfos, label);
try {
while (excessWorkload > 0 && !Jenkins.getInstance().isQuietingDown() && (getAllIdleExecutorsCount()+list.size()) < provisioningThreshold && provisioningCount < provisioningThreshold) {
// Start the scheduler if it's not already running.
if (onDemandRegistration) {
JenkinsScheduler.SUPERVISOR_LOCK.lock();
try {
LOGGER.fine("Checking if scheduler is running");
if (!Mesos.getInstance(this).isSchedulerRunning()) {
restartMesos();
}
} finally {
JenkinsScheduler.SUPERVISOR_LOCK.unlock();
}
}
final int numExecutors = Math.min(excessWorkload, slaveInfo.getMaxExecutors());
excessWorkload -= numExecutors;
provisioningCount += numExecutors;
LOGGER.info("Provisioning Jenkins Slave on Mesos with " + numExecutors +
" executors. Remaining excess workload: " + excessWorkload + " executors)");
list.add(new PlannedNode(this.getDisplayName(), Computer.threadPoolForRemoting
.submit(new Callable<Node>() {
public Node call() throws Exception {
MesosSlave s = doProvision(numExecutors, slaveInfo);
// We do not need to explicitly add the Node here because that is handled by
// hudson.slaves.NodeProvisioner::update() that checks the result from the
// Future and adds the node. Though there is duplicate node addition check
// because of this early addition there is difference in job scheduling and
// best to avoid it.
return s;
}
}), numExecutors));
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to create instances on Mesos", e);
return Collections.emptyList();
}
return list;
}
private MesosSlave doProvision(int numExecutors, MesosSlaveInfo slaveInfo) throws Descriptor.FormException, IOException {
String name = slaveInfo.getLabelString() + "-" + UUID.randomUUID().toString();
return new MesosSlave(this, name, numExecutors, slaveInfo);
}
public List<MesosSlaveInfo> getSlaveInfos() {
return slaveInfos;
}
public void setSlaveInfos(List<MesosSlaveInfo> slaveInfos) {
this.slaveInfos = slaveInfos;
}
@Override
public boolean canProvision(Label label) {
// Provisioning is simply creating a task for a jenkins slave.
// We can provision a Mesos slave as long as the job's label matches any
// item in the list of configured Mesos labels.
// TODO(vinod): The framework may not have the resources necessary
// to start a task when it comes time to launch the slave.
if (label != null && slaveInfos != null) {
for (MesosSlaveInfo slaveInfo : slaveInfos) {
if (label.matches(Label.parse(slaveInfo.getLabelString()))) {
return true;
}
}
}
return false;
}
public String getNativeLibraryPath() {
return this.nativeLibraryPath;
}
public void setNativeLibraryPath(String nativeLibraryPath) {
this.nativeLibraryPath = nativeLibraryPath;
}
public String getMaster() {
return this.master;
}
public void setMaster(String master) {
this.master = master;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFrameworkName() {
return frameworkName;
}
public void setFrameworkName(String frameworkName) {
this.frameworkName = frameworkName;
}
public String getSlavesUser() {
return slavesUser;
}
public void setSlavesUser(String slavesUser) {
this.slavesUser = slavesUser;
}
public String getPrincipal() {
return principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public boolean isOnDemandRegistration() {
return onDemandRegistration;
}
public void setOnDemandRegistration(boolean onDemandRegistration) {
this.onDemandRegistration = onDemandRegistration;
}
public void setProvisioningThreshold(int provisioningThreshold) {
this.provisioningThreshold = provisioningThreshold;
}
public int getProvisioningThreshold() {
return provisioningThreshold;
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
public static MesosCloud get() {
return Hudson.getInstance().clouds.get(MesosCloud.class);
}
/**
* @return the checkpoint
*/
public boolean isCheckpoint() {
return checkpoint;
}
public MesosSlaveInfo getSlaveInfo(List<MesosSlaveInfo> slaveInfos,
Label label) {
for (MesosSlaveInfo slaveInfo : slaveInfos) {
if (label.matches(Label.parse(slaveInfo.getLabelString()))) {
return slaveInfo;
}
}
return null;
}
/**
* Retrieves the slaveattribute corresponding to label name.
*
* @param labelName The Jenkins label name.
* @return slaveattribute as a JSONObject.
*/
public JSONObject getSlaveAttributeForLabel(String labelName) {
if(labelName!=null) {
for (MesosSlaveInfo slaveInfo : slaveInfos) {
if (labelName.equals(slaveInfo.getLabelString())) {
return slaveInfo.getSlaveAttributes();
}
}
}
return null;
}
public String getJenkinsURL() {
return jenkinsURL;
}
public void setJenkinsURL(String jenkinsURL) {
this.jenkinsURL = jenkinsURL;
}
public void forceNewMesosNodes(Label label, int numExecutors) {
Collection<PlannedNode> additionalCapacities = provisionNodes(label, numExecutors);
label.nodeProvisioner.getPendingLaunches().addAll(additionalCapacities);
Jenkins jenkins = Jenkins.getInstance();
//Add Nodes to Jenkins
for (PlannedNode ac : additionalCapacities) {
try {
Node future = future = ac.future.get();
jenkins.addNode(future);
LOGGER.info("Added node " + future.getNodeName() + " for quick access");
for (CloudProvisioningListener cl : CloudProvisioningListener.all())
cl.onStarted(this, label, additionalCapacities);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "IOException while adding node to Jenkins", e);
} catch (InterruptedException e) {
LOGGER.log(Level.SEVERE, "InterruptedException while adding node to Jenkins", e);
} catch (ExecutionException e) {
LOGGER.log(Level.SEVERE, "ExecutionException while adding node to Jenkins", e);
}
}
}
@Extension
public static class DescriptorImpl extends Descriptor<Cloud> {
private String nativeLibraryPath;
private String master;
private String description;
private String frameworkName;
private String slavesUser;
private String principal;
private String secret;
private String slaveAttributes;
private boolean checkpoint;
private String jenkinsURL;
private int provisioningThreshold;
private List<MesosSlaveInfo> slaveInfos;
@Override
public String getDisplayName() {
return "Mesos Cloud";
}
@Override
public boolean configure(StaplerRequest request, JSONObject object)
throws FormException {
LOGGER.info(object.toString());
nativeLibraryPath = object.getString("nativeLibraryPath");
master = object.getString("master");
description = object.getString("description");
frameworkName = object.getString("frameworkName");
principal = object.getString("principal");
secret = object.getString("secret");
slaveAttributes = object.getString("slaveAttributes");
checkpoint = object.getBoolean("checkpoint");
jenkinsURL = object.getString("jenkinsURL");
provisioningThreshold = object.getInt("provisioningThreshold");
slavesUser = object.getString("slavesUser");
slaveInfos = new ArrayList<MesosSlaveInfo>();
JSONArray labels = object.getJSONArray("slaveInfos");
if (labels != null) {
for (int i = 0; i < labels.size(); i++) {
JSONObject label = labels.getJSONObject(i);
if (label != null) {
MesosSlaveInfo.ExternalContainerInfo externalContainerInfo = null;
if (label.has("externalContainerInfo")) {
JSONObject externalContainerInfoJson = label
.getJSONObject("externalContainerInfo");
externalContainerInfo = new MesosSlaveInfo.ExternalContainerInfo(
externalContainerInfoJson.getString("image"),
externalContainerInfoJson.getString("options"));
}
MesosSlaveInfo.ContainerInfo containerInfo = null;
if (label.has("containerInfo")) {
JSONObject containerInfoJson = label
.getJSONObject("containerInfo");
List<MesosSlaveInfo.Volume> volumes = new ArrayList<MesosSlaveInfo.Volume>();
if (containerInfoJson.has("volumes")) {
JSONArray volumesJson = containerInfoJson
.getJSONArray("volumes");
for (Object obj : volumesJson) {
JSONObject volumeJson = (JSONObject) obj;
volumes
.add(new MesosSlaveInfo.Volume(volumeJson
.getString("containerPath"), volumeJson
.getString("hostPath"), volumeJson
.getBoolean("readOnly")));
}
}
List<MesosSlaveInfo.Parameter> parameters = new ArrayList<MesosSlaveInfo.Parameter>();
if (containerInfoJson.has("parameters")) {
JSONArray parametersJson = containerInfoJson.getJSONArray("parameters");
for (Object obj : parametersJson) {
JSONObject parameterJson = (JSONObject) obj;
parameters.add(new MesosSlaveInfo.Parameter(parameterJson.getString("key"), parameterJson.getString("value")));
}
}
List<MesosSlaveInfo.PortMapping> portMappings = new ArrayList<MesosSlaveInfo.PortMapping>();
final String networking = containerInfoJson.getString("networking");
if (Network.BRIDGE.equals(Network.valueOf(networking)) && containerInfoJson.has("portMappings")) {
JSONArray portMappingsJson = containerInfoJson
.getJSONArray("portMappings");
for (Object obj : portMappingsJson) {
JSONObject portMappingJson = (JSONObject) obj;
portMappings.add(new MesosSlaveInfo.PortMapping(
portMappingJson.getInt("containerPort"),
portMappingJson.getInt("hostPort"),
portMappingJson.getString("protocol"),
portMappingJson.getString("description"),
portMappingJson.getString("urlFormat")
));
}
}
containerInfo = new MesosSlaveInfo.ContainerInfo(
containerInfoJson.getString("type"),
containerInfoJson.getString("dockerImage"),
containerInfoJson.getBoolean("dockerPrivilegedMode"),
containerInfoJson.getBoolean("dockerForcePullImage"),
containerInfoJson.getBoolean("useCustomDockerCommandShell"),
containerInfoJson.getString ("customDockerCommandShell"),
volumes,
parameters,
networking,
portMappings);
}
MesosSlaveInfo.RunAsUserInfo runAsUserInfo = null;
if (label.has("runAsUserInfo")) {
JSONObject runAsUserInfoJson = label.getJSONObject("runAsUserInfo");
runAsUserInfo = new MesosSlaveInfo.RunAsUserInfo(
runAsUserInfoJson.getString("username"),
runAsUserInfoJson.getString("command")
);
}
List<MesosSlaveInfo.URI> additionalURIs = new ArrayList<MesosSlaveInfo.URI>();
if (label.has("additionalURIs")) {
JSONArray additionalURIsJson = label.getJSONArray("additionalURIs");
for (Object obj : additionalURIsJson) {
JSONObject URIJson = (JSONObject) obj;
additionalURIs.add(new MesosSlaveInfo.URI(
URIJson.getString("value"),
URIJson.getBoolean("executable"),
URIJson.getBoolean("extract")));
}
}
List<MesosSlaveInfo.Command> additionalCommands = new ArrayList<MesosSlaveInfo.Command>();
if (label.has("additionalCommands")) {
JSONArray additionalCommandsJson = label.getJSONArray("additionalCommands");
for (Object obj : additionalCommandsJson) {
JSONObject additionalCommandJson = (JSONObject) obj;
additionalCommands.add(new MesosSlaveInfo.Command(
additionalCommandJson.getString("value")));
}
}
MesosSlaveInfo slaveInfo = new MesosSlaveInfo(
object.getString("labelString"),
(Mode) object.get("mode"),
object.getString("slaveCpus"),
object.getString("slaveMem"),
object.getString("maxExecutors"),
object.getString("executorCpus"),
object.getString("executorMem"),
object.getString("remoteFSRoot"),
object.getString("idleTerminationMinutes"),
object.getString("maximumTimeToLiveMinutes"),
object.getString("slaveAttributes"),
object.getString("jvmArgs"),
object.getString("jnlpArgs"),
externalContainerInfo,
containerInfo,
additionalURIs,
runAsUserInfo,
additionalCommands,
object.getBoolean("forceProvisioning"),
object.getBoolean("useSlaveOnce"));
slaveInfos.add(slaveInfo);
}
}
}
save();
return super.configure(request, object);
}
/**
* Test connection from configuration page.
*/
public FormValidation doTestConnection(
@QueryParameter("master") String master,
@QueryParameter("nativeLibraryPath") String nativeLibraryPath)
throws IOException, ServletException {
master = master.trim();
if (master.equals("local")) {
return FormValidation.warning("'local' creates a local mesos cluster");
}
if (master.startsWith("zk://")) {
return FormValidation.warning("Zookeeper paths can be used, but the connection cannot be " +
"tested prior to saving this page.");
}
if (master.startsWith("http://")) {
return FormValidation.error("Please omit 'http://'.");
}
if (!nativeLibraryPath.startsWith("/")) {
return FormValidation.error("Please provide an absolute path");
}
try {
// URL requires the protocol to be explicitly specified.
HttpURLConnection urlConn =
(HttpURLConnection) new URL("http://" + master).openConnection();
urlConn.connect();
int code = urlConn.getResponseCode();
urlConn.disconnect();
if (code == 200) {
return FormValidation.ok("Connected to Mesos successfully");
} else {
return FormValidation.error("Status returned from url was " + code);
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to connect to Mesos " + master, e);
return FormValidation.error(e.getMessage());
}
}
public FormValidation doCheckMaxExecutors(@QueryParameter("useSlaveOnce") final String strUseSlaveOnce,
@QueryParameter("maxExecutors") final String strMaxExecutors) {
boolean useSlaveOnce = false;
int maxExecutors = 1;
try {
useSlaveOnce = Boolean.parseBoolean(strUseSlaveOnce);
maxExecutors = Integer.parseInt(strMaxExecutors);
} catch (Exception e) {
return FormValidation.ok();
}
if(useSlaveOnce && maxExecutors > 1) return FormValidation.error("A UseSlaveOnce Slave can only have at least 1 executor.");
return FormValidation.ok();
}
public FormValidation doCheckSlaveCpus(@QueryParameter String value) {
return doCheckCpus(value);
}
public FormValidation doCheckExecutorCpus(@QueryParameter String value) {
return doCheckCpus(value);
}
private FormValidation doCheckCpus(@QueryParameter String value) {
boolean valid = true;
String errorMessage = "Invalid CPUs value, it should be a positive decimal.";
if (StringUtils.isBlank(value)) {
valid = false;
} else {
try {
if (Double.parseDouble(value) < 0) {
valid = false;
}
} catch (NumberFormatException e) {
valid = false;
}
}
return valid ? FormValidation.ok() : FormValidation.error(errorMessage);
}
public FormValidation doCheckRemoteFSRoot(@QueryParameter String value) {
String errorMessage = "Invalid Remote FS Root - should be non-empty. It will be defaulted to \"jenkins\".";
return StringUtils.isNotBlank(value) ? FormValidation.ok() : FormValidation.error(errorMessage);
}
}
}
|
src/main/java/org/jenkinsci/plugins/mesos/MesosCloud.java
|
/*
* Copyright 2013 Twitter, Inc. and other contributors.
* 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.jenkinsci.plugins.mesos;
import hudson.EnvVars;
import hudson.Extension;
import hudson.init.InitMilestone;
import hudson.init.Initializer;
import hudson.model.*;
import hudson.model.Node.Mode;
import hudson.slaves.*;
import hudson.slaves.NodeProvisioner.PlannedNode;
import hudson.util.DescribableList;
import hudson.util.FormValidation;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import jenkins.model.Jenkins;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.mesos.MesosNativeLibrary;
import org.apache.mesos.Protos.ContainerInfo.DockerInfo.Network;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
public class MesosCloud extends Cloud {
private String nativeLibraryPath;
private String master;
private String description;
private String frameworkName;
private String slavesUser;
private String principal;
private String secret;
private final boolean checkpoint; // Set true to enable checkpointing. False by default.
private boolean onDemandRegistration; // If set true, this framework disconnects when there are no builds in the queue and re-registers when there are.
private String jenkinsURL;
private int provisioningThreshold;
private int provisioningCount = 0;
// Find the default values for these variables in
// src/main/resources/org/jenkinsci/plugins/mesos/MesosCloud/config.jelly.
private List<MesosSlaveInfo> slaveInfos;
private static String staticMaster;
private static final Logger LOGGER = Logger.getLogger(MesosCloud.class.getName());
private static volatile boolean nativeLibraryLoaded = false;
/**
* We want to start the Mesos scheduler as part of the initialization of Jenkins
* and after the cloud class values have been restored from persistence.If this is
* the very first time, this method will be NOOP as MesosCloud is not registered yet.
*/
@Initializer(after=InitMilestone.JOB_LOADED)
public static void init() {
Jenkins jenkins = Jenkins.getInstance();
List<Node> slaves = jenkins.getNodes();
// Turning the AUTOMATIC_SLAVE_LAUNCH flag off because the below slave removals
// causes computer launch in other slaves that have not been removed yet.
// To study how a slave removal updates the entire list, one can refer to
// Hudson NodeProvisioner class and follow this method chain removeNode() ->
// setNodes() -> updateComputerList() -> updateComputer().
Jenkins.AUTOMATIC_SLAVE_LAUNCH = false;
for (Node n : slaves) {
//Remove all slaves that were persisted when Jenkins shutdown.
if (n instanceof MesosSlave) {
((MesosSlave)n).terminate();
}
}
// Turn it back on for future real slaves.
Jenkins.AUTOMATIC_SLAVE_LAUNCH = true;
for (Cloud c : jenkins.clouds) {
if( c instanceof MesosCloud) {
// Register mesos framework on init, if on demand registration is not enabled.
if (!((MesosCloud) c).isOnDemandRegistration()) {
((MesosCloud)c).restartMesos();
}
}
}
}
@DataBoundConstructor
public MesosCloud(
String nativeLibraryPath,
String master,
String description,
String frameworkName,
String slavesUser,
String principal,
String secret,
List<MesosSlaveInfo> slaveInfos,
boolean checkpoint,
boolean onDemandRegistration,
String jenkinsURL,
int provisioningThreshold) throws NumberFormatException {
super("MesosCloud");
this.nativeLibraryPath = nativeLibraryPath;
this.master = master;
this.description = description;
this.frameworkName = frameworkName;
this.slavesUser = slavesUser;
this.principal = principal;
this.secret = secret;
this.slaveInfos = slaveInfos;
this.checkpoint = checkpoint;
this.onDemandRegistration = onDemandRegistration;
this.setJenkinsURL(jenkinsURL);
this.provisioningThreshold = provisioningThreshold;
if(!onDemandRegistration) {
JenkinsScheduler.SUPERVISOR_LOCK.lock();
try {
restartMesos();
} finally {
JenkinsScheduler.SUPERVISOR_LOCK.unlock();
}
}
}
// Since MesosCloud is used as a key to a Hashmap, we need to set equals/hashcode
// or lookups won't work if any fields are changed. Use master string as the key since
// the rest of this code assumes it is unique among the Cloud objects.
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MesosCloud that = (MesosCloud) o;
if (master != null ? !master.equals(that.master) : that.master != null) return false;
return true;
}
@Override
public int hashCode() {
return master != null ? master.hashCode() : 0;
}
public void restartMesos() {
if(!nativeLibraryLoaded) {
// First, we attempt to load the library from the given path.
// If unsuccessful, we attempt to load using 'MesosNativeLibrary.load()'.
try {
MesosNativeLibrary.load(nativeLibraryPath);
} catch (UnsatisfiedLinkError error) {
LOGGER.warning("Failed to load native Mesos library from '" + nativeLibraryPath +
"': " + error.getMessage());
MesosNativeLibrary.load();
}
nativeLibraryLoaded = true;
}
// Default to root URL in Jenkins global configuration.
String jenkinsRootURL = Jenkins.getInstance().getRootUrl();
// If 'jenkinsURL' parameter is provided in mesos plugin configuration, then that should take precedence.
if(StringUtils.isNotBlank(jenkinsURL)) {
jenkinsRootURL = expandJenkinsUrlWithEnvVars();
}
// Restart the scheduler if the master has changed or a scheduler is not up.
if (!master.equals(staticMaster) || !Mesos.getInstance(this).isSchedulerRunning()) {
if (!master.equals(staticMaster)) {
LOGGER.info("Mesos master changed, restarting the scheduler");
staticMaster = master;
} else {
LOGGER.info("Scheduler was down, restarting the scheduler");
}
Mesos.getInstance(this).stopScheduler();
Mesos.getInstance(this).startScheduler(jenkinsRootURL, this);
} else {
Mesos.getInstance(this).updateScheduler(jenkinsRootURL, this);
LOGGER.info("Mesos master has not changed, leaving the scheduler running");
}
}
private String expandJenkinsUrlWithEnvVars() {
Jenkins instance = Jenkins.getInstance();
DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties = instance.getGlobalNodeProperties();
if (globalNodeProperties == null) {
return jenkinsURL;
}
EnvVars envVars = globalNodeProperties.get(EnvironmentVariablesNodeProperty.class).getEnvVars();
if (envVars != null) {
return StringUtils.defaultIfBlank(envVars.expand(this.jenkinsURL),instance.getRootUrl());
} else {
return jenkinsURL;
}
}
private boolean isThereAStuckItemInQueue(Label label) {
Jenkins jenkins = Jenkins.getInstance();
for (hudson.model.Queue.BuildableItem bi : jenkins.getQueue().getBuildableItems()) {
if (bi != null && bi.getAssignedLabel() != null) {
if (bi.getAssignedLabel().equals(label)) {
//if an item is longer than 1 Minute buildable in the queue, its count as stuck
if ((bi.buildableStartMilliseconds + TimeUnit.MINUTES.toMillis(1)) < System.currentTimeMillis()) {
return true;
}
}
}
}
return false;
}
public void resetProvisioningCount() {
provisioningCount = 0;
}
@Override
public Collection<PlannedNode> provision(Label label, int excessWorkload) {
final MesosSlaveInfo slaveInfo = getSlaveInfo(slaveInfos, label);
if (slaveInfo.isForceProvisioning()) {
if (isThereAStuckItemInQueue(label)) {
LOGGER.warning("There are Items waiting for more than 1 minute for a free slave executor for label " + label.getName());
LOGGER.info("Accepted Jenkins provisioning request for " + label.getName());
return provisionNodes(label, excessWorkload);
} else {
LOGGER.info("There are no stuck Items in the Queue, Jenkins provisioning request will be ignored");
}
} else {
return provisionNodes(label, excessWorkload);
}
return new ArrayList<PlannedNode>();
}
public int getAllIdleExecutorsCount() {
int count = 0;
Jenkins jenkins = Jenkins.getInstance();
for(Computer computer : jenkins.getComputers()) {
if(computer != null) {
if(computer instanceof MesosComputer) {
MesosSlave mesosSlave = ((MesosComputer) computer).getNode();
if(mesosSlave != null) {
if(this.equals(mesosSlave.getCloud())) {
if (computer.isOffline()) {
count++;
}
}
}
}
}
}
return count;
}
public Collection<PlannedNode> provisionNodes(Label label, int excessWorkload) {
List<PlannedNode> list = new ArrayList<PlannedNode>();
final MesosSlaveInfo slaveInfo = getSlaveInfo(slaveInfos, label);
try {
while (excessWorkload > 0 && !Jenkins.getInstance().isQuietingDown() && (getAllIdleExecutorsCount()+list.size()) < provisioningThreshold && provisioningCount < provisioningThreshold) {
// Start the scheduler if it's not already running.
if (onDemandRegistration) {
JenkinsScheduler.SUPERVISOR_LOCK.lock();
try {
LOGGER.fine("Checking if scheduler is running");
if (!Mesos.getInstance(this).isSchedulerRunning()) {
restartMesos();
}
} finally {
JenkinsScheduler.SUPERVISOR_LOCK.unlock();
}
}
final int numExecutors = Math.min(excessWorkload, slaveInfo.getMaxExecutors());
excessWorkload -= numExecutors;
provisioningCount += numExecutors;
LOGGER.info("Provisioning Jenkins Slave on Mesos with " + numExecutors +
" executors. Remaining excess workload: " + excessWorkload + " executors)");
list.add(new PlannedNode(this.getDisplayName(), Computer.threadPoolForRemoting
.submit(new Callable<Node>() {
public Node call() throws Exception {
MesosSlave s = doProvision(numExecutors, slaveInfo);
// We do not need to explicitly add the Node here because that is handled by
// hudson.slaves.NodeProvisioner::update() that checks the result from the
// Future and adds the node. Though there is duplicate node addition check
// because of this early addition there is difference in job scheduling and
// best to avoid it.
return s;
}
}), numExecutors));
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to create instances on Mesos", e);
return Collections.emptyList();
}
return list;
}
private MesosSlave doProvision(int numExecutors, MesosSlaveInfo slaveInfo) throws Descriptor.FormException, IOException {
String name = slaveInfo.getLabelString() + "-" + UUID.randomUUID().toString();
return new MesosSlave(this, name, numExecutors, slaveInfo);
}
public List<MesosSlaveInfo> getSlaveInfos() {
return slaveInfos;
}
public void setSlaveInfos(List<MesosSlaveInfo> slaveInfos) {
this.slaveInfos = slaveInfos;
}
@Override
public boolean canProvision(Label label) {
// Provisioning is simply creating a task for a jenkins slave.
// We can provision a Mesos slave as long as the job's label matches any
// item in the list of configured Mesos labels.
// TODO(vinod): The framework may not have the resources necessary
// to start a task when it comes time to launch the slave.
if (label != null && slaveInfos != null) {
for (MesosSlaveInfo slaveInfo : slaveInfos) {
if (label.matches(Label.parse(slaveInfo.getLabelString()))) {
return true;
}
}
}
return false;
}
public String getNativeLibraryPath() {
return this.nativeLibraryPath;
}
public void setNativeLibraryPath(String nativeLibraryPath) {
this.nativeLibraryPath = nativeLibraryPath;
}
public String getMaster() {
return this.master;
}
public void setMaster(String master) {
this.master = master;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFrameworkName() {
return frameworkName;
}
public void setFrameworkName(String frameworkName) {
this.frameworkName = frameworkName;
}
public String getSlavesUser() {
return slavesUser;
}
public void setSlavesUser(String slavesUser) {
this.slavesUser = slavesUser;
}
public String getPrincipal() {
return principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public boolean isOnDemandRegistration() {
return onDemandRegistration;
}
public void setOnDemandRegistration(boolean onDemandRegistration) {
this.onDemandRegistration = onDemandRegistration;
}
public void setProvisioningThreshold(int provisioningThreshold) {
this.provisioningThreshold = provisioningThreshold;
}
public int getProvisioningThreshold() {
return provisioningThreshold;
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
public static MesosCloud get() {
return Hudson.getInstance().clouds.get(MesosCloud.class);
}
/**
* @return the checkpoint
*/
public boolean isCheckpoint() {
return checkpoint;
}
public MesosSlaveInfo getSlaveInfo(List<MesosSlaveInfo> slaveInfos,
Label label) {
for (MesosSlaveInfo slaveInfo : slaveInfos) {
if (label.matches(Label.parse(slaveInfo.getLabelString()))) {
return slaveInfo;
}
}
return null;
}
/**
* Retrieves the slaveattribute corresponding to label name.
*
* @param labelName The Jenkins label name.
* @return slaveattribute as a JSONObject.
*/
public JSONObject getSlaveAttributeForLabel(String labelName) {
if(labelName!=null) {
for (MesosSlaveInfo slaveInfo : slaveInfos) {
if (labelName.equals(slaveInfo.getLabelString())) {
return slaveInfo.getSlaveAttributes();
}
}
}
return null;
}
public String getJenkinsURL() {
return jenkinsURL;
}
public void setJenkinsURL(String jenkinsURL) {
this.jenkinsURL = jenkinsURL;
}
public void forceNewMesosNodes(Label label, int numExecutors) {
Collection<PlannedNode> additionalCapacities = provisionNodes(label, numExecutors);
label.nodeProvisioner.getPendingLaunches().addAll(additionalCapacities);
Jenkins jenkins = Jenkins.getInstance();
//Add Nodes to Jenkins
for (PlannedNode ac : additionalCapacities) {
try {
Node future = future = ac.future.get();
jenkins.addNode(future);
LOGGER.info("Added node " + future.getNodeName() + " for quick access");
for (CloudProvisioningListener cl : CloudProvisioningListener.all())
cl.onStarted(this, label, additionalCapacities);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "IOException while adding node to Jenkins", e);
} catch (InterruptedException e) {
LOGGER.log(Level.SEVERE, "InterruptedException while adding node to Jenkins", e);
} catch (ExecutionException e) {
LOGGER.log(Level.SEVERE, "ExecutionException while adding node to Jenkins", e);
}
}
}
@Extension
public static class DescriptorImpl extends Descriptor<Cloud> {
private String nativeLibraryPath;
private String master;
private String description;
private String frameworkName;
private String slavesUser;
private String principal;
private String secret;
private String slaveAttributes;
private boolean checkpoint;
private String jenkinsURL;
private int provisioningThreshold;
private List<MesosSlaveInfo> slaveInfos;
@Override
public String getDisplayName() {
return "Mesos Cloud";
}
@Override
public boolean configure(StaplerRequest request, JSONObject object)
throws FormException {
LOGGER.info(object.toString());
nativeLibraryPath = object.getString("nativeLibraryPath");
master = object.getString("master");
description = object.getString("description");
frameworkName = object.getString("frameworkName");
principal = object.getString("principal");
secret = object.getString("secret");
slaveAttributes = object.getString("slaveAttributes");
checkpoint = object.getBoolean("checkpoint");
jenkinsURL = object.getString("jenkinsURL");
provisioningThreshold = object.getInt("provisioningThreshold");
slavesUser = object.getString("slavesUser");
slaveInfos = new ArrayList<MesosSlaveInfo>();
JSONArray labels = object.getJSONArray("slaveInfos");
if (labels != null) {
for (int i = 0; i < labels.size(); i++) {
JSONObject label = labels.getJSONObject(i);
if (label != null) {
MesosSlaveInfo.ExternalContainerInfo externalContainerInfo = null;
if (label.has("externalContainerInfo")) {
JSONObject externalContainerInfoJson = label
.getJSONObject("externalContainerInfo");
externalContainerInfo = new MesosSlaveInfo.ExternalContainerInfo(
externalContainerInfoJson.getString("image"),
externalContainerInfoJson.getString("options"));
}
MesosSlaveInfo.ContainerInfo containerInfo = null;
if (label.has("containerInfo")) {
JSONObject containerInfoJson = label
.getJSONObject("containerInfo");
List<MesosSlaveInfo.Volume> volumes = new ArrayList<MesosSlaveInfo.Volume>();
if (containerInfoJson.has("volumes")) {
JSONArray volumesJson = containerInfoJson
.getJSONArray("volumes");
for (Object obj : volumesJson) {
JSONObject volumeJson = (JSONObject) obj;
volumes
.add(new MesosSlaveInfo.Volume(volumeJson
.getString("containerPath"), volumeJson
.getString("hostPath"), volumeJson
.getBoolean("readOnly")));
}
}
List<MesosSlaveInfo.Parameter> parameters = new ArrayList<MesosSlaveInfo.Parameter>();
if (containerInfoJson.has("parameters")) {
JSONArray parametersJson = containerInfoJson.getJSONArray("parameters");
for (Object obj : parametersJson) {
JSONObject parameterJson = (JSONObject) obj;
parameters.add(new MesosSlaveInfo.Parameter(parameterJson.getString("key"), parameterJson.getString("value")));
}
}
List<MesosSlaveInfo.PortMapping> portMappings = new ArrayList<MesosSlaveInfo.PortMapping>();
final String networking = containerInfoJson.getString("networking");
if (Network.BRIDGE.equals(Network.valueOf(networking)) && containerInfoJson.has("portMappings")) {
JSONArray portMappingsJson = containerInfoJson
.getJSONArray("portMappings");
for (Object obj : portMappingsJson) {
JSONObject portMappingJson = (JSONObject) obj;
portMappings.add(new MesosSlaveInfo.PortMapping(
portMappingJson.getInt("containerPort"),
portMappingJson.getInt("hostPort"),
portMappingJson.getString("protocol"),
portMappingJson.getString("description"),
portMappingJson.getString("urlFormat")
));
}
}
containerInfo = new MesosSlaveInfo.ContainerInfo(
containerInfoJson.getString("type"),
containerInfoJson.getString("dockerImage"),
containerInfoJson.getBoolean("dockerPrivilegedMode"),
containerInfoJson.getBoolean("dockerForcePullImage"),
containerInfoJson.getBoolean("useCustomDockerCommandShell"),
containerInfoJson.getString ("customDockerCommandShell"),
volumes,
parameters,
networking,
portMappings);
}
MesosSlaveInfo.RunAsUserInfo runAsUserInfo = null;
if (label.has("runAsUserInfo")) {
JSONObject runAsUserInfoJson = label.getJSONObject("runAsUserInfo");
runAsUserInfo = new MesosSlaveInfo.RunAsUserInfo(
runAsUserInfoJson.getString("username"),
runAsUserInfoJson.getString("command")
);
}
List<MesosSlaveInfo.URI> additionalURIs = new ArrayList<MesosSlaveInfo.URI>();
if (label.has("additionalURIs")) {
JSONArray additionalURIsJson = label.getJSONArray("additionalURIs");
for (Object obj : additionalURIsJson) {
JSONObject URIJson = (JSONObject) obj;
additionalURIs.add(new MesosSlaveInfo.URI(
URIJson.getString("value"),
URIJson.getBoolean("executable"),
URIJson.getBoolean("extract")));
}
}
List<MesosSlaveInfo.Command> additionalCommands = new ArrayList<MesosSlaveInfo.Command>();
if (label.has("additionalCommands")) {
JSONArray additionalCommandsJson = label.getJSONArray("additionalCommands");
for (Object obj : additionalCommandsJson) {
JSONObject additionalCommandJson = (JSONObject) obj;
additionalCommands.add(new MesosSlaveInfo.Command(
additionalCommandJson.getString("value")));
}
}
MesosSlaveInfo slaveInfo = new MesosSlaveInfo(
object.getString("labelString"),
(Mode) object.get("mode"),
object.getString("slaveCpus"),
object.getString("slaveMem"),
object.getString("maxExecutors"),
object.getString("executorCpus"),
object.getString("executorMem"),
object.getString("remoteFSRoot"),
object.getString("idleTerminationMinutes"),
object.getString("maximumTimeToLiveMinutes"),
object.getString("slaveAttributes"),
object.getString("jvmArgs"),
object.getString("jnlpArgs"),
externalContainerInfo,
containerInfo,
additionalURIs,
runAsUserInfo,
additionalCommands,
object.getBoolean("forceProvisioning"),
object.getBoolean("useSlaveOnce"));
slaveInfos.add(slaveInfo);
}
}
}
save();
return super.configure(request, object);
}
/**
* Test connection from configuration page.
*/
public FormValidation doTestConnection(
@QueryParameter("master") String master,
@QueryParameter("nativeLibraryPath") String nativeLibraryPath)
throws IOException, ServletException {
master = master.trim();
if (master.equals("local")) {
return FormValidation.warning("'local' creates a local mesos cluster");
}
if (master.startsWith("zk://")) {
return FormValidation.warning("Zookeeper paths can be used, but the connection cannot be " +
"tested prior to saving this page.");
}
if (master.startsWith("http://")) {
return FormValidation.error("Please omit 'http://'.");
}
if (!nativeLibraryPath.startsWith("/")) {
return FormValidation.error("Please provide an absolute path");
}
try {
// URL requires the protocol to be explicitly specified.
HttpURLConnection urlConn =
(HttpURLConnection) new URL("http://" + master).openConnection();
urlConn.connect();
int code = urlConn.getResponseCode();
urlConn.disconnect();
if (code == 200) {
return FormValidation.ok("Connected to Mesos successfully");
} else {
return FormValidation.error("Status returned from url was " + code);
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to connect to Mesos " + master, e);
return FormValidation.error(e.getMessage());
}
}
public FormValidation doCheckMaxExecutors(@QueryParameter("useSlaveOnce") final String strUseSlaveOnce,
@QueryParameter("maxExecutors") final String strMaxExecutors) {
boolean useSlaveOnce = false;
int maxExecutors = 1;
try {
useSlaveOnce = Boolean.parseBoolean(strUseSlaveOnce);
maxExecutors = Integer.parseInt(strMaxExecutors);
} catch (Exception e) {
return FormValidation.ok();
}
if(useSlaveOnce && maxExecutors > 1) return FormValidation.error("A UseSlaveOnce Slave can only have at least 1 executor.");
return FormValidation.ok();
}
public FormValidation doCheckSlaveCpus(@QueryParameter String value) {
return doCheckCpus(value);
}
public FormValidation doCheckExecutorCpus(@QueryParameter String value) {
return doCheckCpus(value);
}
private FormValidation doCheckCpus(@QueryParameter String value) {
boolean valid = true;
String errorMessage = "Invalid CPUs value, it should be a positive decimal.";
if (StringUtils.isBlank(value)) {
valid = false;
} else {
try {
if (Double.parseDouble(value) < 0) {
valid = false;
}
} catch (NumberFormatException e) {
valid = false;
}
}
return valid ? FormValidation.ok() : FormValidation.error(errorMessage);
}
public FormValidation doCheckRemoteFSRoot(@QueryParameter String value) {
String errorMessage = "Invalid Remote FS Root - should be non-empty. It will be defaulted to \"jenkins\".";
return StringUtils.isNotBlank(value) ? FormValidation.ok() : FormValidation.error(errorMessage);
}
}
}
|
Another nullpointer guard.
|
src/main/java/org/jenkinsci/plugins/mesos/MesosCloud.java
|
Another nullpointer guard.
|
|
Java
|
apache-2.0
|
8ced55af90521733e6536129b3f36ea0ac127aec
| 0
|
mattcasters/pentaho-pdi-dataset
|
package org.pentaho.di.dataset;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.csv.QuoteMode;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.vfs2.FileObject;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.logging.LoggingObjectInterface;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaString;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.core.vfs.KettleVFS;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* The implementation of a CSV Data Set Group
* We simply write/read the rows without a header into a file defined by the tableName in the data set
*/
public class DataSetCsvGroup {
public static final String VARIABLE_DATASETS_BASE_PATH = "DATASETS_BASE_PATH";
/**
* Get the base folder for the data set group
*
* @param group
* @return
*/
private static String getDataSetFolder( DataSetGroup group ) {
String folderName = group.getFolderName();
if ( StringUtils.isEmpty( folderName ) ) {
folderName = System.getProperty( VARIABLE_DATASETS_BASE_PATH );
}
if ( StringUtils.isEmpty( folderName ) ) {
// Local folder
folderName = ".";
} else {
// Let's not forget to replace variables as well...
//
VariableSpace space = Variables.getADefaultVariableSpace();
folderName = space.environmentSubstitute( folderName );
}
if ( !folderName.endsWith( File.separator ) ) {
folderName += File.separator;
}
return folderName;
}
private static void setValueFormats( RowMetaInterface rowMeta ) {
for ( ValueMetaInterface valueMeta : rowMeta.getValueMetaList() ) {
if ( StringUtils.isEmpty( valueMeta.getConversionMask() ) ) {
switch ( valueMeta.getType() ) {
case ValueMetaInterface.TYPE_INTEGER:
valueMeta.setConversionMask( "0" );
break;
case ValueMetaInterface.TYPE_NUMBER:
valueMeta.setConversionMask( "0.#" );
break;
case ValueMetaInterface.TYPE_DATE:
valueMeta.setConversionMask( "yyyyMMdd-HHmmss.SSS" );
break;
default:
break;
}
}
}
}
public static String getDataSetFilename( DataSetGroup dataSetGroup, String tableName ) {
String setFolderName = getDataSetFolder( dataSetGroup );
setFolderName += tableName + ".csv";
return setFolderName;
}
public static final List<Object[]> getAllRows( LogChannelInterface log, DataSetGroup group, DataSet dataSet ) throws KettleException {
RowMetaInterface setRowMeta = dataSet.getSetRowMeta( true );
setValueFormats( setRowMeta );
String dataSetFilename = getDataSetFilename( group, dataSet.getTableName() );
List<Object[]> rows = new ArrayList<>();
final ValueMetaString constantValueMeta = new ValueMetaString( "constant" );
try {
FileObject file = KettleVFS.getFileObject( dataSetFilename );
if ( !file.exists() ) {
// This is fine. We haven't put rows in yet.
//
return rows;
}
try (
Reader reader = new InputStreamReader( new BufferedInputStream( KettleVFS.getInputStream( file ) ) );
CSVParser csvParser = new CSVParser( reader, getCsvFormat( setRowMeta ) );
) {
for ( CSVRecord csvRecord : csvParser ) {
if ( csvRecord.getRecordNumber() > 1 ) {
Object[] row = RowDataUtil.allocateRowData( setRowMeta.size() );
for ( int i = 0; i < setRowMeta.size(); i++ ) {
ValueMetaInterface valueMeta = setRowMeta.getValueMeta( i ).clone();
constantValueMeta.setConversionMetadata( valueMeta );
String value = csvRecord.get( i );
row[ i ] = valueMeta.convertData( constantValueMeta, value );
}
rows.add( row );
}
}
}
return rows;
} catch ( Exception e ) {
throw new KettleException( "Unable to get all rows for CSV data set '" + dataSet.getName() + "'", e );
}
}
/**
* Get the rows for this data set in the format of the data set.
*
* @param log the logging channel to which you can write.
* @param location The fields to obtain in the order given
* @return The rows for the given location
* @throws KettleException
*/
public static final List<Object[]> getAllRows( LogChannelInterface log, DataSetGroup group, DataSet dataSet, TransUnitTestSetLocation location ) throws KettleException {
RowMetaInterface setRowMeta = dataSet.getSetRowMeta( false );
// The row description of the output of this step...
//
final RowMetaInterface outputRowMeta = dataSet.getMappedDataSetFieldsRowMeta( location );
setValueFormats( setRowMeta );
String dataSetFilename = getDataSetFilename( group, dataSet.getTableName() );
List<Object[]> rows = new ArrayList<>();
final ValueMetaString constantValueMeta = new ValueMetaString( "constant" );
try {
FileObject file = KettleVFS.getFileObject( dataSetFilename );
if ( !file.exists() ) {
// This is fine. We haven't put rows in yet.
//
return rows;
}
List<String> sortFields = location.getFieldOrder();
// See how we mapped the fields
//
List<TransUnitTestFieldMapping> fieldMappings = location.getFieldMappings();
int[] dataSetFieldIndexes = new int[ fieldMappings.size() ];
for ( int i = 0; i < fieldMappings.size(); i++ ) {
TransUnitTestFieldMapping fieldMapping = fieldMappings.get( i );
String dataSetFieldName = fieldMapping.getDataSetFieldName();
dataSetFieldIndexes[ i ] = setRowMeta.indexOfValue( dataSetFieldName );
}
try (
Reader reader = new InputStreamReader( new BufferedInputStream( KettleVFS.getInputStream( file ) ) );
CSVParser csvParser = new CSVParser( reader, CSVFormat.DEFAULT );
) {
for ( CSVRecord csvRecord : csvParser ) {
if ( csvRecord.getRecordNumber() > 1 ) {
Object[] row = RowDataUtil.allocateRowData( dataSetFieldIndexes.length );
// Only get certain values...
//
for ( int i = 0; i < dataSetFieldIndexes.length; i++ ) {
int index = dataSetFieldIndexes[ i ];
ValueMetaInterface valueMeta = setRowMeta.getValueMeta( index );
constantValueMeta.setConversionMetadata( valueMeta );
String value = csvRecord.get( index );
row[ i ] = valueMeta.convertData( constantValueMeta, value );
}
rows.add( row );
}
}
}
// Which fields are we sorting on (if any)
//
int[] sortIndexes = new int[ sortFields.size() ];
for ( int i = 0; i < sortIndexes.length; i++ ) {
sortIndexes[ i ] = outputRowMeta.indexOfValue( sortFields.get( i ) );
}
if ( outputRowMeta.isEmpty() ) {
log.logError( "WARNING: No field mappings selected for data set '" + dataSet.getName() + "', returning empty set of rows" );
return new ArrayList<>();
}
if ( !sortFields.isEmpty() ) {
// Sort the rows...
//
Collections.sort( rows, new Comparator<Object[]>() {
@Override public int compare( Object[] o1, Object[] o2 ) {
try {
return outputRowMeta.compare( o1, o2, sortIndexes );
} catch ( KettleValueException e ) {
throw new RuntimeException( "Unable to compare 2 rows", e );
}
}
} );
}
return rows;
} catch (
Exception e ) {
throw new KettleException( "Unable to get all rows for database data set '" + dataSet.getName() + "'", e );
}
}
public static final void writeDataSetData( LoggingObjectInterface loggingObject, DataSetGroup dataSetGroup, String tableName,
RowMetaInterface rowMeta, List<Object[]> rows ) throws KettleException {
String dataSetFilename = getDataSetFilename( dataSetGroup, tableName );
RowMetaInterface setRowMeta = rowMeta.clone(); // just making sure
setValueFormats( setRowMeta );
OutputStream outputStream = null;
BufferedWriter writer = null;
CSVPrinter csvPrinter = null;
try {
FileObject file = KettleVFS.getFileObject( dataSetFilename );
outputStream = KettleVFS.getOutputStream( file, false );
writer = new BufferedWriter( new OutputStreamWriter( outputStream ) );
CSVFormat csvFormat = getCsvFormat( rowMeta );
csvPrinter = new CSVPrinter( writer, csvFormat );
for ( Object[] row : rows ) {
List<String> strings = new ArrayList<>();
for ( int i = 0; i < setRowMeta.size(); i++ ) {
ValueMetaInterface valueMeta = setRowMeta.getValueMeta( i );
String string = valueMeta.getString( row[ i ] );
strings.add( string );
}
csvPrinter.printRecord( strings );
}
csvPrinter.flush();
} catch ( Exception e ) {
throw new KettleException( "Unable to write data set to file '" + dataSetFilename + "'", e );
} finally {
try {
if ( csvPrinter != null ) {
csvPrinter.close();
}
if ( writer != null ) {
writer.close();
}
if ( outputStream != null ) {
outputStream.close();
}
} catch ( IOException e ) {
throw new KettleException( "Error closing file " + dataSetFilename + " : ", e );
}
}
}
public static CSVFormat getCsvFormat( RowMetaInterface rowMeta ) {
return CSVFormat.DEFAULT.withHeader( rowMeta.getFieldNames() ).withQuote( '\"' ).withQuoteMode( QuoteMode.MINIMAL );
}
public static void createTable( DataSetGroup group, String tableName, RowMetaInterface rowMeta ) throws KettleDatabaseException {
// Not needed with files
}
}
|
src/main/java/org/pentaho/di/dataset/DataSetCsvGroup.java
|
package org.pentaho.di.dataset;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.csv.QuoteMode;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.vfs2.FileObject;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.logging.LoggingObjectInterface;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaString;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.core.vfs.KettleVFS;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* The implementation of a CSV Data Set Group
* We simply write/read the rows without a header into a file defined by the tableName in the data set
*/
public class DataSetCsvGroup {
public static final String VARIABLE_DATASETS_BASE_PATH = "DATASETS_BASE_PATH";
/**
* Get the base folder for the data set group
*
* @param group
* @return
*/
private static String getDataSetFolder( DataSetGroup group ) {
String folderName = group.getFolderName();
if ( StringUtils.isEmpty( folderName ) ) {
folderName = System.getProperty( VARIABLE_DATASETS_BASE_PATH );
}
if ( StringUtils.isEmpty( folderName ) ) {
// Local folder
folderName = ".";
} else {
// Let's not forget to replace variables as well...
//
VariableSpace space = Variables.getADefaultVariableSpace();
folderName = space.environmentSubstitute( folderName );
}
if ( !folderName.endsWith( File.separator ) ) {
folderName += File.separator;
}
return folderName;
}
private static void setValueFormats( RowMetaInterface rowMeta ) {
for ( ValueMetaInterface valueMeta : rowMeta.getValueMetaList() ) {
if ( StringUtils.isEmpty( valueMeta.getConversionMask() ) ) {
switch ( valueMeta.getType() ) {
case ValueMetaInterface.TYPE_INTEGER:
valueMeta.setConversionMask( "0" );
break;
case ValueMetaInterface.TYPE_NUMBER:
valueMeta.setConversionMask( "0.#" );
break;
case ValueMetaInterface.TYPE_DATE:
valueMeta.setConversionMask( "yyyyMMdd-HHmmss.SSS" );
break;
default:
break;
}
}
}
}
public static String getDataSetFilename( DataSetGroup dataSetGroup, String tableName ) {
String setFolderName = getDataSetFolder( dataSetGroup );
setFolderName += tableName + ".csv";
return setFolderName;
}
public static final List<Object[]> getAllRows( LogChannelInterface log, DataSetGroup group, DataSet dataSet ) throws KettleException {
RowMetaInterface setRowMeta = dataSet.getSetRowMeta( true );
setValueFormats( setRowMeta );
String dataSetFilename = getDataSetFilename( group, dataSet.getTableName() );
List<Object[]> rows = new ArrayList<>();
final ValueMetaString constantValueMeta = new ValueMetaString( "constant" );
try {
FileObject file = KettleVFS.getFileObject( dataSetFilename );
if ( !file.exists() ) {
// This is fine. We haven't put rows in yet.
//
return rows;
}
try (
Reader reader = new InputStreamReader( new BufferedInputStream( KettleVFS.getInputStream( file ) ) );
CSVParser csvParser = new CSVParser( reader, getCsvFormat( setRowMeta ) );
) {
for ( CSVRecord csvRecord : csvParser ) {
if ( csvRecord.getRecordNumber() > 1 ) {
Object[] row = RowDataUtil.allocateRowData( setRowMeta.size() );
for ( int i = 0; i < setRowMeta.size(); i++ ) {
ValueMetaInterface valueMeta = setRowMeta.getValueMeta( i ).clone();
constantValueMeta.setConversionMetadata( valueMeta );
String value = csvRecord.get( i );
row[ i ] = valueMeta.convertData( constantValueMeta, value );
}
rows.add( row );
}
}
}
return rows;
} catch ( Exception e ) {
throw new KettleException( "Unable to get all rows for CSV data set '" + dataSet.getName() + "'", e );
}
}
/**
* Get the rows for this data set in the format of the data set.
*
* @param log the logging channel to which you can write.
* @param location The fields to obtain in the order given
* @return The rows for the given location
* @throws KettleException
*/
public static final List<Object[]> getAllRows( LogChannelInterface log, DataSetGroup group, DataSet dataSet, TransUnitTestSetLocation location ) throws KettleException {
RowMetaInterface setRowMeta = dataSet.getSetRowMeta( false );
// The row description of the output of this step...
//
final RowMetaInterface outputRowMeta = dataSet.getMappedDataSetFieldsRowMeta( location );
setValueFormats( setRowMeta );
String dataSetFilename = getDataSetFilename( group, dataSet.getTableName() );
List<Object[]> rows = new ArrayList<>();
final ValueMetaString constantValueMeta = new ValueMetaString( "constant" );
try {
FileObject file = KettleVFS.getFileObject( dataSetFilename );
if ( !file.exists() ) {
// This is fine. We haven't put rows in yet.
//
return rows;
}
List<String> sortFields = location.getFieldOrder();
// See how we mapped the fields
//
List<TransUnitTestFieldMapping> fieldMappings = location.getFieldMappings();
int[] dataSetFieldIndexes = new int[ fieldMappings.size() ];
for ( int i = 0; i < fieldMappings.size(); i++ ) {
TransUnitTestFieldMapping fieldMapping = fieldMappings.get( i );
String dataSetFieldName = fieldMapping.getDataSetFieldName();
dataSetFieldIndexes[ i ] = setRowMeta.indexOfValue( dataSetFieldName );
}
try (
Reader reader = new InputStreamReader( new BufferedInputStream( KettleVFS.getInputStream( file ) ) );
CSVParser csvParser = new CSVParser( reader, CSVFormat.DEFAULT );
) {
for ( CSVRecord csvRecord : csvParser ) {
if ( csvRecord.getRecordNumber() > 1 ) {
Object[] row = RowDataUtil.allocateRowData( dataSetFieldIndexes.length );
// Only get certain values...
//
for ( int i = 0; i < dataSetFieldIndexes.length; i++ ) {
int index = dataSetFieldIndexes[ i ];
ValueMetaInterface valueMeta = setRowMeta.getValueMeta( index );
String value = csvRecord.get( index );
row[ i ] = valueMeta.convertDataFromString( value, constantValueMeta, null, null, ValueMetaInterface.TRIM_TYPE_NONE );
}
rows.add( row );
}
}
}
// Which fields are we sorting on (if any)
//
int[] sortIndexes = new int[ sortFields.size() ];
for ( int i = 0; i < sortIndexes.length; i++ ) {
sortIndexes[ i ] = outputRowMeta.indexOfValue( sortFields.get( i ) );
}
if ( outputRowMeta.isEmpty() ) {
log.logError( "WARNING: No field mappings selected for data set '" + dataSet.getName() + "', returning empty set of rows" );
return new ArrayList<>();
}
if ( !sortFields.isEmpty() ) {
// Sort the rows...
//
Collections.sort( rows, new Comparator<Object[]>() {
@Override public int compare( Object[] o1, Object[] o2 ) {
try {
return outputRowMeta.compare( o1, o2, sortIndexes );
} catch ( KettleValueException e ) {
throw new RuntimeException( "Unable to compare 2 rows", e );
}
}
} );
}
return rows;
} catch (
Exception e ) {
throw new KettleException( "Unable to get all rows for database data set '" + dataSet.getName() + "'", e );
}
}
public static final void writeDataSetData( LoggingObjectInterface loggingObject, DataSetGroup dataSetGroup, String tableName,
RowMetaInterface rowMeta, List<Object[]> rows ) throws KettleException {
String dataSetFilename = getDataSetFilename( dataSetGroup, tableName );
RowMetaInterface setRowMeta = rowMeta.clone(); // just making sure
setValueFormats( setRowMeta );
OutputStream outputStream = null;
BufferedWriter writer = null;
CSVPrinter csvPrinter = null;
try {
FileObject file = KettleVFS.getFileObject( dataSetFilename );
outputStream = KettleVFS.getOutputStream( file, false );
writer = new BufferedWriter( new OutputStreamWriter( outputStream ) );
CSVFormat csvFormat = getCsvFormat( rowMeta );
csvPrinter = new CSVPrinter( writer, csvFormat );
for ( Object[] row : rows ) {
List<String> strings = new ArrayList<>();
for ( int i = 0; i < setRowMeta.size(); i++ ) {
ValueMetaInterface valueMeta = setRowMeta.getValueMeta( i );
String string = valueMeta.getString( row[ i ] );
strings.add( string );
}
csvPrinter.printRecord( strings );
}
csvPrinter.flush();
} catch ( Exception e ) {
throw new KettleException( "Unable to write data set to file '" + dataSetFilename + "'", e );
} finally {
try {
if ( csvPrinter != null ) {
csvPrinter.close();
}
if ( writer != null ) {
writer.close();
}
if ( outputStream != null ) {
outputStream.close();
}
} catch ( IOException e ) {
throw new KettleException( "Error closing file " + dataSetFilename + " : ", e );
}
}
}
public static CSVFormat getCsvFormat( RowMetaInterface rowMeta ) {
return CSVFormat.DEFAULT.withHeader( rowMeta.getFieldNames() ).withQuote( '\"' ).withQuoteMode( QuoteMode.MINIMAL );
}
public static void createTable( DataSetGroup group, String tableName, RowMetaInterface rowMeta ) throws KettleDatabaseException {
// Not needed with files
}
}
|
Issue #49 : allow format masks
|
src/main/java/org/pentaho/di/dataset/DataSetCsvGroup.java
|
Issue #49 : allow format masks
|
|
Java
|
apache-2.0
|
91f5cc927cdbaa32f62a14f0189277ad9f01b0a3
| 0
|
dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android
|
package org.commcare.models.database.user;
import android.content.Context;
import android.util.Log;
import net.sqlcipher.database.SQLiteDatabase;
import org.commcare.CommCareApplication;
import org.commcare.android.database.user.models.FormRecordV2;
import org.commcare.android.logging.ForceCloseLogEntry;
import org.commcare.android.javarosa.AndroidLogEntry;
import org.commcare.logging.XPathErrorEntry;
import org.commcare.models.database.AndroidTableBuilder;
import org.commcare.models.database.ConcreteAndroidDbHelper;
import org.commcare.models.database.DbUtil;
import org.commcare.models.database.IndexedFixturePathUtils;
import org.commcare.models.database.SqlStorage;
import org.commcare.models.database.SqlStorageIterator;
import org.commcare.models.database.migration.FixtureSerializationMigration;
import org.commcare.android.database.user.models.ACase;
import org.commcare.android.database.user.models.ACasePreV6Model;
import org.commcare.android.database.user.models.AUser;
import org.commcare.models.database.user.models.AndroidCaseIndexTable;
import org.commcare.models.database.user.models.EntityStorageCache;
import org.commcare.android.database.user.models.FormRecord;
import org.commcare.android.database.user.models.FormRecordV1;
import org.commcare.android.database.user.models.GeocodeCacheModel;
import org.commcare.modern.database.DatabaseIndexingUtils;
import org.javarosa.core.model.User;
import org.javarosa.core.services.storage.Persistable;
import java.util.Vector;
/**
* @author ctsims
*/
class UserDatabaseUpgrader {
private static final String TAG = UserDatabaseUpgrader.class.getSimpleName();
private boolean inSenseMode = false;
private final Context c;
private final byte[] fileMigrationKey;
private final String userKeyRecordId;
public UserDatabaseUpgrader(Context c, String userKeyRecordId, boolean inSenseMode, byte[] fileMigrationKey) {
this.c = c;
this.userKeyRecordId = userKeyRecordId;
this.inSenseMode = inSenseMode;
this.fileMigrationKey = fileMigrationKey;
}
public void upgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1) {
if (upgradeOneTwo(db)) {
oldVersion = 2;
}
}
if (oldVersion == 2) {
if (upgradeTwoThree(db)) {
oldVersion = 3;
}
}
if (oldVersion == 3) {
if (upgradeThreeFour(db)) {
oldVersion = 4;
}
}
if (oldVersion == 4) {
if (upgradeFourFive(db)) {
oldVersion = 5;
}
}
if (oldVersion == 5) {
if (upgradeFiveSix(db)) {
oldVersion = 6;
}
}
if (oldVersion == 6) {
if (upgradeSixSeven(db)) {
oldVersion = 7;
}
}
if (oldVersion == 7) {
if (upgradeSevenEight(db)) {
oldVersion = 8;
}
}
if (oldVersion == 8) {
if (upgradeEightNine(db)) {
oldVersion = 9;
}
}
if (oldVersion == 9) {
if (upgradeNineTen(db)) {
oldVersion = 10;
}
}
if (oldVersion == 10) {
if (upgradeTenEleven(db)) {
oldVersion = 11;
}
}
if (oldVersion == 11) {
if (upgradeElevenTwelve(db)) {
oldVersion = 12;
}
}
if (oldVersion == 12) {
if (upgradeTwelveThirteen(db)) {
oldVersion = 13;
}
}
if (oldVersion == 13) {
if (upgradeThirteenFourteen(db)) {
oldVersion = 14;
}
}
if (oldVersion == 14) {
if (upgradeFourteenFifteen(db)) {
oldVersion = 15;
}
}
if (oldVersion == 15) {
if (upgradeFifteenSixteen(db)) {
oldVersion = 16;
}
}
if (oldVersion == 16) {
if (upgradeSixteenSeventeen(db)) {
oldVersion = 17;
}
}
}
private boolean upgradeOneTwo(final SQLiteDatabase db) {
db.beginTransaction();
try {
markSenseIncompleteUnsent(db);
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private boolean upgradeTwoThree(final SQLiteDatabase db) {
db.beginTransaction();
try {
markSenseIncompleteUnsent(db);
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private boolean upgradeThreeFour(SQLiteDatabase db) {
db.beginTransaction();
try {
UserDbUpgradeUtils.addStockTable(db);
UserDbUpgradeUtils.updateIndexes(db);
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private boolean upgradeFourFive(SQLiteDatabase db) {
db.beginTransaction();
try {
db.execSQL(DatabaseIndexingUtils.indexOnTableCommand("ledger_entity_id", "ledger", "entity_id"));
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private boolean upgradeFiveSix(SQLiteDatabase db) {
//On some devices this process takes a significant amount of time (sorry!) we should
//tell the service to wait longer to make sure this can finish.
CommCareApplication.instance().setCustomServiceBindTimeout(60 * 5 * 1000);
db.beginTransaction();
try {
db.execSQL(DatabaseIndexingUtils.indexOnTableCommand("case_status_open_index", "AndroidCase", "case_type,case_status"));
DbUtil.createNumbersTable(db);
db.execSQL(EntityStorageCache.getTableDefinition());
EntityStorageCache.createIndexes(db);
db.execSQL(AndroidCaseIndexTable.getTableDefinition());
AndroidCaseIndexTable.createIndexes(db);
AndroidCaseIndexTable cit = new AndroidCaseIndexTable(db);
//NOTE: Need to use the PreV6 case model any time we manipulate cases in this model for upgraders
//below 6
SqlStorage<ACase> caseStorage = new SqlStorage<ACase>(ACase.STORAGE_KEY, ACasePreV6Model.class, new ConcreteAndroidDbHelper(c, db));
for (ACase c : caseStorage) {
cit.indexCase(c);
}
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private boolean upgradeSixSeven(SQLiteDatabase db) {
//On some devices this process takes a significant amount of time (sorry!) we should
//tell the service to wait longer to make sure this can finish.
CommCareApplication.instance().setCustomServiceBindTimeout(60 * 5 * 1000);
long start = System.currentTimeMillis();
db.beginTransaction();
try {
SqlStorage<ACase> caseStorage = new SqlStorage<ACase>(ACase.STORAGE_KEY, ACasePreV6Model.class, new ConcreteAndroidDbHelper(c, db));
updateModels(caseStorage);
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
Log.d(TAG, "Case model update complete in " + (System.currentTimeMillis() - start) + "ms");
}
}
/**
* Depcrecate the old AUser object so that both platforms are using the User object
* to represents users
*/
private boolean upgradeSevenEight(SQLiteDatabase db) {
//On some devices this process takes a significant amount of time (sorry!) we should
//tell the service to wait longer to make sure this can finish.
CommCareApplication.instance().setCustomServiceBindTimeout(60 * 5 * 1000);
long start = System.currentTimeMillis();
db.beginTransaction();
try {
SqlStorage<Persistable> userStorage = new SqlStorage<Persistable>(AUser.STORAGE_KEY, AUser.class, new ConcreteAndroidDbHelper(c, db));
SqlStorageIterator<Persistable> iterator = userStorage.iterate();
while (iterator.hasMore()) {
AUser oldUser = (AUser)iterator.next();
User newUser = oldUser.toNewUser();
userStorage.write(newUser);
}
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
Log.d(TAG, "Case model update complete in " + (System.currentTimeMillis() - start) + "ms");
}
}
/*
* Deserialize user fixtures in db using old form instance serialization
* scheme, and re-serialize them using the new scheme that preserves
* attributes.
*/
private boolean upgradeEightNine(SQLiteDatabase db) {
Log.d(TAG, "starting user fixture migration");
FixtureSerializationMigration.stageFixtureTables(db);
boolean didFixturesMigrate =
FixtureSerializationMigration.migrateFixtureDbBytes(db, c, userKeyRecordId, fileMigrationKey);
FixtureSerializationMigration.dropTempFixtureTable(db);
return didFixturesMigrate;
}
/**
* Adding an appId field to FormRecords, for compatibility with multiple apps functionality
*/
private boolean upgradeNineTen(SQLiteDatabase db) {
// This process could take a while, so tell the service to wait longer to make sure
// it can finish
CommCareApplication.instance().setCustomServiceBindTimeout(60 * 5 * 1000);
db.beginTransaction();
try {
if (UserDbUpgradeUtils.multipleInstalledAppRecords()) {
// Cannot migrate FormRecords once this device has already started installing
// multiple applications, because there is no way to know which of those apps the
// existing FormRecords belong to
UserDbUpgradeUtils.deleteExistingFormRecordsAndWarnUser(c, db);
UserDbUpgradeUtils.addAppIdColumnToTable(db);
db.setTransactionSuccessful();
return true;
}
SqlStorage<FormRecordV1> oldStorage = new SqlStorage<>(
FormRecord.STORAGE_KEY,
FormRecordV1.class,
new ConcreteAndroidDbHelper(c, db));
String appId = UserDbUpgradeUtils.getInstalledAppRecord().getApplicationId();
Vector<FormRecordV2> upgradedRecords = new Vector<>();
// Create all of the updated records, based upon the existing ones
for (FormRecordV1 oldRecord : oldStorage) {
FormRecordV2 newRecord = new FormRecordV2(
oldRecord.getInstanceURIString(),
oldRecord.getStatus(),
oldRecord.getFormNamespace(),
oldRecord.getAesKey(),
oldRecord.getInstanceID(),
oldRecord.lastModified(),
appId);
newRecord.setID(oldRecord.getID());
upgradedRecords.add(newRecord);
}
UserDbUpgradeUtils.addAppIdColumnToTable(db);
// Write all of the new records to the updated table
SqlStorage<FormRecordV2> newStorage = new SqlStorage<>(
FormRecord.STORAGE_KEY,
FormRecordV2.class,
new ConcreteAndroidDbHelper(c, db));
for (FormRecordV2 r : upgradedRecords) {
newStorage.write(r);
}
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private boolean upgradeTenEleven(SQLiteDatabase db) {
db.beginTransaction();
try {
// add table for dedicated xpath error logging for reporting xpath
// errors on specific cc app builds.
AndroidTableBuilder builder = new AndroidTableBuilder(XPathErrorEntry.STORAGE_KEY);
builder.addData(new XPathErrorEntry());
db.execSQL(builder.getTableCreateString());
db.setTransactionSuccessful();
return true;
} catch (Exception e) {
return false;
} finally {
db.endTransaction();
}
}
private boolean upgradeElevenTwelve(SQLiteDatabase db) {
db.beginTransaction();
try {
db.execSQL("DROP TABLE IF EXISTS " + GeocodeCacheModel.STORAGE_KEY);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return true;
}
private boolean upgradeTwelveThirteen(SQLiteDatabase db) {
db.beginTransaction();
try {
AndroidTableBuilder builder = new AndroidTableBuilder(AndroidLogEntry.STORAGE_KEY);
builder.addData(new AndroidLogEntry());
db.execSQL(builder.getTableCreateString());
builder = new AndroidTableBuilder(ForceCloseLogEntry.STORAGE_KEY);
builder.addData(new ForceCloseLogEntry());
db.execSQL(builder.getTableCreateString());
db.setTransactionSuccessful();
return true;
} catch (Exception e) {
return false;
} finally {
db.endTransaction();
}
}
private boolean upgradeThirteenFourteen(SQLiteDatabase db) {
// This process could take a while, so tell the service to wait longer
// to make sure it can finish
CommCareApplication.instance().setCustomServiceBindTimeout(60 * 5 * 1000);
db.beginTransaction();
try {
SqlStorage<FormRecord> formRecordSqlStorage = new SqlStorage<>(
FormRecord.STORAGE_KEY,
FormRecord.class,
new ConcreteAndroidDbHelper(c, db));
// Re-store all the form records, forcing new date representation
// to be used. Must happen proactively because the date parsing
// code was updated to handle new representation
for (FormRecord formRecord : formRecordSqlStorage) {
formRecordSqlStorage.write(formRecord);
}
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private boolean upgradeFourteenFifteen(SQLiteDatabase db) {
db.beginTransaction();
try {
IndexedFixturePathUtils.createStorageBackedFixtureIndexTable(db);
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private boolean upgradeFifteenSixteen(SQLiteDatabase db) {
db.beginTransaction();
try {
String typeFirstIndexId = "NAME_TARGET_RECORD";
String typeFirstIndex = "name" + ", " + "case_rec_id" + ", " + "target";
db.execSQL(DatabaseIndexingUtils.indexOnTableCommand(typeFirstIndexId, "case_index_storage", typeFirstIndex));
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
/**
* Add a metadata field to all form records for "form number" that will be used for ordering
* submissions. Since submissions were previously ordered by the last modified property,
* set the new form numbers in this order.
*/
private boolean upgradeSixteenSeventeen(SQLiteDatabase db) {
db.beginTransaction();
try {
SqlStorage<FormRecordV2> oldStorage = new SqlStorage<>(
FormRecord.STORAGE_KEY,
FormRecordV2.class,
new ConcreteAndroidDbHelper(c, db));
// Sort the old record ids by their last modified date, which is how form submission
// ordering was previously done
Vector<Integer> recordIds = oldStorage.getIDsForAllRecords();
UserDbUpgradeUtils.sortRecordsByDate(recordIds, oldStorage);
Vector<FormRecord> upgradedRecords = new Vector<>();
for (int i = 0; i < recordIds.size(); i++) {
FormRecordV2 oldRecord = oldStorage.read(recordIds.elementAt(i));
FormRecord newRecord = new FormRecord(
oldRecord.getInstanceURIString(),
oldRecord.getStatus(),
oldRecord.getFormNamespace(),
oldRecord.getAesKey(),
oldRecord.getInstanceID(),
oldRecord.lastModified(),
oldRecord.getAppId());
String statusOfOldRecord = oldRecord.getStatus();
if (FormRecord.STATUS_COMPLETE.equals(statusOfOldRecord) ||
FormRecord.STATUS_UNSENT.equals(statusOfOldRecord)) {
// By processing the old records in order of their last modified date, we make
// sure that we are setting this form numbers in the most accurate order we can
newRecord.setFormNumberForSubmissionOrdering();
}
upgradedRecords.add(newRecord);
}
// Add new column to db and then write all of the new records
UserDbUpgradeUtils.addFormNumberColumnToTable(db);
SqlStorage<FormRecord> newStorage = new SqlStorage<>(
FormRecord.STORAGE_KEY,
FormRecord.class,
new ConcreteAndroidDbHelper(c, db));
for (FormRecord r : upgradedRecords) {
newStorage.write(r);
}
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private void markSenseIncompleteUnsent(final SQLiteDatabase db) {
//Fix for Bug in 2.7.0/1, forms in sense mode weren't being properly marked as complete after entry.
if (inSenseMode) {
//Get form record storage
SqlStorage<FormRecord> storage = new SqlStorage<>(FormRecord.STORAGE_KEY, FormRecord.class, new ConcreteAndroidDbHelper(c, db));
//Iterate through all forms currently saved
for (FormRecord record : storage) {
//Update forms marked as incomplete with the appropriate status
if (FormRecord.STATUS_INCOMPLETE.equals(record.getStatus())) {
//update to complete to process/send.
storage.write(record.updateInstanceAndStatus(record.getInstanceURI().toString(), FormRecord.STATUS_COMPLETE));
}
}
}
}
/**
* Reads and rewrites all of the records in a table, generally to adapt an old serialization format to a new
* format
*/
private <T extends Persistable> void updateModels(SqlStorage<T> storage) {
for (T t : storage) {
storage.write(t);
}
}
}
|
app/src/org/commcare/models/database/user/UserDatabaseUpgrader.java
|
package org.commcare.models.database.user;
import android.content.Context;
import android.util.Log;
import net.sqlcipher.database.SQLiteDatabase;
import org.commcare.CommCareApplication;
import org.commcare.android.database.user.models.FormRecordV2;
import org.commcare.android.logging.ForceCloseLogEntry;
import org.commcare.android.javarosa.AndroidLogEntry;
import org.commcare.logging.XPathErrorEntry;
import org.commcare.models.database.AndroidTableBuilder;
import org.commcare.models.database.ConcreteAndroidDbHelper;
import org.commcare.models.database.DbUtil;
import org.commcare.models.database.IndexedFixturePathUtils;
import org.commcare.models.database.SqlStorage;
import org.commcare.models.database.SqlStorageIterator;
import org.commcare.models.database.migration.FixtureSerializationMigration;
import org.commcare.android.database.user.models.ACase;
import org.commcare.android.database.user.models.ACasePreV6Model;
import org.commcare.android.database.user.models.AUser;
import org.commcare.models.database.user.models.AndroidCaseIndexTable;
import org.commcare.models.database.user.models.EntityStorageCache;
import org.commcare.android.database.user.models.FormRecord;
import org.commcare.android.database.user.models.FormRecordV1;
import org.commcare.android.database.user.models.GeocodeCacheModel;
import org.commcare.modern.database.DatabaseIndexingUtils;
import org.javarosa.core.model.User;
import org.javarosa.core.services.storage.Persistable;
import java.util.Vector;
/**
* @author ctsims
*/
class UserDatabaseUpgrader {
private static final String TAG = UserDatabaseUpgrader.class.getSimpleName();
private boolean inSenseMode = false;
private final Context c;
private final byte[] fileMigrationKey;
private final String userKeyRecordId;
public UserDatabaseUpgrader(Context c, String userKeyRecordId, boolean inSenseMode, byte[] fileMigrationKey) {
this.c = c;
this.userKeyRecordId = userKeyRecordId;
this.inSenseMode = inSenseMode;
this.fileMigrationKey = fileMigrationKey;
}
public void upgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1) {
if (upgradeOneTwo(db)) {
oldVersion = 2;
}
}
if (oldVersion == 2) {
if (upgradeTwoThree(db)) {
oldVersion = 3;
}
}
if (oldVersion == 3) {
if (upgradeThreeFour(db)) {
oldVersion = 4;
}
}
if (oldVersion == 4) {
if (upgradeFourFive(db)) {
oldVersion = 5;
}
}
if (oldVersion == 5) {
if (upgradeFiveSix(db)) {
oldVersion = 6;
}
}
if (oldVersion == 6) {
if (upgradeSixSeven(db)) {
oldVersion = 7;
}
}
if (oldVersion == 7) {
if (upgradeSevenEight(db)) {
oldVersion = 8;
}
}
if (oldVersion == 8) {
if (upgradeEightNine(db)) {
oldVersion = 9;
}
}
if (oldVersion == 9) {
if (upgradeNineTen(db)) {
oldVersion = 10;
}
}
if (oldVersion == 10) {
if (upgradeTenEleven(db)) {
oldVersion = 11;
}
}
if (oldVersion == 11) {
if (upgradeElevenTwelve(db)) {
oldVersion = 12;
}
}
if (oldVersion == 12) {
if (upgradeTwelveThirteen(db)) {
oldVersion = 13;
}
}
if (oldVersion == 13) {
if (upgradeThirteenFourteen(db)) {
oldVersion = 14;
}
}
if (oldVersion == 14) {
if (upgradeFourteenFifteen(db)) {
oldVersion = 15;
}
}
if (oldVersion == 15) {
if (upgradeFifteenSixteen(db)) {
oldVersion = 16;
}
}
if (oldVersion == 16) {
if (upgradeSixteenSeventeen(db)) {
oldVersion = 17;
}
}
}
private boolean upgradeOneTwo(final SQLiteDatabase db) {
db.beginTransaction();
try {
markSenseIncompleteUnsent(db);
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private boolean upgradeTwoThree(final SQLiteDatabase db) {
db.beginTransaction();
try {
markSenseIncompleteUnsent(db);
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private boolean upgradeThreeFour(SQLiteDatabase db) {
db.beginTransaction();
try {
UserDbUpgradeUtils.addStockTable(db);
UserDbUpgradeUtils.updateIndexes(db);
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private boolean upgradeFourFive(SQLiteDatabase db) {
db.beginTransaction();
try {
db.execSQL(DatabaseIndexingUtils.indexOnTableCommand("ledger_entity_id", "ledger", "entity_id"));
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private boolean upgradeFiveSix(SQLiteDatabase db) {
//On some devices this process takes a significant amount of time (sorry!) we should
//tell the service to wait longer to make sure this can finish.
CommCareApplication.instance().setCustomServiceBindTimeout(60 * 5 * 1000);
db.beginTransaction();
try {
db.execSQL(DatabaseIndexingUtils.indexOnTableCommand("case_status_open_index", "AndroidCase", "case_type,case_status"));
DbUtil.createNumbersTable(db);
db.execSQL(EntityStorageCache.getTableDefinition());
EntityStorageCache.createIndexes(db);
db.execSQL(AndroidCaseIndexTable.getTableDefinition());
AndroidCaseIndexTable.createIndexes(db);
AndroidCaseIndexTable cit = new AndroidCaseIndexTable(db);
//NOTE: Need to use the PreV6 case model any time we manipulate cases in this model for upgraders
//below 6
SqlStorage<ACase> caseStorage = new SqlStorage<ACase>(ACase.STORAGE_KEY, ACasePreV6Model.class, new ConcreteAndroidDbHelper(c, db));
for (ACase c : caseStorage) {
cit.indexCase(c);
}
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private boolean upgradeSixSeven(SQLiteDatabase db) {
//On some devices this process takes a significant amount of time (sorry!) we should
//tell the service to wait longer to make sure this can finish.
CommCareApplication.instance().setCustomServiceBindTimeout(60 * 5 * 1000);
long start = System.currentTimeMillis();
db.beginTransaction();
try {
SqlStorage<ACase> caseStorage = new SqlStorage<ACase>(ACase.STORAGE_KEY, ACasePreV6Model.class, new ConcreteAndroidDbHelper(c, db));
updateModels(caseStorage);
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
Log.d(TAG, "Case model update complete in " + (System.currentTimeMillis() - start) + "ms");
}
}
/**
* Depcrecate the old AUser object so that both platforms are using the User object
* to represents users
*/
private boolean upgradeSevenEight(SQLiteDatabase db) {
//On some devices this process takes a significant amount of time (sorry!) we should
//tell the service to wait longer to make sure this can finish.
CommCareApplication.instance().setCustomServiceBindTimeout(60 * 5 * 1000);
long start = System.currentTimeMillis();
db.beginTransaction();
try {
SqlStorage<Persistable> userStorage = new SqlStorage<Persistable>(AUser.STORAGE_KEY, AUser.class, new ConcreteAndroidDbHelper(c, db));
SqlStorageIterator<Persistable> iterator = userStorage.iterate();
while (iterator.hasMore()) {
AUser oldUser = (AUser)iterator.next();
User newUser = oldUser.toNewUser();
userStorage.write(newUser);
}
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
Log.d(TAG, "Case model update complete in " + (System.currentTimeMillis() - start) + "ms");
}
}
/*
* Deserialize user fixtures in db using old form instance serialization
* scheme, and re-serialize them using the new scheme that preserves
* attributes.
*/
private boolean upgradeEightNine(SQLiteDatabase db) {
Log.d(TAG, "starting user fixture migration");
FixtureSerializationMigration.stageFixtureTables(db);
boolean didFixturesMigrate =
FixtureSerializationMigration.migrateFixtureDbBytes(db, c, userKeyRecordId, fileMigrationKey);
FixtureSerializationMigration.dropTempFixtureTable(db);
return didFixturesMigrate;
}
/**
* Adding an appId field to FormRecords, for compatibility with multiple apps functionality
*/
private boolean upgradeNineTen(SQLiteDatabase db) {
// This process could take a while, so tell the service to wait longer to make sure
// it can finish
CommCareApplication.instance().setCustomServiceBindTimeout(60 * 5 * 1000);
db.beginTransaction();
try {
if (UserDbUpgradeUtils.multipleInstalledAppRecords()) {
// Cannot migrate FormRecords once this device has already started installing
// multiple applications, because there is no way to know which of those apps the
// existing FormRecords belong to
UserDbUpgradeUtils.deleteExistingFormRecordsAndWarnUser(c, db);
UserDbUpgradeUtils.addAppIdColumnToTable(db);
db.setTransactionSuccessful();
return true;
}
SqlStorage<FormRecordV1> oldStorage = new SqlStorage<>(
FormRecord.STORAGE_KEY,
FormRecordV1.class,
new ConcreteAndroidDbHelper(c, db));
String appId = UserDbUpgradeUtils.getInstalledAppRecord().getApplicationId();
Vector<FormRecordV2> upgradedRecords = new Vector<>();
// Create all of the updated records, based upon the existing ones
for (FormRecordV1 oldRecord : oldStorage) {
FormRecordV2 newRecord = new FormRecordV2(
oldRecord.getInstanceURIString(),
oldRecord.getStatus(),
oldRecord.getFormNamespace(),
oldRecord.getAesKey(),
oldRecord.getInstanceID(),
oldRecord.lastModified(),
appId);
newRecord.setID(oldRecord.getID());
upgradedRecords.add(newRecord);
}
UserDbUpgradeUtils.addAppIdColumnToTable(db);
// Write all of the new records to the updated table
SqlStorage<FormRecordV2> newStorage = new SqlStorage<>(
FormRecord.STORAGE_KEY,
FormRecordV2.class,
new ConcreteAndroidDbHelper(c, db));
for (FormRecordV2 r : upgradedRecords) {
newStorage.write(r);
}
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private boolean upgradeTenEleven(SQLiteDatabase db) {
db.beginTransaction();
try {
// add table for dedicated xpath error logging for reporting xpath
// errors on specific cc app builds.
AndroidTableBuilder builder = new AndroidTableBuilder(XPathErrorEntry.STORAGE_KEY);
builder.addData(new XPathErrorEntry());
db.execSQL(builder.getTableCreateString());
db.setTransactionSuccessful();
return true;
} catch (Exception e) {
return false;
} finally {
db.endTransaction();
}
}
private boolean upgradeElevenTwelve(SQLiteDatabase db) {
db.beginTransaction();
try {
db.execSQL("DROP TABLE IF EXISTS " + GeocodeCacheModel.STORAGE_KEY);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return true;
}
private boolean upgradeTwelveThirteen(SQLiteDatabase db) {
db.beginTransaction();
try {
AndroidTableBuilder builder = new AndroidTableBuilder(AndroidLogEntry.STORAGE_KEY);
builder.addData(new AndroidLogEntry());
db.execSQL(builder.getTableCreateString());
builder = new AndroidTableBuilder(ForceCloseLogEntry.STORAGE_KEY);
builder.addData(new ForceCloseLogEntry());
db.execSQL(builder.getTableCreateString());
db.setTransactionSuccessful();
return true;
} catch (Exception e) {
return false;
} finally {
db.endTransaction();
}
}
private boolean upgradeThirteenFourteen(SQLiteDatabase db) {
// This process could take a while, so tell the service to wait longer
// to make sure it can finish
CommCareApplication.instance().setCustomServiceBindTimeout(60 * 5 * 1000);
db.beginTransaction();
try {
SqlStorage<FormRecord> formRecordSqlStorage = new SqlStorage<>(
FormRecord.STORAGE_KEY,
FormRecord.class,
new ConcreteAndroidDbHelper(c, db));
// Re-store all the form records, forcing new date representation
// to be used. Must happen proactively because the date parsing
// code was updated to handle new representation
for (FormRecord formRecord : formRecordSqlStorage) {
formRecordSqlStorage.write(formRecord);
}
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private boolean upgradeFourteenFifteen(SQLiteDatabase db) {
db.beginTransaction();
try {
IndexedFixturePathUtils.createStorageBackedFixtureIndexTable(db);
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private boolean upgradeFifteenSixteen(SQLiteDatabase db) {
db.beginTransaction();
try {
String typeFirstIndexId = "NAME_TARGET_RECORD";
String typeFirstIndex = "name" + ", " + "case_rec_id" + ", " + "target";
db.execSQL(DatabaseIndexingUtils.indexOnTableCommand(typeFirstIndexId, "case_index_storage", typeFirstIndex));
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
/**
* Add a metadata field to all form records for "form number" that will be used for ordering
* submissions. Since submissions were previously ordered by the last modified property,
* set the new form numbers in this order.
*/
private boolean upgradeSixteenSeventeen(SQLiteDatabase db) {
db.beginTransaction();
try {
SqlStorage<FormRecordV2> oldStorage = new SqlStorage<>(
FormRecord.STORAGE_KEY,
FormRecordV2.class,
new ConcreteAndroidDbHelper(c, db));
// Sort the old record ids by their last modified date, which is how form submission
// ordering was previously done
Vector<Integer> recordIds = oldStorage.getIDsForAllRecords();
UserDbUpgradeUtils.sortRecordsByDate(recordIds, oldStorage);
Vector<FormRecord> upgradedRecords = new Vector<>();
for (int i = 0; i < recordIds.size(); i++) {
FormRecordV2 oldRecord = oldStorage.read(recordIds.elementAt(i));
FormRecord newRecord = new FormRecord(
oldRecord.getInstanceURIString(),
oldRecord.getStatus(),
oldRecord.getFormNamespace(),
oldRecord.getAesKey(),
oldRecord.getInstanceID(),
oldRecord.lastModified(),
oldRecord.getAppId());
// By processing the old records in order of their last modified date, we make sure
// that we are setting this form numbers in the most accurate order we can
newRecord.setFormNumberForSubmissionOrdering();
upgradedRecords.add(newRecord);
}
// Add new column to db and then write all of the new records
UserDbUpgradeUtils.addFormNumberColumnToTable(db);
SqlStorage<FormRecord> newStorage = new SqlStorage<>(
FormRecord.STORAGE_KEY,
FormRecord.class,
new ConcreteAndroidDbHelper(c, db));
for (FormRecord r : upgradedRecords) {
newStorage.write(r);
}
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
}
}
private void markSenseIncompleteUnsent(final SQLiteDatabase db) {
//Fix for Bug in 2.7.0/1, forms in sense mode weren't being properly marked as complete after entry.
if (inSenseMode) {
//Get form record storage
SqlStorage<FormRecord> storage = new SqlStorage<>(FormRecord.STORAGE_KEY, FormRecord.class, new ConcreteAndroidDbHelper(c, db));
//Iterate through all forms currently saved
for (FormRecord record : storage) {
//Update forms marked as incomplete with the appropriate status
if (FormRecord.STATUS_INCOMPLETE.equals(record.getStatus())) {
//update to complete to process/send.
storage.write(record.updateInstanceAndStatus(record.getInstanceURI().toString(), FormRecord.STATUS_COMPLETE));
}
}
}
}
/**
* Reads and rewrites all of the records in a table, generally to adapt an old serialization format to a new
* format
*/
private <T extends Persistable> void updateModels(SqlStorage<T> storage) {
for (T t : storage) {
storage.write(t);
}
}
}
|
only set a form number on an upgraded form record if its status is COMPLETE or UNSENT
|
app/src/org/commcare/models/database/user/UserDatabaseUpgrader.java
|
only set a form number on an upgraded form record if its status is COMPLETE or UNSENT
|
|
Java
|
apache-2.0
|
c5d36de8db1c55dc5f184dd5b675468d0984456e
| 0
|
threerings/playn,threerings/playn,ruslansennov/playn,ruslansennov/playn,threerings/playn,ruslansennov/playn,threerings/playn
|
/**
* Copyright 2012 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.tests.core;
import pythagoras.f.FloatMath;
import playn.core.CanvasImage;
import playn.core.Image;
import playn.core.ImageLayer;
import playn.core.ImmediateLayer;
import playn.core.Surface;
import playn.core.gl.IndexedTrisShader;
import playn.core.util.Callback;
import static playn.core.PlayN.*;
/**
* Tests custom shader support.
*/
public class ShaderTest extends Test {
private float elapsed;
@Override
public String getName() {
return "ShaderTest";
}
@Override
public String getDescription() {
return "Tests custom shader support.";
}
@Override
public void init() {
// TODO: display some text saying shaders aren't supported
if (graphics().ctx() == null) return;
Image orange = assets().getImage("images/orange.png");
orange.addCallback(new Callback<Image>() {
public void onSuccess(Image orange) {
init(orange);
}
public void onFailure(Throwable err) {
log().warn("Failed to load orange image", err);
}
});
}
protected void init (final Image orange) {
// add the normal orange
float dx = orange.width() + 25;
graphics().rootLayer().addAt(graphics().createImageLayer(orange), 25, 25);
// add a sepia toned orange
ImageLayer olayer = graphics().createImageLayer(orange);
olayer.setShader(createSepiaShader());
graphics().rootLayer().addAt(olayer, 25+dx, 25);
// create a shader that rotates things around the (3D) y axis
IndexedTrisShader rotShader = new IndexedTrisShader(graphics().ctx()) {
@Override protected String vertexShader() {
return VERT_UNIFS +
"uniform float u_Angle;\n" +
"uniform vec2 u_Eye;\n" +
VERT_ATTRS +
PER_VERT_ATTRS +
VERT_VARS +
"void main(void) {\n" +
// Rotate the vertex per our 3D rotation
" float cosa = cos(u_Angle);\n" +
" float sina = sin(u_Angle);\n" +
" mat4 rotmat = mat4(\n" +
" cosa, 0, sina, 0,\n" +
" 0, 1, 0, 0,\n" +
" -sina, 0, cosa, 0,\n" +
" 0, 0, 0, 1);\n" +
" vec4 pos = rotmat * vec4(a_Position - u_Eye, 0, 1);\n" +
// Perspective project the vertex back into the plane
" mat4 persp = mat4(\n" +
" 1, 0, 0, 0,\n" +
" 0, 1, 0, 0,\n" +
" 0, 0, 1, -1.0/200.0,\n" +
" 0, 0, 0, 1);\n" +
" pos = persp * pos;\n" +
" pos /= pos.w;\n" +
" pos += vec4(u_Eye, 0, 0);\n;" +
// Transform the vertex per the normal screen transform
" mat4 transform = mat4(\n" +
" a_Matrix[0], a_Matrix[1], 0, 0,\n" +
" a_Matrix[2], a_Matrix[3], 0, 0,\n" +
" 0, 0, 1, 0,\n" +
" a_Translation[0], a_Translation[1], 0, 1);\n" +
" pos = transform * pos;\n" +
" pos.x /= (u_ScreenSize.x / 2.0);\n" +
" pos.y /= (u_ScreenSize.y / 2.0);\n" +
" pos.z /= (u_ScreenSize.y / 2.0);\n" +
" pos.x -= 1.0;\n" +
" pos.y = 1.0 - pos.y;\n" +
" gl_Position = pos;\n" +
VERT_SETTEX +
VERT_SETCOLOR +
"}";
}
@Override
protected Core createTextureCore() {
return new RotCore(vertexShader(), textureFragmentShader());
}
@Override
protected Core createColorCore() {
return new RotCore(vertexShader(), colorFragmentShader());
}
class RotCore extends ITCore {
private final Uniform1f uAngle = prog.getUniform1f("u_Angle");
private final Uniform2f uEye = prog.getUniform2f("u_Eye");
public RotCore (String vertShader, String fragShader) {
super(vertShader, fragShader);
}
@Override
public void activate(int fbufWidth, int fbufHeight) {
super.activate(fbufWidth, fbufHeight);
uAngle.bind(elapsed * FloatMath.PI);
uEye.bind(0, orange.height()/2);
}
}
};
// add an image that is rotated around the (3D) y axis
CanvasImage image = graphics().createImage(orange.width(), orange.height());
image.canvas().setFillColor(0xFF99CCFF);
image.canvas().fillRect(0, 0, image.width(), image.height());
image.canvas().drawImage(orange, 0, 0);
ImageLayer rotlayer = graphics().createImageLayer(image);
rotlayer.setShader(rotShader);
graphics().rootLayer().addAt(rotlayer, 25 + 2*dx + orange.width(), 25);
// add an immediate layer that draws a quad and an image (which should rotate)
ImmediateLayer irotlayer = graphics().createImmediateLayer(new ImmediateLayer.Renderer() {
public void render (Surface surf) {
surf.setFillColor(0xFFCC99FF);
surf.fillRect(0, 0, orange.width(), orange.height());
surf.drawImage(orange, 0, 0);
}
});
irotlayer.setShader(rotShader);
graphics().rootLayer().addAt(irotlayer, 25 + 3*dx + orange.width(), 25);
}
@Override
public void update(int delta) {
elapsed += delta/1000f;
}
}
|
tests/core/src/main/java/playn/tests/core/ShaderTest.java
|
/**
* Copyright 2012 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.tests.core;
import pythagoras.f.FloatMath;
import playn.core.CanvasImage;
import playn.core.Image;
import playn.core.ImageLayer;
import playn.core.ImmediateLayer;
import playn.core.Surface;
import playn.core.gl.IndexedTrisShader;
import playn.core.util.Callback;
import static playn.core.PlayN.*;
/**
* Tests custom shader support.
*/
public class ShaderTest extends Test {
private float elapsed;
@Override
public String getName() {
return "ShaderTest";
}
@Override
public String getDescription() {
return "Tests custom shader support.";
}
@Override
public void init() {
// TODO: display some text saying shaders aren't supported
if (graphics().ctx() == null) return;
Image orange = assets().getImage("images/orange.png");
orange.addCallback(new Callback<Image>() {
public void onSuccess(Image orange) {
init(orange);
}
public void onFailure(Throwable err) {
log().warn("Failed to load orange image", err);
}
});
}
protected void init (final Image orange) {
// add the normal orange
float dx = orange.width() + 25;
graphics().rootLayer().addAt(graphics().createImageLayer(orange), 25, 25);
// add a sepia toned orange
ImageLayer olayer = graphics().createImageLayer(orange);
olayer.setShader(createSepiaShader());
graphics().rootLayer().addAt(olayer, 25+dx, 25);
// create a shader that rotates things around the (3D) y axis
IndexedTrisShader rotShader = new IndexedTrisShader(graphics().ctx()) {
@Override protected String vertexShader() {
return VERT_UNIFS +
"uniform float u_Angle;\n" +
"uniform vec2 u_Eye;\n" +
VERT_ATTRS +
PER_VERT_ATTRS +
VERT_VARS +
"void main(void) {\n" +
// Rotate the vertex per our 3D rotation
" float cosa = cos(u_Angle);\n" +
" float sina = sin(u_Angle);\n" +
" mat4 rotmat = mat4(\n" +
" cosa, 0, sina, 0,\n" +
" 0, 1, 0, 0,\n" +
" -sina, 0, cosa, 0,\n" +
" 0, 0, 0, 1);\n" +
" vec4 pos = rotmat * vec4(a_Position - u_Eye, 0, 1);\n" +
// Perspective project the vertex back into the plane
" mat4 persp = mat4(\n" +
" 1, 0, 0, 0,\n" +
" 0, 1, 0, 0,\n" +
" 0, 0, 1, -1.0/200.0,\n" +
" 0, 0, 0, 1);\n" +
" pos = persp * pos;\n" +
" pos /= pos.w;\n" +
" pos += vec4(u_Eye, 0, 0);\n;" +
// Transform the vertex per the normal screen transform
" mat4 transform = mat4(\n" +
" a_Matrix[0], a_Matrix[1], 0, 0,\n" +
" a_Matrix[2], a_Matrix[3], 0, 0,\n" +
" 0, 0, 1, 0,\n" +
" a_Translation[0], a_Translation[1], 0, 1);\n" +
" pos = transform * pos;\n" +
" pos.x /= (u_ScreenSize.x / 2.0);\n" +
" pos.y /= (u_ScreenSize.y / 2.0);\n" +
" pos.z /= (u_ScreenSize.y / 2.0);\n" +
" pos.x -= 1.0;\n" +
" pos.y = 1.0 - pos.y;\n" +
" gl_Position = pos;\n" +
VERT_SETTEX +
VERT_SETCOLOR +
"}";
}
@Override
protected Core createTextureCore() {
return new RotCore(vertexShader(), textureFragmentShader());
}
@Override
protected Core createColorCore() {
return new RotCore(vertexShader(), colorFragmentShader());
}
class RotCore extends ITCore {
private final Uniform1f uAngle = prog.getUniform1f("u_Angle");
private final Uniform2f uEye = prog.getUniform2f("u_Eye");
public RotCore (String vertShader, String fragShader) {
super(vertShader, fragShader);
}
@Override
public void activate(int fbufWidth, int fbufHeight) {
super.activate(fbufWidth, fbufHeight);
uAngle.bind(elapsed * FloatMath.PI);
uEye.bind(0, orange.height()/2);
}
};
};
// add an image that is rotated around the (3D) y axis
CanvasImage image = graphics().createImage(orange.width(), orange.height());
image.canvas().setFillColor(0xFF99CCFF);
image.canvas().fillRect(0, 0, image.width(), image.height());
image.canvas().drawImage(orange, 0, 0);
ImageLayer rotlayer = graphics().createImageLayer(image);
rotlayer.setShader(rotShader);
graphics().rootLayer().addAt(rotlayer, 25 + 2*dx + orange.width(), 25);
// add an immediate layer that draws a quad and an image (which should rotate)
ImmediateLayer irotlayer = graphics().createImmediateLayer(new ImmediateLayer.Renderer() {
public void render (Surface surf) {
surf.setFillColor(0xFFCC99FF);
surf.fillRect(0, 0, orange.width(), orange.height());
surf.drawImage(orange, 0, 0);
}
});
irotlayer.setShader(rotShader);
graphics().rootLayer().addAt(irotlayer, 25 + 3*dx + orange.width(), 25);
}
@Override
public void update(int delta) {
elapsed += delta/1000f;
}
}
|
Spurious semicolon
|
tests/core/src/main/java/playn/tests/core/ShaderTest.java
|
Spurious semicolon
|
|
Java
|
apache-2.0
|
e1cbda980af376fc2742512671a57629ca8f3b32
| 0
|
aldaris/wicket,selckin/wicket,AlienQueen/wicket,AlienQueen/wicket,topicusonderwijs/wicket,topicusonderwijs/wicket,apache/wicket,dashorst/wicket,Servoy/wicket,astrapi69/wicket,dashorst/wicket,Servoy/wicket,aldaris/wicket,apache/wicket,klopfdreh/wicket,astrapi69/wicket,dashorst/wicket,klopfdreh/wicket,freiheit-com/wicket,Servoy/wicket,bitstorm/wicket,mosoft521/wicket,bitstorm/wicket,dashorst/wicket,klopfdreh/wicket,freiheit-com/wicket,martin-g/wicket-osgi,apache/wicket,selckin/wicket,mosoft521/wicket,bitstorm/wicket,bitstorm/wicket,astrapi69/wicket,apache/wicket,martin-g/wicket-osgi,mafulafunk/wicket,aldaris/wicket,AlienQueen/wicket,klopfdreh/wicket,aldaris/wicket,Servoy/wicket,topicusonderwijs/wicket,zwsong/wicket,mosoft521/wicket,astrapi69/wicket,AlienQueen/wicket,mafulafunk/wicket,selckin/wicket,zwsong/wicket,klopfdreh/wicket,AlienQueen/wicket,freiheit-com/wicket,apache/wicket,zwsong/wicket,zwsong/wicket,topicusonderwijs/wicket,dashorst/wicket,freiheit-com/wicket,selckin/wicket,freiheit-com/wicket,aldaris/wicket,Servoy/wicket,selckin/wicket,mosoft521/wicket,bitstorm/wicket,topicusonderwijs/wicket,mosoft521/wicket,mafulafunk/wicket,martin-g/wicket-osgi
|
/*
* 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 wicket;
import wicket.request.compound.IExceptionResponseStrategy;
/**
* Immediately aborts any further processing. This exception will not be handled
* by {@link IExceptionResponseStrategy}.
*
* @author Igor Vaynberg (ivaynberg)
*/
public class AbortException extends RuntimeException
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @see java.lang.Throwable#fillInStackTrace()
*/
public synchronized Throwable fillInStackTrace()
{
// we do not need a stack trace, so to speed things up just return null
return null;
}
}
|
wicket/src/main/java/wicket/AbortException.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 wicket;
import wicket.request.compound.IExceptionResponseStrategy;
/**
* Immediately aborts any further processing. This exception will not be handled
* by {@link IExceptionResponseStrategy}.
*
* @author Igor Vaynberg (ivaynberg)
*/
public class AbortException extends RuntimeException
{
/**
*
*/
private static final long serialVersionUID = 1L;
}
|
WICKET-188
git-svn-id: 6d6ade8e88b1292e17cba3559b7335a947e495e0@491042 13f79535-47bb-0310-9956-ffa450edef68
|
wicket/src/main/java/wicket/AbortException.java
|
WICKET-188
|
|
Java
|
agpl-3.0
|
7f97979a973d9d622598dc142a1210944d22556a
| 0
|
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
9a0f3d26-2e60-11e5-9284-b827eb9e62be
|
hello.java
|
9a09a974-2e60-11e5-9284-b827eb9e62be
|
9a0f3d26-2e60-11e5-9284-b827eb9e62be
|
hello.java
|
9a0f3d26-2e60-11e5-9284-b827eb9e62be
|
|
Java
|
agpl-3.0
|
15b1adcfcbe7eb3f7fc72f1b7cd18901e0514067
| 0
|
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
3f2694fc-2e62-11e5-9284-b827eb9e62be
|
hello.java
|
3f2123f0-2e62-11e5-9284-b827eb9e62be
|
3f2694fc-2e62-11e5-9284-b827eb9e62be
|
hello.java
|
3f2694fc-2e62-11e5-9284-b827eb9e62be
|
|
Java
|
agpl-3.0
|
89bcaf2663f7425db3864e5e2e53f3b15a9386ec
| 0
|
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
26b72332-2e62-11e5-9284-b827eb9e62be
|
hello.java
|
26b1aa56-2e62-11e5-9284-b827eb9e62be
|
26b72332-2e62-11e5-9284-b827eb9e62be
|
hello.java
|
26b72332-2e62-11e5-9284-b827eb9e62be
|
|
Java
|
mit
|
8dba8d2a2dbec27d8b68e591579d542c7bbfdb1f
| 0
|
mcyuan00/ABC-music-player
|
package abc.player;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JDialog;
import org.antlr.v4.gui.Trees;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.misc.Utils;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.tree.TerminalNode;
import abc.parser.HeaderLexer;
import abc.parser.HeaderListener;
import abc.parser.HeaderParser;
import abc.parser.HeaderParser.CommentContext;
import abc.parser.HeaderParser.ComposerContext;
import abc.parser.HeaderParser.EndlineContext;
import abc.parser.HeaderParser.HeaderContext;
import abc.parser.HeaderParser.IndexContext;
import abc.parser.HeaderParser.KeyContext;
import abc.parser.HeaderParser.LengthContext;
import abc.parser.HeaderParser.MeterContext;
import abc.parser.HeaderParser.OtherfieldsContext;
import abc.parser.HeaderParser.RootContext;
import abc.parser.HeaderParser.TempoContext;
import abc.parser.HeaderParser.TextContext;
import abc.parser.HeaderParser.TitleContext;
import abc.parser.HeaderParser.VoiceContext;
import abc.parser.MusicLexer;
import abc.parser.MusicListener;
import abc.parser.MusicParser;
import abc.parser.MusicParser.ChordContext;
import abc.parser.MusicParser.DoublebarmeasureContext;
import abc.parser.MusicParser.ElementContext;
import abc.parser.MusicParser.EndrepeatmeasureContext;
import abc.parser.MusicParser.FirstendingmeasureContext;
import abc.parser.MusicParser.MeasureContext;
import abc.parser.MusicParser.MusicContext;
import abc.parser.MusicParser.NormalmeasureContext;
import abc.parser.MusicParser.NoteContext;
import abc.parser.MusicParser.NoteelementContext;
import abc.parser.MusicParser.NotelengthContext;
import abc.parser.MusicParser.PitchContext;
import abc.parser.MusicParser.RestContext;
import abc.parser.MusicParser.SecondendingmeasureContext;
import abc.parser.MusicParser.SinglerepeatmeasureContext;
import abc.parser.MusicParser.StartrepeatmeasureContext;
import abc.parser.MusicParser.TupletelementContext;
import abc.parser.MusicParser.TupletspecContext;
public class Parser {
public static Header parseHeader(String input){
// try{
// Create a stream of characters from the string
CharStream stream = new ANTLRInputStream(input);
HeaderLexer lexer = new HeaderLexer(stream);
TokenStream tokens = new CommonTokenStream(lexer);
HeaderParser parser = new HeaderParser(tokens);
lexer.reportErrorsAsExceptions();
parser.reportErrorsAsExceptions();
// Generate the parse tree using the starter rule.
// root is the starter rule for this grammar.
// Other grammars may have different names for the starter rule.
ParseTree tree = parser.root();
// Future<JDialog> inspect = Trees.inspect(tree, parser);
// try {
// Utils.waitForClose(inspect.get());
// } catch (Exception e) {
// e.printStackTrace();
// }
MakeHeader headerMaker = new MakeHeader();
new ParseTreeWalker().walk(headerMaker, tree);
return headerMaker.getHeader();
// }
// catch(Exception e){
// System.out.println(e.getMessage()); //not used after debugging
// throw new IllegalArgumentException();
// }
}
static class MakeHeader implements HeaderListener {
private final Stack<String> requiredStack = new Stack<>();
private final Stack<String> optionalStack = new Stack<>();
/**
* @return the Header that was parsed
* @Throws IllegalArgumentException of index, title, or keySignature is missing
*/
public Header getHeader(){
int index = -1;
String title = "";
KeySignature keySignature= KeySignature.valueOf("NEGATIVE");
// parse/check existence of required fields index, header, keySignature
while (!requiredStack.isEmpty()){
String context = requiredStack.pop();
// System.out.println(context);
// if (context.contains("missing")){
// throw new IllegalArgumentException();
// }
//parse out index, header, and keySignature
if (context.contains("X:")){
Pattern pattern = Pattern.compile("[0-9-]+");
Matcher matcher = pattern.matcher(context);
if (matcher.find()){
index = Integer.valueOf( matcher.group());
}
}
else if (context.contains("T:")){
title = context.replace("T:", "").replace("\n", "");
}
else if (context.contains("K:")){
String key = "";
context = context.replace("K:", "");
Pattern pattern = Pattern.compile("[A-G]");
Matcher matcher = pattern.matcher(context);
if (matcher.find()){
key += matcher.group();
}
if (context.contains("b")){
key+="_FLAT";
}
else if (context.contains("#")){
key+="_SHARP";
}
if(context.contains("m")){
key+="_MINOR";
}
else{
key+="_MAJOR";
}
keySignature = KeySignature.valueOf(key);
}
}
//missing one of index, header or keySig
// if(index < 0 || title.equals("") || keySignature.equals(KeySignature.valueOf("NEGATIVE"))){
// throw new IllegalArgumentException();
// }
Header header = new Header(index, title, keySignature);
//parse other fields
while (!optionalStack.isEmpty()){
String context = optionalStack.pop();
// System.out.println(context);
// if (context.contains("missing")|| !(context.contains(":"))){
// throw new IllegalArgumentException();
// }
if (context.contains("C:")){
String composer = context.replace("C:", "").replace("\n", "");
header.setComposer(composer);
}
if (context.contains("M:")){
// System.out.println(context);
if(context.contains("C|")){
header.setMeter(new Fraction(2,2));
}
else if(context.contains("C")){
header.setMeter(new Fraction(4, 4));
}
else{
context = context.replace("M:", "").replace("\n", "");
Fraction meter = parseFraction(context);
header.setMeter(meter);
}
}
if (context.contains("L:")){
context = context.replace("L:", "").replace("\n", "");
Fraction noteLength = parseFraction(context);
header.setNoteLength(noteLength);;
}
if (context.contains("Q:")){
Pattern pattern = Pattern.compile("=[0-9]+");
Matcher matcher = pattern.matcher(context);
int tempo = -1;
if (matcher.find()){
String group = matcher.group();
tempo = Integer.valueOf(group.replace("=", ""));
context = context.replace(group, "").replace("\n", "").replace("Q:", "");
}
else{
throw new IllegalArgumentException();
}
Fraction given = parseFraction(context);
Fraction headerLength = header.noteLength();
double tempoOffset = given.numerator()*headerLength.denominator()/(given.denominator()*headerLength.numerator());
header.setTempo((int)(tempo/tempoOffset));
}
if (context.contains("V:")){
String voice = context.replace("V:", "").replace("\n", "");
header.addVoice(voice);
}
}
return header;
}
/**
* @param context the context containing the fraction to parse out
* @return the Fraction that the context represented
*/
private Fraction parseFraction(String context){
String[] nums = context.split("/");
int numerator = Integer.valueOf(nums[0]);
int denominator = Integer.valueOf(nums[1]);
return new Fraction(numerator, denominator);
}
@Override
public void exitRoot(HeaderParser.RootContext ctx) { }
@Override
public void exitHeader(HeaderParser.HeaderContext ctx) { }
@Override
public void exitIndex(HeaderParser.IndexContext ctx) {
requiredStack.push(ctx.getText());
}
@Override
public void exitTitle(HeaderParser.TitleContext ctx) {
requiredStack.push(ctx.getText());
}
@Override
public void exitOtherfields(HeaderParser.OtherfieldsContext ctx) { }
@Override
public void exitComposer(HeaderParser.ComposerContext ctx) {
optionalStack.push(ctx.getText());
}
@Override
public void exitMeter(HeaderParser.MeterContext ctx) {
System.out.println(ctx.getText());
optionalStack.push(ctx.getText());
}
@Override
public void exitLength(HeaderParser.LengthContext ctx) {
optionalStack.push(ctx.getText());
}
@Override
public void exitTempo(HeaderParser.TempoContext ctx) {
optionalStack.push(ctx.getText());
}
@Override
public void exitVoice(HeaderParser.VoiceContext ctx) {
optionalStack.push(ctx.getText());
}
@Override
public void exitKey(HeaderParser.KeyContext ctx) {
requiredStack.push(ctx.getText());
}
@Override
public void exitComment(HeaderParser.CommentContext ctx) { }
@Override
public void exitText(HeaderParser.TextContext ctx) { }
// ~~~~~~~~~~~~~~~~~~~
@Override
public void enterEveryRule(ParserRuleContext arg0) { }
@Override
public void exitEveryRule(ParserRuleContext arg0) { }
@Override
public void visitErrorNode(ErrorNode arg0) { }
@Override
public void visitTerminal(TerminalNode arg0) { }
@Override
public void enterRoot(RootContext ctx) { }
@Override
public void enterHeader(HeaderContext ctx) { }
@Override
public void enterIndex(IndexContext ctx) { }
@Override
public void enterTitle(TitleContext ctx) { }
@Override
public void enterOtherfields(OtherfieldsContext ctx) { }
@Override
public void enterComposer(ComposerContext ctx) { }
@Override
public void enterMeter(MeterContext ctx) { }
@Override
public void enterLength(LengthContext ctx) { }
@Override
public void enterTempo(TempoContext ctx) { }
@Override
public void enterVoice(VoiceContext ctx) { }
@Override
public void enterKey(KeyContext ctx) { }
@Override
public void enterComment(CommentContext ctx) { }
@Override
public void enterText(TextContext ctx) { }
@Override
public void enterEndline(EndlineContext ctx) { }
@Override
public void exitEndline(EndlineContext ctx) { }
}
public static Music parseMusic(String input, Fraction defaultNoteLength, KeySignature keySig, String voice){
// try{
// Create a stream of characters from the string
CharStream stream = new ANTLRInputStream(input);
MusicLexer lexer = new MusicLexer(stream);
TokenStream tokens = new CommonTokenStream(lexer);
MusicParser parser = new MusicParser(tokens);
lexer.reportErrorsAsExceptions();
parser.reportErrorsAsExceptions();
// Generate the parse tree using the starter rule.
// root is the starter rule for this grammar.
// Other grammars may have different names for the starter rule.
ParseTree tree = parser.root();
Future<JDialog> inspect = Trees.inspect(tree, parser);
try {
Utils.waitForClose(inspect.get());
} catch (Exception e) {
e.printStackTrace();
}
MakeMusic musicMaker = new MakeMusic(keySig, defaultNoteLength, voice);
new ParseTreeWalker().walk(musicMaker, tree);
return musicMaker.getMusic();
// }
// catch(RuntimeException e){
// System.out.println(e.getMessage()); //not used after debugging
// throw new IllegalArgumentException();
// }
}
static class MakeMusic implements MusicListener{
private final Map<NoteLetter, Accidental> keySig;
private final String voiceName;
private final Fraction defaultNoteLength;
private final Map<Accidental, Integer> accidental = new HashMap<Accidental, Integer>();
private final Stack<Music> stack = new Stack<>();
// public MakeMusic(){
// KeySignatureMap map = new KeySignatureMap();
// this.keySig = KeySignatureMap.KEY_SIGNATURE_MAP.get(KeySignature.valueOf("C_MAJOR"));
// accidental.put(Accidental.valueOf("DOUBLESHARP"), 2);
// accidental.put(Accidental.valueOf("SHARP"), 1);
// accidental.put(Accidental.valueOf("NATURAL"), 0);
// accidental.put(Accidental.valueOf("FLAT"), -1);
// accidental.put(Accidental.valueOf("DOUBLEFLAT"), -2);
//
// }
public MakeMusic(KeySignature keysig, Fraction defaultNoteLength, String voiceName){
KeySignatureMap map = new KeySignatureMap();
this.defaultNoteLength = defaultNoteLength;
this.voiceName = voiceName;
this.keySig = map.KEY_SIGNATURE_MAP.get(keysig);
accidental.put(Accidental.valueOf("DOUBLESHARP"), 2);
accidental.put(Accidental.valueOf("SHARP"), 1);
accidental.put(Accidental.valueOf("NATURAL"), 0);
accidental.put(Accidental.valueOf("FLAT"), -1);
accidental.put(Accidental.valueOf("DOUBLEFLAT"), -2);
}
/**
* @return the music object that was parsed
*/
public Music getMusic(){
return stack.get(0);
}
@Override
public void exitRoot(MusicParser.RootContext ctx) { }
@Override
public void exitMusic(MusicContext ctx) {
List<Music> voiceMeasures = new ArrayList<Music>();
while(!stack.isEmpty()){
voiceMeasures.add(stack.pop());
}
Collections.reverse(voiceMeasures);
Voice voice = new Voice(voiceName, voiceMeasures);
stack.push(voice);
}
@Override
public void exitMeasure(MeasureContext ctx) {
if (ctx.endrepeatmeasure()!= null){
List<Music> repeatBody= new ArrayList<Music>();
List<Music> firstRepeat = new ArrayList<Music>();
List<Music> repeat = new ArrayList<Music>();
while(!stack.isEmpty()){
Music music = stack.pop();
Measure m = (Measure)music;
if (m.isFirstEnding()){
repeat.add(music);
firstRepeat.addAll(repeat);
Collections.reverse(firstRepeat);
repeat = new ArrayList<Music>();
}
else if(m.isStartRepeat()){
repeat.add(music);
repeatBody.addAll(repeat);
Collections.reverse(repeatBody);
repeat = new ArrayList<Music>();
break;
}
else if(m.isDoubleBar()){
repeatBody.addAll(repeat);
stack.push(m);
Collections.reverse(repeatBody);
repeat = new ArrayList<Music>();
break;
}
}
repeat.addAll(repeatBody);
repeat.addAll(firstRepeat);
repeat.addAll(repeatBody);
for (Music m: repeat){
stack.push(m);
}
}
}
@Override
public void exitFirstendingmeasure(FirstendingmeasureContext ctx) {
int numNorm = ctx.normalmeasure().size();
List<Music> measures = new ArrayList<Music>();
for (int i = 0; i < numNorm; i++){
measures.add(stack.pop());
}
Measure startFirstEnding = (Measure) stack.pop();
Measure replacedStartFirst = new Measure(startFirstEnding, true, false, false, false);
measures.add(replacedStartFirst);
Collections.reverse(measures);
for (int i = 0; i < numNorm + 1; i++){
stack.push(measures.get(i));
}
}
@Override
public void exitSecondendingmeasure(SecondendingmeasureContext ctx) { }
@Override
public void exitDoublebarmeasure(DoublebarmeasureContext ctx) {
int numElements = ctx.element().size();
List<Music> elements = new ArrayList<Music>();
for (int i = 0; i < numElements; i++){
elements.add(stack.pop());
}
Collections.reverse(elements);
List<Music> newElements = applyAccidentalsToMeasure(elements);
Measure m = new Measure(newElements, false, false, false, true);
stack.push(m);
}
@Override
public void exitStartrepeatmeasure(StartrepeatmeasureContext ctx) {
int numElements = ctx.element().size();
List<Music> elements = new ArrayList<Music>();
for (int i = 0; i < numElements; i++){
elements.add(stack.pop());
}
Collections.reverse(elements);
List<Music> newElements = applyAccidentalsToMeasure(elements);
Measure m = new Measure(newElements, true, false, false, false);
stack.push(m);
}
@Override
public void exitEndrepeatmeasure(EndrepeatmeasureContext ctx) {
int numElements = ctx.element().size();
List<Music> elements = new ArrayList<Music>();
for (int i = 0; i < numElements; i++){
elements.add(stack.pop());
}
Collections.reverse(elements);
List<Music> newElements = applyAccidentalsToMeasure(elements);
Measure m = new Measure(newElements, false, true, false, false);
stack.push(m);
}
//TODO
@Override
public void exitSinglerepeatmeasure(SinglerepeatmeasureContext ctx) { }
@Override
public void exitNormalmeasure(NormalmeasureContext ctx) {
int numElements = ctx.element().size();
assert stack.size()>= numElements;
List<Music> elements = new ArrayList<Music>();
for (int i = 0; i < numElements; i++){
elements.add(stack.pop());
}
Collections.reverse(elements);
List<Music> newElements = applyAccidentalsToMeasure(elements);
Measure m = new Measure(newElements, false, false, false, false);
stack.push(m);
}
/**
* Checks from beginning to end if list of music elements has accidentals and applies these
* to the rest of the list if found
* @param elements list of music elements to apply accidentals to
* @return modified list of elements
*/
private List<Music> applyAccidentalsToMeasure(List<Music> elements){
Map<String, Integer> accidentalsMap = new HashMap<>();
List<Music> newElements = new ArrayList<>();
for (Music m : elements){
Music newMusic = m.applyAccidentals(accidentalsMap);
newElements.add(newMusic);
}
return newElements;
}
@Override
public void exitElement(ElementContext ctx) { }
@Override
public void exitNoteelement(NoteelementContext ctx) { }
@Override
public void exitNote(NoteContext ctx) { }
@Override
public void exitPitch(PitchContext ctx) {
System.out.println(ctx.NOTELETTER().getText());
Fraction noteLength = defaultNoteLength;
int octave = 0;
char noteLetter = 'y';
int numAccidental = 0;
boolean transpose = false;
if (ctx.NOTELETTER()!= null){
char note = ctx.NOTELETTER().getText().charAt(0);
if (Character.isLowerCase(note)){
octave +=1;
}
noteLetter = Character.toUpperCase(note);
Accidental acc = keySig.get(NoteLetter.valueOf(Character.toString(noteLetter)));
numAccidental += accidental.get(acc);
}
if (ctx.OCTAVE()!= null){
String octaves = ctx.OCTAVE().getText();
if (octaves.contains(",")){
octave -= octaves.length();
}
else if(octaves.contains("'")){
octave += octaves.length();
}
}
if (ctx.notelength()!= null){
String length = ctx.notelength().getText();
noteLength = parseNoteLength(length);
}
if (ctx.ACCIDENTAL()!= null){
String accidental = ctx.ACCIDENTAL().getText();
if (accidental.contains("_")){
numAccidental = -1 * accidental.length();
}
else if (accidental.contains("^")){
numAccidental = accidental.length();
}
else{
numAccidental = 0;
}
transpose = true;
}
Note n = new Note(noteLength, noteLetter, octave, numAccidental, transpose);
stack.push(n);
}
@Override
public void exitRest(RestContext ctx) {
Fraction noteLength = defaultNoteLength;
if (ctx.notelength()!= null){
String length = ctx.notelength().getText();
noteLength = parseNoteLength(length);
}
Rest r = new Rest(noteLength);
stack.push(r);
}
@Override
public void exitNotelength(NotelengthContext ctx) { }
@Override
public void exitTupletelement(TupletelementContext ctx) {
int tupletNum = Integer.valueOf(ctx.tupletspec().getText().replace("(", ""));
int tupletSize = ctx.noteelement().size();
assert tupletSize >= tupletNum;
assert tupletNum > 1 && tupletNum < 5;
List<Music> tupletNotes = new ArrayList<Music>();
for (int i = 0; i < tupletSize; i++){
tupletNotes.add(stack.pop());
}
Collections.reverse(tupletNotes);
Tuplet t = new Tuplet(tupletNum, tupletNotes);
stack.push(t);
}
@Override
public void exitTupletspec(TupletspecContext ctx) { }
@Override
public void exitChord(ChordContext ctx) {
List<NoteContext> notes = ctx.note();
assert stack.size() >= notes.size();
assert notes.size()>= 1;
List<Music> chordNotes = new ArrayList<Music>();
for (int i = 0; i < notes.size(); i++){
chordNotes.add(stack.pop());
}
Collections.reverse(chordNotes);
Music m = new Chord(chordNotes);
stack.push(m);
}
/**
* Given a string representing a note or rest's length, returns a Fraction object representing the
* given length
* @param length string representation of note/rest's length
* @return Fraction object representing the note/rest's length
*/
private Fraction parseNoteLength(String length){
int numerator;
int denominator;
if(!length.contains("/")){
numerator = Integer.valueOf(length);
denominator = 1;
}
else{
String[] nums = length.split("/");
if (nums.length == 0){
numerator = 1;
denominator = 2;
}
else if (nums.length == 1){
numerator = Integer.valueOf(nums[0]);
denominator = 2;
}
else{
numerator = (nums[0].equals("")) ? 1 : Integer.valueOf(nums[0]);
denominator = Integer.valueOf(nums[1]);
}
}
return new Fraction(numerator * defaultNoteLength.numerator(), denominator * defaultNoteLength.denominator()).simplify();
}
@Override
public void exitComment(MusicParser.CommentContext ctx) { }
@Override
public void exitText(MusicParser.TextContext ctx) { }
//~~~~~~~~~~~~~~
@Override
public void enterEveryRule(ParserRuleContext arg0) { }
@Override
public void exitEveryRule(ParserRuleContext arg0) { }
@Override
public void visitErrorNode(ErrorNode arg0) { }
@Override
public void visitTerminal(TerminalNode arg0) { }
@Override
public void enterRoot(abc.parser.MusicParser.RootContext ctx) {}
@Override
public void enterMusic(MusicContext ctx) {}
@Override
public void enterNote(NoteContext ctx) { }
@Override
public void enterRest(RestContext ctx) {}
@Override
public void enterNotelength(NotelengthContext ctx) {}
@Override
public void enterTupletspec(TupletspecContext ctx) {}
@Override
public void enterComment(abc.parser.MusicParser.CommentContext ctx) { }
@Override
public void enterText(abc.parser.MusicParser.TextContext ctx) { }
@Override
public void enterChord(ChordContext ctx) { }
@Override
public void enterNoteelement(NoteelementContext ctx) { }
@Override
public void enterMeasure(MeasureContext ctx) { }
@Override
public void enterTupletelement(TupletelementContext ctx) { }
@Override
public void enterFirstendingmeasure(FirstendingmeasureContext ctx) { }
@Override
public void enterSecondendingmeasure(SecondendingmeasureContext ctx) { }
@Override
public void enterDoublebarmeasure(DoublebarmeasureContext ctx) { }
@Override
public void enterStartrepeatmeasure(StartrepeatmeasureContext ctx) { }
@Override
public void enterEndrepeatmeasure(EndrepeatmeasureContext ctx) { }
@Override
public void enterNormalmeasure(NormalmeasureContext ctx) { }
@Override
public void enterElement(ElementContext ctx) { }
@Override
public void enterPitch(PitchContext ctx) { }
@Override
public void enterSinglerepeatmeasure(SinglerepeatmeasureContext ctx) { }
}
}
|
src/abc/player/Parser.java
|
package abc.player;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JDialog;
import org.antlr.v4.gui.Trees;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.misc.Utils;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.tree.TerminalNode;
import abc.parser.HeaderLexer;
import abc.parser.HeaderListener;
import abc.parser.HeaderParser;
import abc.parser.HeaderParser.CommentContext;
import abc.parser.HeaderParser.ComposerContext;
import abc.parser.HeaderParser.EndlineContext;
import abc.parser.HeaderParser.HeaderContext;
import abc.parser.HeaderParser.IndexContext;
import abc.parser.HeaderParser.KeyContext;
import abc.parser.HeaderParser.LengthContext;
import abc.parser.HeaderParser.MeterContext;
import abc.parser.HeaderParser.OtherfieldsContext;
import abc.parser.HeaderParser.RootContext;
import abc.parser.HeaderParser.TempoContext;
import abc.parser.HeaderParser.TextContext;
import abc.parser.HeaderParser.TitleContext;
import abc.parser.HeaderParser.VoiceContext;
import abc.parser.MusicLexer;
import abc.parser.MusicListener;
import abc.parser.MusicParser;
import abc.parser.MusicParser.ChordContext;
import abc.parser.MusicParser.DoublebarmeasureContext;
import abc.parser.MusicParser.ElementContext;
import abc.parser.MusicParser.EndrepeatmeasureContext;
import abc.parser.MusicParser.FirstendingmeasureContext;
import abc.parser.MusicParser.MeasureContext;
import abc.parser.MusicParser.MusicContext;
import abc.parser.MusicParser.NormalmeasureContext;
import abc.parser.MusicParser.NoteContext;
import abc.parser.MusicParser.NoteelementContext;
import abc.parser.MusicParser.NotelengthContext;
import abc.parser.MusicParser.PitchContext;
import abc.parser.MusicParser.RestContext;
import abc.parser.MusicParser.SecondendingmeasureContext;
import abc.parser.MusicParser.SinglerepeatmeasureContext;
import abc.parser.MusicParser.StartrepeatmeasureContext;
import abc.parser.MusicParser.TupletelementContext;
import abc.parser.MusicParser.TupletspecContext;
public class Parser {
public static Header parseHeader(String input){
// try{
// Create a stream of characters from the string
CharStream stream = new ANTLRInputStream(input);
HeaderLexer lexer = new HeaderLexer(stream);
TokenStream tokens = new CommonTokenStream(lexer);
HeaderParser parser = new HeaderParser(tokens);
lexer.reportErrorsAsExceptions();
parser.reportErrorsAsExceptions();
// Generate the parse tree using the starter rule.
// root is the starter rule for this grammar.
// Other grammars may have different names for the starter rule.
ParseTree tree = parser.root();
// Future<JDialog> inspect = Trees.inspect(tree, parser);
// try {
// Utils.waitForClose(inspect.get());
// } catch (Exception e) {
// e.printStackTrace();
// }
MakeHeader headerMaker = new MakeHeader();
new ParseTreeWalker().walk(headerMaker, tree);
return headerMaker.getHeader();
// }
// catch(Exception e){
// System.out.println(e.getMessage()); //not used after debugging
// throw new IllegalArgumentException();
// }
}
static class MakeHeader implements HeaderListener {
private final Stack<String> requiredStack = new Stack<>();
private final Stack<String> optionalStack = new Stack<>();
/**
* @return the Header that was parsed
* @Throws IllegalArgumentException of index, title, or keySignature is missing
*/
public Header getHeader(){
int index = -1;
String title = "";
KeySignature keySignature= KeySignature.valueOf("NEGATIVE");
// parse/check existence of required fields index, header, keySignature
while (!requiredStack.isEmpty()){
String context = requiredStack.pop();
// System.out.println(context);
// if (context.contains("missing")){
// throw new IllegalArgumentException();
// }
//parse out index, header, and keySignature
if (context.contains("X:")){
Pattern pattern = Pattern.compile("[0-9-]+");
Matcher matcher = pattern.matcher(context);
if (matcher.find()){
index = Integer.valueOf( matcher.group());
}
}
else if (context.contains("T:")){
title = context.replace("T:", "").replace("\n", "");
}
else if (context.contains("K:")){
String key = "";
context = context.replace("K:", "");
Pattern pattern = Pattern.compile("[A-G]");
Matcher matcher = pattern.matcher(context);
if (matcher.find()){
key += matcher.group();
}
if (context.contains("b")){
key+="_FLAT";
}
else if (context.contains("#")){
key+="_SHARP";
}
if(context.contains("m")){
key+="_MINOR";
}
else{
key+="_MAJOR";
}
keySignature = KeySignature.valueOf(key);
}
}
//missing one of index, header or keySig
// if(index < 0 || title.equals("") || keySignature.equals(KeySignature.valueOf("NEGATIVE"))){
// throw new IllegalArgumentException();
// }
Header header = new Header(index, title, keySignature);
//parse other fields
while (!optionalStack.isEmpty()){
String context = optionalStack.pop();
// System.out.println(context);
// if (context.contains("missing")|| !(context.contains(":"))){
// throw new IllegalArgumentException();
// }
if (context.contains("C:")){
String composer = context.replace("C:", "").replace("\n", "");
header.setComposer(composer);
}
if (context.contains("M:")){
// System.out.println(context);
if(context.contains("C|")){
header.setMeter(new Fraction(2,2));
}
else if(context.contains("C")){
header.setMeter(new Fraction(4, 4));
}
else{
context = context.replace("M:", "").replace("\n", "");
Fraction meter = parseFraction(context);
header.setMeter(meter);
}
}
if (context.contains("L:")){
context = context.replace("L:", "").replace("\n", "");
Fraction noteLength = parseFraction(context);
header.setNoteLength(noteLength);;
}
if (context.contains("Q:")){
Pattern pattern = Pattern.compile("=[0-9]+");
Matcher matcher = pattern.matcher(context);
int tempo = -1;
if (matcher.find()){
String group = matcher.group();
tempo = Integer.valueOf(group.replace("=", ""));
context = context.replace(group, "").replace("\n", "").replace("Q:", "");
}
else{
throw new IllegalArgumentException();
}
Fraction given = parseFraction(context);
Fraction headerLength = header.noteLength();
double tempoOffset = given.numerator()*headerLength.denominator()/(given.denominator()*headerLength.numerator());
header.setTempo((int)(tempo/tempoOffset));
}
if (context.contains("V:")){
String voice = context.replace("V:", "").replace("\n", "");
header.addVoice(voice);
}
}
return header;
}
/**
* @param context the context containing the fraction to parse out
* @return the Fraction that the context represented
*/
private Fraction parseFraction(String context){
String[] nums = context.split("/");
int numerator = Integer.valueOf(nums[0]);
int denominator = Integer.valueOf(nums[1]);
return new Fraction(numerator, denominator);
}
@Override
public void exitRoot(HeaderParser.RootContext ctx) { }
@Override
public void exitHeader(HeaderParser.HeaderContext ctx) { }
@Override
public void exitIndex(HeaderParser.IndexContext ctx) {
requiredStack.push(ctx.getText());
}
@Override
public void exitTitle(HeaderParser.TitleContext ctx) {
requiredStack.push(ctx.getText());
}
@Override
public void exitOtherfields(HeaderParser.OtherfieldsContext ctx) { }
@Override
public void exitComposer(HeaderParser.ComposerContext ctx) {
optionalStack.push(ctx.getText());
}
@Override
public void exitMeter(HeaderParser.MeterContext ctx) {
System.out.println(ctx.getText());
optionalStack.push(ctx.getText());
}
@Override
public void exitLength(HeaderParser.LengthContext ctx) {
optionalStack.push(ctx.getText());
}
@Override
public void exitTempo(HeaderParser.TempoContext ctx) {
optionalStack.push(ctx.getText());
}
@Override
public void exitVoice(HeaderParser.VoiceContext ctx) {
optionalStack.push(ctx.getText());
}
@Override
public void exitKey(HeaderParser.KeyContext ctx) {
requiredStack.push(ctx.getText());
}
@Override
public void exitComment(HeaderParser.CommentContext ctx) { }
@Override
public void exitText(HeaderParser.TextContext ctx) { }
// ~~~~~~~~~~~~~~~~~~~
@Override
public void enterEveryRule(ParserRuleContext arg0) { }
@Override
public void exitEveryRule(ParserRuleContext arg0) { }
@Override
public void visitErrorNode(ErrorNode arg0) { }
@Override
public void visitTerminal(TerminalNode arg0) { }
@Override
public void enterRoot(RootContext ctx) { }
@Override
public void enterHeader(HeaderContext ctx) { }
@Override
public void enterIndex(IndexContext ctx) { }
@Override
public void enterTitle(TitleContext ctx) { }
@Override
public void enterOtherfields(OtherfieldsContext ctx) { }
@Override
public void enterComposer(ComposerContext ctx) { }
@Override
public void enterMeter(MeterContext ctx) { }
@Override
public void enterLength(LengthContext ctx) { }
@Override
public void enterTempo(TempoContext ctx) { }
@Override
public void enterVoice(VoiceContext ctx) { }
@Override
public void enterKey(KeyContext ctx) { }
@Override
public void enterComment(CommentContext ctx) { }
@Override
public void enterText(TextContext ctx) { }
@Override
public void enterEndline(EndlineContext ctx) { }
@Override
public void exitEndline(EndlineContext ctx) { }
}
public static Music parseMusic(String input, Fraction defaultNoteLength, KeySignature keySig, String voice){
// try{
// Create a stream of characters from the string
CharStream stream = new ANTLRInputStream(input);
MusicLexer lexer = new MusicLexer(stream);
TokenStream tokens = new CommonTokenStream(lexer);
MusicParser parser = new MusicParser(tokens);
lexer.reportErrorsAsExceptions();
parser.reportErrorsAsExceptions();
// Generate the parse tree using the starter rule.
// root is the starter rule for this grammar.
// Other grammars may have different names for the starter rule.
ParseTree tree = parser.root();
Future<JDialog> inspect = Trees.inspect(tree, parser);
try {
Utils.waitForClose(inspect.get());
} catch (Exception e) {
e.printStackTrace();
}
MakeMusic musicMaker = new MakeMusic(keySig, defaultNoteLength, voice);
new ParseTreeWalker().walk(musicMaker, tree);
return musicMaker.getMusic();
// }
// catch(RuntimeException e){
// System.out.println(e.getMessage()); //not used after debugging
// throw new IllegalArgumentException();
// }
}
static class MakeMusic implements MusicListener{
private final Map<NoteLetter, Accidental> keySig;
private final String voiceName;
private final Fraction defaultNoteLength;
private final Map<Accidental, Integer> accidental = new HashMap<Accidental, Integer>();
private final Stack<Music> stack = new Stack<>();
// public MakeMusic(){
// KeySignatureMap map = new KeySignatureMap();
// this.keySig = KeySignatureMap.KEY_SIGNATURE_MAP.get(KeySignature.valueOf("C_MAJOR"));
// accidental.put(Accidental.valueOf("DOUBLESHARP"), 2);
// accidental.put(Accidental.valueOf("SHARP"), 1);
// accidental.put(Accidental.valueOf("NATURAL"), 0);
// accidental.put(Accidental.valueOf("FLAT"), -1);
// accidental.put(Accidental.valueOf("DOUBLEFLAT"), -2);
//
// }
public MakeMusic(KeySignature keysig, Fraction defaultNoteLength, String voiceName){
KeySignatureMap map = new KeySignatureMap();
this.defaultNoteLength = defaultNoteLength;
this.voiceName = voiceName;
this.keySig = map.KEY_SIGNATURE_MAP.get(keysig);
accidental.put(Accidental.valueOf("DOUBLESHARP"), 2);
accidental.put(Accidental.valueOf("SHARP"), 1);
accidental.put(Accidental.valueOf("NATURAL"), 0);
accidental.put(Accidental.valueOf("FLAT"), -1);
accidental.put(Accidental.valueOf("DOUBLEFLAT"), -2);
}
/**
* @return the music object that was parsed
*/
public Music getMusic(){
return stack.get(0);
}
@Override
public void exitRoot(MusicParser.RootContext ctx) { }
@Override
public void exitMusic(MusicContext ctx) {
List<Music> voiceMeasures = new ArrayList<Music>();
while(!stack.isEmpty()){
voiceMeasures.add(stack.pop());
}
Collections.reverse(voiceMeasures);
Voice voice = new Voice(voiceName, voiceMeasures);
stack.push(voice);
}
@Override
public void exitMeasure(MeasureContext ctx) {
if (ctx.endrepeatmeasure()!= null){
List<Music> repeatBody= new ArrayList<Music>();
List<Music> firstRepeat = new ArrayList<Music>();
List<Music> repeat = new ArrayList<Music>();
while(!stack.isEmpty()){
Music music = stack.pop();
Measure m = (Measure)music;
if (m.isFirstEnding()){
repeat.add(music);
firstRepeat.addAll(repeat);
Collections.reverse(firstRepeat);
repeat = new ArrayList<Music>();
}
else if(m.isStartRepeat()){
repeat.add(music);
repeatBody.addAll(repeat);
Collections.reverse(repeatBody);
repeat = new ArrayList<Music>();
break;
}
else if(m.isDoubleBar()){
repeatBody.addAll(repeat);
stack.push(m);
Collections.reverse(repeatBody);
repeat = new ArrayList<Music>();
break;
}
}
repeat.addAll(repeatBody);
repeat.addAll(firstRepeat);
repeat.addAll(repeatBody);
for (Music m: repeat){
stack.push(m);
}
}
}
@Override
public void exitFirstendingmeasure(FirstendingmeasureContext ctx) {
int numNorm = ctx.normalmeasure().size();
List<Music> measures = new ArrayList<Music>();
for (int i = 0; i < numNorm; i++){
measures.add(stack.pop());
}
Measure startFirstEnding = (Measure) stack.pop();
Measure replacedStartFirst = new Measure(startFirstEnding, true, false, false, false);
measures.add(replacedStartFirst);
Collections.reverse(measures);
for (int i = 0; i < numNorm + 1; i++){
stack.push(measures.get(i));
}
}
@Override
public void exitSecondendingmeasure(SecondendingmeasureContext ctx) { }
@Override
public void exitDoublebarmeasure(DoublebarmeasureContext ctx) {
int numElements = ctx.element().size();
List<Music> elements = new ArrayList<Music>();
for (int i = 0; i < numElements; i++){
elements.add(stack.pop());
}
Collections.reverse(elements);
List<Music> newElements = applyAccidentalsToMeasure(elements);
Measure m = new Measure(newElements, false, false, false, true);
stack.push(m);
}
@Override
public void exitStartrepeatmeasure(StartrepeatmeasureContext ctx) {
int numElements = ctx.element().size();
List<Music> elements = new ArrayList<Music>();
for (int i = 0; i < numElements; i++){
elements.add(stack.pop());
}
Collections.reverse(elements);
List<Music> newElements = applyAccidentalsToMeasure(elements);
Measure m = new Measure(newElements, true, false, false, false);
stack.push(m);
}
@Override
public void exitEndrepeatmeasure(EndrepeatmeasureContext ctx) {
int numElements = ctx.element().size();
List<Music> elements = new ArrayList<Music>();
for (int i = 0; i < numElements; i++){
elements.add(stack.pop());
}
Collections.reverse(elements);
List<Music> newElements = applyAccidentalsToMeasure(elements);
Measure m = new Measure(newElements, false, true, false, false);
stack.push(m);
}
//TODO
@Override
public void exitSinglerepeatmeasure(SinglerepeatmeasureContext ctx) { }
@Override
public void exitNormalmeasure(NormalmeasureContext ctx) {
int numElements = ctx.element().size();
assert stack.size()>= numElements;
List<Music> elements = new ArrayList<Music>();
for (int i = 0; i < numElements; i++){
elements.add(stack.pop());
}
Collections.reverse(elements);
List<Music> newElements = applyAccidentalsToMeasure(elements);
Measure m = new Measure(newElements, false, false, false, false);
stack.push(m);
}
/**
* Checks from beginning to end if list of music elements has accidentals and applies these
* to the rest of the list if found
* @param elements list of music elements to apply accidentals to
* @return modified list of elements
*/
private List<Music> applyAccidentalsToMeasure(List<Music> elements){
// make sure accidentals apply to the entire line
// boolean transpose = false;
// char note = 'y';
// int octave = 0;
// int semitonesUp= 0;
// for (Music m : elements){
// List<Note> notesToCheck = new ArrayList<Note>();
// if(m instanceof Chord){
// Chord chord = (Chord)m;
// notesToCheck = extractChordNotes(chord);
// }
// else if(m instanceof Tuplet){
// Tuplet tuplet = (Tuplet)m;
// notesToCheck = extractTupletNotes(tuplet);
// }
// else if (m instanceof Note){
// Note n = (Note)m;
// notesToCheck= Arrays.asList(n);
// }
// for (Note n: notesToCheck){
// if (n.getTransposeTag()){
// transpose = true;
// note = n.getNoteLetter();
// octave = n.getOctave();
// semitonesUp = n.getAccidental();
// }
// if(transpose){
// n.transposeKey(note, octave, semitonesUp);
// }
// }
// }
// return elements;
Map<String, Integer> accidentalsMap = new HashMap<>();
List<Music> newElements = new ArrayList<>();
for (Music m : elements){
Music newMusic = m.applyAccidentals(accidentalsMap);
newElements.add(newMusic);
}
return newElements;
}
// private List<Note> extractChordNotes(Chord chord){
// List<Note> notes = new ArrayList<Note>();
// for(Music music:chord.chordNotes()){
// notes.add((Note)music);
// }
// return notes;
// }
//
// private List<Note> extractTupletNotes(Tuplet tuplet){
// List<Note> notes = new ArrayList<Note>();
// for(Music music: tuplet.tupletNotes()){
// if (music instanceof Chord){
// Chord chord = (Chord)music;
// notes.addAll(extractChordNotes(chord));
// }
// else{
// Note note = (Note)music;
// notes.add(note);
// }
// }
// return notes;
// }
@Override
public void exitElement(ElementContext ctx) { }
@Override
public void exitNoteelement(NoteelementContext ctx) { }
@Override
public void exitNote(NoteContext ctx) { }
@Override
public void exitPitch(PitchContext ctx) {
System.out.println(ctx.NOTELETTER().getText());
Fraction noteLength = defaultNoteLength;
int octave = 0;
char noteLetter = 'y';
int numAccidental = 0;
boolean transpose = false;
if (ctx.NOTELETTER()!= null){
char note = ctx.NOTELETTER().getText().charAt(0);
if (Character.isLowerCase(note)){
octave +=1;
}
noteLetter = Character.toUpperCase(note);
Accidental acc = keySig.get(NoteLetter.valueOf(Character.toString(noteLetter)));
numAccidental += accidental.get(acc);
}
if (ctx.OCTAVE()!= null){
String octaves = ctx.OCTAVE().getText();
if (octaves.contains(",")){
octave -= octaves.length();
}
else if(octaves.contains("'")){
octave += octaves.length();
}
}
if (ctx.notelength()!= null){
String length = ctx.notelength().getText();
noteLength = parseNoteLength(length);
}
if (ctx.ACCIDENTAL()!= null){
String accidental = ctx.ACCIDENTAL().getText();
if (accidental.contains("_")){
numAccidental = -1 * accidental.length();
}
else if (accidental.contains("^")){
numAccidental = accidental.length();
}
else{
numAccidental = 0;
}
transpose = true;
}
Note n = new Note(noteLength, noteLetter, octave, numAccidental, transpose);
stack.push(n);
}
@Override
public void exitRest(RestContext ctx) {
Fraction noteLength = defaultNoteLength;
if (ctx.notelength()!= null){
String length = ctx.notelength().getText();
noteLength = parseNoteLength(length);
}
Rest r = new Rest(noteLength);
stack.push(r);
}
@Override
public void exitNotelength(NotelengthContext ctx) { }
@Override
public void exitTupletelement(TupletelementContext ctx) {
int tupletNum = Integer.valueOf(ctx.tupletspec().getText().replace("(", ""));
int tupletSize = ctx.noteelement().size();
assert tupletSize >= tupletNum;
assert tupletNum > 1 && tupletNum < 5;
List<Music> tupletNotes = new ArrayList<Music>();
for (int i = 0; i < tupletSize; i++){
tupletNotes.add(stack.pop());
}
Collections.reverse(tupletNotes);
Tuplet t = new Tuplet(tupletNum, tupletNotes);
stack.push(t);
}
@Override
public void exitTupletspec(TupletspecContext ctx) { }
@Override
public void exitChord(ChordContext ctx) {
List<NoteContext> notes = ctx.note();
assert stack.size() >= notes.size();
assert notes.size()>= 1;
List<Music> chordNotes = new ArrayList<Music>();
for (int i = 0; i < notes.size(); i++){
chordNotes.add(stack.pop());
}
Collections.reverse(chordNotes);
Music m = new Chord(chordNotes);
stack.push(m);
}
/**
* Given a string representing a note or rest's length, returns a Fraction object representing the
* given length
* @param length string representation of note/rest's length
* @return Fraction object representing the note/rest's length
*/
private Fraction parseNoteLength(String length){
int numerator;
int denominator;
if(!length.contains("/")){
numerator = Integer.valueOf(length);
denominator = 1;
}
else{
String[] nums = length.split("/");
if (nums.length == 0){
numerator = 1;
denominator = 2;
}
else if (nums.length == 1){
numerator = Integer.valueOf(nums[0]);
denominator = 2;
}
else{
numerator = (nums[0].equals("")) ? 1 : Integer.valueOf(nums[0]);
denominator = Integer.valueOf(nums[1]);
}
}
return new Fraction(numerator * defaultNoteLength.numerator(), denominator * defaultNoteLength.denominator()).simplify();
}
@Override
public void exitComment(MusicParser.CommentContext ctx) { }
@Override
public void exitText(MusicParser.TextContext ctx) { }
//~~~~~~~~~~~~~~
@Override
public void enterEveryRule(ParserRuleContext arg0) { }
@Override
public void exitEveryRule(ParserRuleContext arg0) { }
@Override
public void visitErrorNode(ErrorNode arg0) { }
@Override
public void visitTerminal(TerminalNode arg0) { }
@Override
public void enterRoot(abc.parser.MusicParser.RootContext ctx) {}
@Override
public void enterMusic(MusicContext ctx) {}
@Override
public void enterNote(NoteContext ctx) { }
@Override
public void enterRest(RestContext ctx) {}
@Override
public void enterNotelength(NotelengthContext ctx) {}
@Override
public void enterTupletspec(TupletspecContext ctx) {}
@Override
public void enterComment(abc.parser.MusicParser.CommentContext ctx) { }
@Override
public void enterText(abc.parser.MusicParser.TextContext ctx) { }
@Override
public void enterChord(ChordContext ctx) { }
@Override
public void enterNoteelement(NoteelementContext ctx) { }
@Override
public void enterMeasure(MeasureContext ctx) { }
@Override
public void enterTupletelement(TupletelementContext ctx) { }
@Override
public void enterFirstendingmeasure(FirstendingmeasureContext ctx) { }
@Override
public void enterSecondendingmeasure(SecondendingmeasureContext ctx) { }
@Override
public void enterDoublebarmeasure(DoublebarmeasureContext ctx) { }
@Override
public void enterStartrepeatmeasure(StartrepeatmeasureContext ctx) { }
@Override
public void enterEndrepeatmeasure(EndrepeatmeasureContext ctx) { }
@Override
public void enterNormalmeasure(NormalmeasureContext ctx) { }
@Override
public void enterElement(ElementContext ctx) { }
@Override
public void enterPitch(PitchContext ctx) { }
@Override
public void enterSinglerepeatmeasure(SinglerepeatmeasureContext ctx) { }
}
}
|
deleted unnecessary lines from Parser
|
src/abc/player/Parser.java
|
deleted unnecessary lines from Parser
|
|
Java
|
mit
|
86faf402123e73de9e7fde2f4cf28d872c38c329
| 0
|
happyfoxinc/helpstack-android,kzganesan/helpstack-android,thuytrinh/helpstack-android,NYPL/helpstack-android,NYPL-Simplified/helpstack-android
|
// HSSource
//
//Copyright (c) 2014 HelpStack (http://helpstack.io)
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package com.tenmiles.helpstack.logic;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.text.Html;
import android.text.SpannableString;
import android.util.Log;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.tenmiles.helpstack.HSHelpStack;
import com.tenmiles.helpstack.activities.HSActivityManager;
import com.tenmiles.helpstack.fragments.HSFragmentParent;
import com.tenmiles.helpstack.model.HSAttachment;
import com.tenmiles.helpstack.model.HSDraft;
import com.tenmiles.helpstack.model.HSCachedTicket;
import com.tenmiles.helpstack.model.HSCachedUser;
import com.tenmiles.helpstack.model.HSKBItem;
import com.tenmiles.helpstack.model.HSTicket;
import com.tenmiles.helpstack.model.HSTicketUpdate;
import com.tenmiles.helpstack.model.HSUploadAttachment;
import com.tenmiles.helpstack.model.HSUser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
public class HSSource {
private static final String TAG = HSSource.class.getSimpleName();
private static final String HELPSTACK_DIRECTORY = "helpstack";
private static final String HELPSTACK_TICKETS_FILE_NAME = "tickets";
private static final String HELPSTACK_TICKETS_USER_DATA = "user_credential";
private static final String HELPSTACK_DRAFT = "draft";
private static HSSource singletonInstance = null;
/**
*
* @param context
* @return singleton instance of this class.
*/
public static HSSource getInstance(Context context) {
if (singletonInstance == null) {
synchronized (HSSource.class) { // 1
if (singletonInstance == null) // 2
{
Log.d(TAG, "New Instance");
singletonInstance = new HSSource(
context.getApplicationContext()); // 3
}
}
}
// Can be called even before a gear is set
if (singletonInstance.gear == null) {
singletonInstance.setGear(HSHelpStack.getInstance(context).getGear());
}
return singletonInstance;
}
private HSGear gear;
private Context mContext;
private RequestQueue mRequestQueue;
private HSCachedTicket cachedTicket;
private HSCachedUser cachedUser;
private HSDraft draftObject;
private HSSource(Context context) {
this.mContext = context;
setGear(HSHelpStack.getInstance(context).getGear());
mRequestQueue = HSHelpStack.getInstance(context).getRequestQueue();
cachedTicket = new HSCachedTicket();
cachedUser = new HSCachedUser();
draftObject = new HSDraft();
refreshFieldsFromCache();
}
public void requestKBArticle(String cancelTag, HSKBItem section, OnFetchedArraySuccessListener success, ErrorListener errorListener ) {
if (gear.haveImplementedKBFetching()) {
gear.fetchKBArticle(cancelTag, section,mRequestQueue, new SuccessWrapper(success) {
@Override
public void onSuccess(Object[] successObject) {
assert successObject != null : "It seems requestKBArticle was not implemented in gear" ;
// Do your work here, may be caching, data validation etc.
super.onSuccess(successObject);
}
}, new ErrorWrapper("Fetching KB articles", errorListener));
}
else {
try {
HSArticleReader reader = new HSArticleReader(gear.getLocalArticleResourceId());
success.onSuccess(reader.readArticlesFromResource(mContext));
} catch (XmlPullParserException e) {
e.printStackTrace();
throwError(errorListener, "Unable to parse local article XML");
} catch (IOException e) {
e.printStackTrace();
throwError(errorListener, "Unable to read local article XML");
}
}
}
public void requestAllTickets(OnFetchedArraySuccessListener success, ErrorListener error ) {
if (cachedTicket == null) {
success.onSuccess(new HSTicket[0]);
}
else {
success.onSuccess(cachedTicket.getTickets());
}
}
public void checkForUserDetailsValidity(String cancelTag, String firstName, String lastName, String email,OnFetchedSuccessListener success, ErrorListener errorListener) {
gear.registerNewUser(cancelTag, firstName, lastName, email, mRequestQueue, success, new ErrorWrapper("Registering New User", errorListener));
}
public void createNewTicket(String cancelTag, HSUser user, String subject, String message, HSAttachment[] attachment, OnNewTicketFetchedSuccessListener successListener, ErrorListener errorListener) {
HSUploadAttachment[] upload_attachments = convertAttachmentArrayToUploadAttachment(attachment);
message = message + getDeviceInformation(mContext);
if (gear.canUplaodMessageAsHtmlString()) {
message = Html.toHtml(new SpannableString(message));
}
gear.createNewTicket(cancelTag, user, subject, message, upload_attachments, mRequestQueue, new NewTicketSuccessWrapper(successListener) {
@Override
public void onSuccess(HSUser udpatedUserDetail, HSTicket ticket) {
// Save ticket and user details in cache
// Save properties also later.
doSaveNewTicketPropertiesForGearInCache(ticket);
doSaveNewUserPropertiesForGearInCache(udpatedUserDetail);
super.onSuccess(udpatedUserDetail, ticket);
}
}, new ErrorWrapper("Creating New Ticket", errorListener));
}
public void requestAllUpdatesOnTicket(String cancelTag, HSTicket ticket, OnFetchedArraySuccessListener success, ErrorListener errorListener ) {
gear.fetchAllUpdateOnTicket(cancelTag, ticket, cachedUser.getUser(), mRequestQueue, success, new ErrorWrapper("Fetching updates on Ticket", errorListener));
}
public void addReplyOnATicket(String cancelTag, String message, HSAttachment[] attachments, HSTicket ticket, OnFetchedSuccessListener success, ErrorListener errorListener) {
if (gear.canUplaodMessageAsHtmlString()) {
message = Html.toHtml(new SpannableString(message));
}
gear.addReplyOnATicket(cancelTag, message, convertAttachmentArrayToUploadAttachment(attachments), ticket, getUser(), mRequestQueue, new OnFetchedSuccessListenerWrapper(success, message, attachments) {
@Override
public void onSuccess(Object successObject) {
if (gear.canIgnoreTicketUpdateInformationAfterAddingReply()) {
HSTicketUpdate update = HSTicketUpdate.createUpdateByUser(null, null, this.message, Calendar.getInstance().getTime(), this.attachments);
super.onSuccess(update);
}
else {
super.onSuccess(successObject);
}
}
}, new ErrorWrapper("Adding reply to a ticket", errorListener));
}
public HSGear getGear() {
return gear;
}
private void setGear(HSGear gear) {
this.gear = gear;
}
public boolean isNewUser() {
return cachedUser.getUser() == null;
}
public void refreshUser() {
doReadUserFromCache();
}
public HSUser getUser() {
return cachedUser.getUser();
}
public String getDraftSubject() {
if(draftObject != null) {
return draftObject.getSubject();
}
return null;
}
public String getDraftMessage() {
if(draftObject != null) {
return draftObject.getMessage();
}
return null;
}
public HSUser getDraftUser() {
if(draftObject != null) {
return draftObject.getDraftUser();
}
return null;
}
public HSAttachment[] getDraftAttachments() {
if(draftObject != null) {
return draftObject.getAttachments();
}
return null;
}
public String getDraftReplyMessage() {
if(draftObject != null) {
return draftObject.getDraftReplyMessage();
}
return null;
}
public HSAttachment[] getDraftReplyAttachments() {
if(draftObject != null) {
return draftObject.getDraftReplyAttachments();
}
return null;
}
public void saveTicketDetailsInDraft(String subject, String message, HSAttachment[] attachmentsArray) {
doSaveTicketDraftForGearInCache(subject, message, attachmentsArray);
}
public void saveUserDetailsInDraft(HSUser user) {
doSaveUserDraftForGearInCache(user);
}
public void saveReplyDetailsInDraft(String message, HSAttachment[] attachmentsArray) {
doSaveReplyDraftForGearInCache(message, attachmentsArray);
}
public boolean haveImplementedTicketFetching() {
return gear.haveImplementedTicketFetching();
}
public String getSupportEmailAddress() {
return gear.getCompanySupportEmailAddress();
}
/***
*
* Depending on the setting set on gear, it launches new ticket activity.
*
* if email : launches email [Done]
* else:
* if user logged in : launches user details [Done]
* else: launches new ticket [Done]
*
* @param fragment
* @param requestCode
*/
public void launchCreateNewTicketScreen(HSFragmentParent fragment, int requestCode) {
if (haveImplementedTicketFetching()) {
if(isNewUser()) {
HSActivityManager.startNewIssueActivity(fragment, null, requestCode);
}else {
HSActivityManager.startNewIssueActivity(fragment, getUser(), requestCode);
}
}
else {
launchEmailAppWithEmailAddress(fragment.getActivity());
}
}
public void launchEmailAppWithEmailAddress(Activity activity) {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ getSupportEmailAddress()});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, getDeviceInformation(activity));
activity.startActivity(Intent.createChooser(emailIntent, "Email"));
}
private static String getDeviceInformation(Context activity) {
StringBuilder builder = new StringBuilder();
builder.append("\n\n\n");
builder.append("========");
builder.append("\nDevice Android version : ");
builder.append(Build.VERSION.SDK_INT);
builder.append("\nDevice brand : ");
builder.append(Build.MODEL);
builder.append("\nApplication package :");
try {
builder.append(activity.getPackageManager().getPackageInfo(activity.getPackageName(),0).packageName);
} catch (NameNotFoundException e) {
builder.append("NA");
}
builder.append("\nApplication version :");
try {
builder.append(activity.getPackageManager().getPackageInfo(activity.getPackageName(),0).versionCode);
} catch (NameNotFoundException e) {
builder.append("NA");
}
return builder.toString();
}
public void cancelOperation(String cancelTag) {
mRequestQueue.cancelAll(cancelTag);
}
/////////////////////////////////////////////////
//////// Utility Functions /////////////////
/////////////////////////////////////////////////
public void refreshFieldsFromCache() {
// read the ticket data from cache and maintain here
doReadTicketsFromCache();
doReadUserFromCache();
doReadDraftFromCache();
}
/**
* Opens a file and read its content. Return null if any error occured or file not found
* @param file
* @return
*/
private String readJsonFromFile(File file) {
if (!file.exists()) {
return null;
}
String json = null;
FileInputStream inputStream;
try {
StringBuilder datax = new StringBuilder();
inputStream = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader ( inputStream ) ;
BufferedReader buffreader = new BufferedReader ( isr ) ;
String readString = buffreader.readLine ( ) ;
while ( readString != null ) {
datax.append(readString);
readString = buffreader.readLine ( ) ;
}
isr.close ( ) ;
json = datax.toString();
return json;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void writeJsonIntoFile (File file, String json) {
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(file);
outputStream.write(json.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doSaveNewTicketPropertiesForGearInCache(HSTicket ticket) {
cachedTicket.addTicketAtStart(ticket);
Gson gson = new Gson();
String ticketsgson = gson.toJson(cachedTicket);
File ticketFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_FILE_NAME);
writeJsonIntoFile(ticketFile, ticketsgson);
}
protected void doSaveNewUserPropertiesForGearInCache(HSUser user) {
cachedUser.setUser(user);
Gson gson = new Gson();
String userjson = gson.toJson(cachedUser);
File userFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_USER_DATA);
writeJsonIntoFile(userFile, userjson);
}
protected void doReadTicketsFromCache() {
File ticketFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_FILE_NAME);
String json = readJsonFromFile(ticketFile);
if (json != null) {
Gson gson = new Gson();
cachedTicket = gson.fromJson(json, HSCachedTicket.class);
}
}
protected void doReadUserFromCache() {
File userFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_USER_DATA);
String json = readJsonFromFile(userFile);
if (json != null) {
Gson gson = new Gson();
cachedUser = gson.fromJson(json, HSCachedUser.class);
}
}
protected void doReadDraftFromCache() {
File draftFile = new File(getProjectDirectory(), HELPSTACK_DRAFT);
String json = readJsonFromFile(draftFile);
if (json != null) {
Gson gson = new Gson();
draftObject = gson.fromJson(json, HSDraft.class);
}
}
protected void doSaveTicketDraftForGearInCache(String subject, String message, HSAttachment[] attachmentsArray) {
draftObject.setDraftSubject(subject);
draftObject.setDraftMessage(message);
draftObject.setDraftAttachments(attachmentsArray);
writeDraftIntoFile();
}
protected void doSaveUserDraftForGearInCache(HSUser user) {
draftObject.setDraftUSer(user);
writeDraftIntoFile();
}
protected void doSaveReplyDraftForGearInCache(String message, HSAttachment[] attachmentsArray) {
draftObject.setDraftReplyMessage(message);
draftObject.setDraftReplyAttachments(attachmentsArray);
writeDraftIntoFile();
}
private void writeDraftIntoFile() {
Gson gson = new Gson();
String draftJson = gson.toJson(draftObject);
File draftFile = new File(getProjectDirectory(), HELPSTACK_DRAFT);
writeJsonIntoFile(draftFile, draftJson);
}
protected File getProjectDirectory() {
File projDir = new File(mContext.getFilesDir(), HELPSTACK_DIRECTORY);
if (!projDir.exists())
projDir.mkdirs();
return projDir;
}
public void clearTicketDraft() {
saveTicketDetailsInDraft("", "", null);
}
public void clearReplyDraft() {
saveReplyDetailsInDraft("", null);
}
private class NewTicketSuccessWrapper implements OnNewTicketFetchedSuccessListener
{
private OnNewTicketFetchedSuccessListener lastListner;
public NewTicketSuccessWrapper(OnNewTicketFetchedSuccessListener lastListner) {
this.lastListner = lastListner;
}
@Override
public void onSuccess(HSUser udpatedUserDetail, HSTicket ticket) {
if (lastListner != null)
lastListner.onSuccess(udpatedUserDetail, ticket);
}
}
protected HSUploadAttachment[] convertAttachmentArrayToUploadAttachment(HSAttachment[] attachment) {
HSUploadAttachment[] upload_attachments = new HSUploadAttachment[0];
if (attachment != null && attachment.length > 0) {
int attachmentCount = gear.getNumberOfAttachmentGearCanHandle();
assert attachmentCount >= attachment.length : "Gear cannot handle more than "+attachmentCount+" attachmnets";
upload_attachments = new HSUploadAttachment[attachment.length];
for (int i = 0; i < upload_attachments.length; i++) {
upload_attachments[i] = new HSUploadAttachment(mContext, attachment[i]);
}
}
return upload_attachments;
}
private class SuccessWrapper implements OnFetchedArraySuccessListener
{
private OnFetchedArraySuccessListener lastListner;
public SuccessWrapper(OnFetchedArraySuccessListener lastListner) {
this.lastListner = lastListner;
}
@Override
public void onSuccess(Object[] successObject) {
if (lastListner != null)
lastListner.onSuccess(successObject);
}
}
private class OnFetchedSuccessListenerWrapper implements OnFetchedSuccessListener {
private OnFetchedSuccessListener listener;
protected String message;
protected HSAttachment[] attachments;
private OnFetchedSuccessListenerWrapper(OnFetchedSuccessListener listener, String message, HSAttachment[] attachments) {
this.listener = listener;
this.message = message;
this.attachments = attachments;
}
@Override
public void onSuccess(Object successObject) {
if (this.listener != null) {
this.listener.onSuccess(successObject);
}
}
}
private class ErrorWrapper implements ErrorListener {
private ErrorListener errorListener;
private String methodName;
public ErrorWrapper(String methodName, ErrorListener errorListener) {
this.errorListener = errorListener;
this.methodName = methodName;
}
@Override
public void onErrorResponse(VolleyError error) {
printErrorDescription(methodName, error);
this.errorListener.onErrorResponse(error);
}
}
public static void throwError(ErrorListener errorListener, String error) {
VolleyError volleyError = new VolleyError(error);
printErrorDescription(null, volleyError);
errorListener.onErrorResponse(volleyError);
}
private static void printErrorDescription (String methodName, VolleyError error)
{
if (methodName == null) {
Log.e(HSHelpStack.LOG_TAG, "Error occurred in HelpStack");
}
else {
Log.e(HSHelpStack.LOG_TAG, "Error occurred when executing " + methodName);
}
Log.e(HSHelpStack.LOG_TAG, error.toString());
if (error.getMessage() != null) {
Log.e(HSHelpStack.LOG_TAG, error.getMessage());
}
if (error.networkResponse != null && error.networkResponse.data != null) {
try {
Log.e(HSHelpStack.LOG_TAG, new String(error.networkResponse.data, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
error.printStackTrace();
}
}
|
helpstack/src/com/tenmiles/helpstack/logic/HSSource.java
|
// HSSource
//
//Copyright (c) 2014 HelpStack (http://helpstack.io)
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package com.tenmiles.helpstack.logic;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.text.Html;
import android.text.SpannableString;
import android.util.Log;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.tenmiles.helpstack.HSHelpStack;
import com.tenmiles.helpstack.activities.HSActivityManager;
import com.tenmiles.helpstack.fragments.HSFragmentParent;
import com.tenmiles.helpstack.model.HSAttachment;
import com.tenmiles.helpstack.model.HSDraft;
import com.tenmiles.helpstack.model.HSCachedTicket;
import com.tenmiles.helpstack.model.HSCachedUser;
import com.tenmiles.helpstack.model.HSKBItem;
import com.tenmiles.helpstack.model.HSTicket;
import com.tenmiles.helpstack.model.HSTicketUpdate;
import com.tenmiles.helpstack.model.HSUploadAttachment;
import com.tenmiles.helpstack.model.HSUser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
public class HSSource {
private static final String TAG = HSSource.class.getSimpleName();
private static final String HELPSTACK_DIRECTORY = "helpstack";
private static final String HELPSTACK_TICKETS_FILE_NAME = "tickets";
private static final String HELPSTACK_TICKETS_USER_DATA = "user_credential";
private static final String HELPSTACK_DRAFT = "draft";
private static HSSource singletonInstance = null;
/**
*
* @param context
* @return singleton instance of this class.
*/
public static HSSource getInstance(Context context) {
if (singletonInstance == null) {
synchronized (HSSource.class) { // 1
if (singletonInstance == null) // 2
{
Log.d(TAG, "New Instance");
singletonInstance = new HSSource(
context.getApplicationContext()); // 3
}
// Can be called even before a gear is set
if (singletonInstance.gear == null) {
singletonInstance.setGear(HSHelpStack.getInstance(context).getGear());
}
}
}
return singletonInstance;
}
private HSGear gear;
private Context mContext;
private RequestQueue mRequestQueue;
private HSCachedTicket cachedTicket;
private HSCachedUser cachedUser;
private HSDraft draftObject;
private HSSource(Context context) {
this.mContext = context;
setGear(HSHelpStack.getInstance(context).getGear());
mRequestQueue = HSHelpStack.getInstance(context).getRequestQueue();
cachedTicket = new HSCachedTicket();
cachedUser = new HSCachedUser();
draftObject = new HSDraft();
refreshFieldsFromCache();
}
public void requestKBArticle(String cancelTag, HSKBItem section, OnFetchedArraySuccessListener success, ErrorListener errorListener ) {
if (gear.haveImplementedKBFetching()) {
gear.fetchKBArticle(cancelTag, section,mRequestQueue, new SuccessWrapper(success) {
@Override
public void onSuccess(Object[] successObject) {
assert successObject != null : "It seems requestKBArticle was not implemented in gear" ;
// Do your work here, may be caching, data validation etc.
super.onSuccess(successObject);
}
}, new ErrorWrapper("Fetching KB articles", errorListener));
}
else {
try {
HSArticleReader reader = new HSArticleReader(gear.getLocalArticleResourceId());
success.onSuccess(reader.readArticlesFromResource(mContext));
} catch (XmlPullParserException e) {
e.printStackTrace();
throwError(errorListener, "Unable to parse local article XML");
} catch (IOException e) {
e.printStackTrace();
throwError(errorListener, "Unable to read local article XML");
}
}
}
public void requestAllTickets(OnFetchedArraySuccessListener success, ErrorListener error ) {
if (cachedTicket == null) {
success.onSuccess(new HSTicket[0]);
}
else {
success.onSuccess(cachedTicket.getTickets());
}
}
public void checkForUserDetailsValidity(String cancelTag, String firstName, String lastName, String email,OnFetchedSuccessListener success, ErrorListener errorListener) {
gear.registerNewUser(cancelTag, firstName, lastName, email, mRequestQueue, success, new ErrorWrapper("Registering New User", errorListener));
}
public void createNewTicket(String cancelTag, HSUser user, String subject, String message, HSAttachment[] attachment, OnNewTicketFetchedSuccessListener successListener, ErrorListener errorListener) {
HSUploadAttachment[] upload_attachments = convertAttachmentArrayToUploadAttachment(attachment);
message = message + getDeviceInformation(mContext);
if (gear.canUplaodMessageAsHtmlString()) {
message = Html.toHtml(new SpannableString(message));
}
gear.createNewTicket(cancelTag, user, subject, message, upload_attachments, mRequestQueue, new NewTicketSuccessWrapper(successListener) {
@Override
public void onSuccess(HSUser udpatedUserDetail, HSTicket ticket) {
// Save ticket and user details in cache
// Save properties also later.
doSaveNewTicketPropertiesForGearInCache(ticket);
doSaveNewUserPropertiesForGearInCache(udpatedUserDetail);
super.onSuccess(udpatedUserDetail, ticket);
}
}, new ErrorWrapper("Creating New Ticket", errorListener));
}
public void requestAllUpdatesOnTicket(String cancelTag, HSTicket ticket, OnFetchedArraySuccessListener success, ErrorListener errorListener ) {
gear.fetchAllUpdateOnTicket(cancelTag, ticket, cachedUser.getUser(), mRequestQueue, success, new ErrorWrapper("Fetching updates on Ticket", errorListener));
}
public void addReplyOnATicket(String cancelTag, String message, HSAttachment[] attachments, HSTicket ticket, OnFetchedSuccessListener success, ErrorListener errorListener) {
if (gear.canUplaodMessageAsHtmlString()) {
message = Html.toHtml(new SpannableString(message));
}
gear.addReplyOnATicket(cancelTag, message, convertAttachmentArrayToUploadAttachment(attachments), ticket, getUser(), mRequestQueue, new OnFetchedSuccessListenerWrapper(success, message, attachments) {
@Override
public void onSuccess(Object successObject) {
if (gear.canIgnoreTicketUpdateInformationAfterAddingReply()) {
HSTicketUpdate update = HSTicketUpdate.createUpdateByUser(null, null, this.message, Calendar.getInstance().getTime(), this.attachments);
super.onSuccess(update);
}
else {
super.onSuccess(successObject);
}
}
}, new ErrorWrapper("Adding reply to a ticket", errorListener));
}
public HSGear getGear() {
return gear;
}
private void setGear(HSGear gear) {
this.gear = gear;
}
public boolean isNewUser() {
return cachedUser.getUser() == null;
}
public void refreshUser() {
doReadUserFromCache();
}
public HSUser getUser() {
return cachedUser.getUser();
}
public String getDraftSubject() {
if(draftObject != null) {
return draftObject.getSubject();
}
return null;
}
public String getDraftMessage() {
if(draftObject != null) {
return draftObject.getMessage();
}
return null;
}
public HSUser getDraftUser() {
if(draftObject != null) {
return draftObject.getDraftUser();
}
return null;
}
public HSAttachment[] getDraftAttachments() {
if(draftObject != null) {
return draftObject.getAttachments();
}
return null;
}
public String getDraftReplyMessage() {
if(draftObject != null) {
return draftObject.getDraftReplyMessage();
}
return null;
}
public HSAttachment[] getDraftReplyAttachments() {
if(draftObject != null) {
return draftObject.getDraftReplyAttachments();
}
return null;
}
public void saveTicketDetailsInDraft(String subject, String message, HSAttachment[] attachmentsArray) {
doSaveTicketDraftForGearInCache(subject, message, attachmentsArray);
}
public void saveUserDetailsInDraft(HSUser user) {
doSaveUserDraftForGearInCache(user);
}
public void saveReplyDetailsInDraft(String message, HSAttachment[] attachmentsArray) {
doSaveReplyDraftForGearInCache(message, attachmentsArray);
}
public boolean haveImplementedTicketFetching() {
return gear.haveImplementedTicketFetching();
}
public String getSupportEmailAddress() {
return gear.getCompanySupportEmailAddress();
}
/***
*
* Depending on the setting set on gear, it launches new ticket activity.
*
* if email : launches email [Done]
* else:
* if user logged in : launches user details [Done]
* else: launches new ticket [Done]
*
* @param fragment
* @param requestCode
*/
public void launchCreateNewTicketScreen(HSFragmentParent fragment, int requestCode) {
if (haveImplementedTicketFetching()) {
if(isNewUser()) {
HSActivityManager.startNewIssueActivity(fragment, null, requestCode);
}else {
HSActivityManager.startNewIssueActivity(fragment, getUser(), requestCode);
}
}
else {
launchEmailAppWithEmailAddress(fragment.getActivity());
}
}
public void launchEmailAppWithEmailAddress(Activity activity) {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ getSupportEmailAddress()});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, getDeviceInformation(activity));
activity.startActivity(Intent.createChooser(emailIntent, "Email"));
}
private static String getDeviceInformation(Context activity) {
StringBuilder builder = new StringBuilder();
builder.append("\n\n\n");
builder.append("========");
builder.append("\nDevice Android version : ");
builder.append(Build.VERSION.SDK_INT);
builder.append("\nDevice brand : ");
builder.append(Build.MODEL);
builder.append("\nApplication package :");
try {
builder.append(activity.getPackageManager().getPackageInfo(activity.getPackageName(),0).packageName);
} catch (NameNotFoundException e) {
builder.append("NA");
}
builder.append("\nApplication version :");
try {
builder.append(activity.getPackageManager().getPackageInfo(activity.getPackageName(),0).versionCode);
} catch (NameNotFoundException e) {
builder.append("NA");
}
return builder.toString();
}
public void cancelOperation(String cancelTag) {
mRequestQueue.cancelAll(cancelTag);
}
/////////////////////////////////////////////////
//////// Utility Functions /////////////////
/////////////////////////////////////////////////
public void refreshFieldsFromCache() {
// read the ticket data from cache and maintain here
doReadTicketsFromCache();
doReadUserFromCache();
doReadDraftFromCache();
}
/**
* Opens a file and read its content. Return null if any error occured or file not found
* @param file
* @return
*/
private String readJsonFromFile(File file) {
if (!file.exists()) {
return null;
}
String json = null;
FileInputStream inputStream;
try {
StringBuilder datax = new StringBuilder();
inputStream = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader ( inputStream ) ;
BufferedReader buffreader = new BufferedReader ( isr ) ;
String readString = buffreader.readLine ( ) ;
while ( readString != null ) {
datax.append(readString);
readString = buffreader.readLine ( ) ;
}
isr.close ( ) ;
json = datax.toString();
return json;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void writeJsonIntoFile (File file, String json) {
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(file);
outputStream.write(json.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doSaveNewTicketPropertiesForGearInCache(HSTicket ticket) {
cachedTicket.addTicketAtStart(ticket);
Gson gson = new Gson();
String ticketsgson = gson.toJson(cachedTicket);
File ticketFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_FILE_NAME);
writeJsonIntoFile(ticketFile, ticketsgson);
}
protected void doSaveNewUserPropertiesForGearInCache(HSUser user) {
cachedUser.setUser(user);
Gson gson = new Gson();
String userjson = gson.toJson(cachedUser);
File userFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_USER_DATA);
writeJsonIntoFile(userFile, userjson);
}
protected void doReadTicketsFromCache() {
File ticketFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_FILE_NAME);
String json = readJsonFromFile(ticketFile);
if (json != null) {
Gson gson = new Gson();
cachedTicket = gson.fromJson(json, HSCachedTicket.class);
}
}
protected void doReadUserFromCache() {
File userFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_USER_DATA);
String json = readJsonFromFile(userFile);
if (json != null) {
Gson gson = new Gson();
cachedUser = gson.fromJson(json, HSCachedUser.class);
}
}
protected void doReadDraftFromCache() {
File draftFile = new File(getProjectDirectory(), HELPSTACK_DRAFT);
String json = readJsonFromFile(draftFile);
if (json != null) {
Gson gson = new Gson();
draftObject = gson.fromJson(json, HSDraft.class);
}
}
protected void doSaveTicketDraftForGearInCache(String subject, String message, HSAttachment[] attachmentsArray) {
draftObject.setDraftSubject(subject);
draftObject.setDraftMessage(message);
draftObject.setDraftAttachments(attachmentsArray);
writeDraftIntoFile();
}
protected void doSaveUserDraftForGearInCache(HSUser user) {
draftObject.setDraftUSer(user);
writeDraftIntoFile();
}
protected void doSaveReplyDraftForGearInCache(String message, HSAttachment[] attachmentsArray) {
draftObject.setDraftReplyMessage(message);
draftObject.setDraftReplyAttachments(attachmentsArray);
writeDraftIntoFile();
}
private void writeDraftIntoFile() {
Gson gson = new Gson();
String draftJson = gson.toJson(draftObject);
File draftFile = new File(getProjectDirectory(), HELPSTACK_DRAFT);
writeJsonIntoFile(draftFile, draftJson);
}
protected File getProjectDirectory() {
File projDir = new File(mContext.getFilesDir(), HELPSTACK_DIRECTORY);
if (!projDir.exists())
projDir.mkdirs();
return projDir;
}
public void clearTicketDraft() {
saveTicketDetailsInDraft("", "", null);
}
public void clearReplyDraft() {
saveReplyDetailsInDraft("", null);
}
private class NewTicketSuccessWrapper implements OnNewTicketFetchedSuccessListener
{
private OnNewTicketFetchedSuccessListener lastListner;
public NewTicketSuccessWrapper(OnNewTicketFetchedSuccessListener lastListner) {
this.lastListner = lastListner;
}
@Override
public void onSuccess(HSUser udpatedUserDetail, HSTicket ticket) {
if (lastListner != null)
lastListner.onSuccess(udpatedUserDetail, ticket);
}
}
protected HSUploadAttachment[] convertAttachmentArrayToUploadAttachment(HSAttachment[] attachment) {
HSUploadAttachment[] upload_attachments = new HSUploadAttachment[0];
if (attachment != null && attachment.length > 0) {
int attachmentCount = gear.getNumberOfAttachmentGearCanHandle();
assert attachmentCount >= attachment.length : "Gear cannot handle more than "+attachmentCount+" attachmnets";
upload_attachments = new HSUploadAttachment[attachment.length];
for (int i = 0; i < upload_attachments.length; i++) {
upload_attachments[i] = new HSUploadAttachment(mContext, attachment[i]);
}
}
return upload_attachments;
}
private class SuccessWrapper implements OnFetchedArraySuccessListener
{
private OnFetchedArraySuccessListener lastListner;
public SuccessWrapper(OnFetchedArraySuccessListener lastListner) {
this.lastListner = lastListner;
}
@Override
public void onSuccess(Object[] successObject) {
if (lastListner != null)
lastListner.onSuccess(successObject);
}
}
private class OnFetchedSuccessListenerWrapper implements OnFetchedSuccessListener {
private OnFetchedSuccessListener listener;
protected String message;
protected HSAttachment[] attachments;
private OnFetchedSuccessListenerWrapper(OnFetchedSuccessListener listener, String message, HSAttachment[] attachments) {
this.listener = listener;
this.message = message;
this.attachments = attachments;
}
@Override
public void onSuccess(Object successObject) {
if (this.listener != null) {
this.listener.onSuccess(successObject);
}
}
}
private class ErrorWrapper implements ErrorListener {
private ErrorListener errorListener;
private String methodName;
public ErrorWrapper(String methodName, ErrorListener errorListener) {
this.errorListener = errorListener;
this.methodName = methodName;
}
@Override
public void onErrorResponse(VolleyError error) {
printErrorDescription(methodName, error);
this.errorListener.onErrorResponse(error);
}
}
public static void throwError(ErrorListener errorListener, String error) {
VolleyError volleyError = new VolleyError(error);
printErrorDescription(null, volleyError);
errorListener.onErrorResponse(volleyError);
}
private static void printErrorDescription (String methodName, VolleyError error)
{
if (methodName == null) {
Log.e(HSHelpStack.LOG_TAG, "Error occurred in HelpStack");
}
else {
Log.e(HSHelpStack.LOG_TAG, "Error occurred when executing " + methodName);
}
Log.e(HSHelpStack.LOG_TAG, error.toString());
if (error.getMessage() != null) {
Log.e(HSHelpStack.LOG_TAG, error.getMessage());
}
if (error.networkResponse != null && error.networkResponse.data != null) {
try {
Log.e(HSHelpStack.LOG_TAG, new String(error.networkResponse.data, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
error.printStackTrace();
}
}
|
Fix the gear resource handling in wrong loop
|
helpstack/src/com/tenmiles/helpstack/logic/HSSource.java
|
Fix the gear resource handling in wrong loop
|
|
Java
|
mit
|
f7927fceaf213c5a5d56af11c008e8a60df9abec
| 0
|
InfinityPhase/CARIS,InfinityPhase/CARIS
|
package caris.framework.reactions;
import caris.framework.basereactions.Reaction;
import caris.framework.library.GuildInfo.SpecialChannel;
import caris.framework.library.Variables;
import caris.framework.utilities.BotUtils;
import caris.framework.utilities.Logger;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IGuild;
public class ReactionChannelAssign extends Reaction {
public IGuild guild;
public IChannel channel;
public SpecialChannel channelType;
public ReactionChannelAssign(IGuild guild, IChannel channel, SpecialChannel channelType) {
this(guild, channel, channelType, -1);
}
public ReactionChannelAssign(IGuild guild, IChannel channel, SpecialChannel channelType, int priority) {
super(priority);
this.guild = guild;
this.channel = channel;
this.channelType = channelType;
}
@Override
public void run() {
Variables.guildIndex.get(guild).specialChannels.put(channelType, channel);
if( channel == null ) {
switch(channelType) {
case DEFAULT:
Logger.print("Default channel reset in guild <" + guild.getName() + "> (" + guild.getLongID() + ")", 3);
break;
case LOG:
Logger.print("Log channel reset in guild <" + guild.getName() + "> (" + guild.getLongID() + ")", 3);
break;
default:
Logger.error("Invalid ChannelType in ReactionChannelAssign");
break;
}
} else {
switch(channelType) {
case DEFAULT:
BotUtils.sendMessage(channel, "This channel has been set as the default channel!");
Logger.print("Channel (" + channel.getLongID() + ") <" + channel.getName() + "> set as default channel in guild <" + guild.getName() + "> (" + guild.getLongID() + ")", 3);
break;
case LOG:
BotUtils.sendMessage(channel, "This channel has been set as the log channel!");
Logger.print("Channel (" + channel.getLongID() + ") <" + channel.getName() + "> set as log channel in guild <" + guild.getName() + "> (" + guild.getLongID() + ")", 3);
break;
default:
Logger.error("Invalid ChannelType in ReactionChannelAssign");
break;
}
}
}
}
|
src/caris/framework/reactions/ReactionChannelAssign.java
|
package caris.framework.reactions;
import caris.framework.basereactions.Reaction;
import caris.framework.library.Variables;
import caris.framework.utilities.Logger;
import caris.framework.library.GuildInfo.SpecialChannel;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IGuild;
import utilities.BotUtils;
public class ReactionChannelAssign extends Reaction {
public IGuild guild;
public IChannel channel;
public SpecialChannel channelType;
public ReactionChannelAssign(IGuild guild, IChannel channel, SpecialChannel channelType) {
this(guild, channel, channelType, -1);
}
public ReactionChannelAssign(IGuild guild, IChannel channel, SpecialChannel channelType, int priority) {
super(priority);
this.guild = guild;
this.channel = channel;
this.channelType = channelType;
}
@Override
public void run() {
Variables.guildIndex.get(guild).specialChannels.put(channelType, channel);
if( channel == null ) {
switch(channelType) {
case DEFAULT:
Logger.print("Default channel reset in guild <" + guild.getName() + "> (" + guild.getLongID() + ")", 3);
break;
case LOG:
Logger.print("Log channel reset in guild <" + guild.getName() + "> (" + guild.getLongID() + ")", 3);
break;
default:
Logger.error("Invalid ChannelType in ReactionChannelAssign");
break;
}
} else {
switch(channelType) {
case DEFAULT:
BotUtils.sendMessage(channel, "This channel has been set as the default channel!");
Logger.print("Channel (" + channel.getLongID() + ") <" + channel.getName() + "> set as default channel in guild <" + guild.getName() + "> (" + guild.getLongID() + ")", 3);
break;
case LOG:
BotUtils.sendMessage(channel, "This channel has been set as the log channel!");
Logger.print("Channel (" + channel.getLongID() + ") <" + channel.getName() + "> set as log channel in guild <" + guild.getName() + "> (" + guild.getLongID() + ")", 3);
break;
default:
Logger.error("Invalid ChannelType in ReactionChannelAssign");
break;
}
}
}
}
|
Critical error with calling old code
|
src/caris/framework/reactions/ReactionChannelAssign.java
|
Critical error with calling old code
|
|
Java
|
epl-1.0
|
1c472bcc2c961d9474d95f3ecf9b1b8108113e1f
| 0
|
codenvy/plugin-datasource,codenvy/plugin-datasource
|
/*
* Copyright 2014 Codenvy, S.A.
*
* 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.codenvy.ide.ext.datasource.client.sqllauncher;
import static com.google.gwt.user.client.ui.HasHorizontalAlignment.ALIGN_LEFT;
import java.util.Collection;
import java.util.List;
import javax.validation.constraints.NotNull;
import com.codenvy.ide.api.notification.Notification;
import com.codenvy.ide.api.notification.Notification.Type;
import com.codenvy.ide.api.notification.NotificationManager;
import com.codenvy.ide.api.preferences.PreferencesManager;
import com.codenvy.ide.api.ui.workspace.WorkspaceAgent;
import com.codenvy.ide.dto.DtoFactory;
import com.codenvy.ide.ext.datasource.client.DatabaseInfoStore;
import com.codenvy.ide.ext.datasource.client.DatasourceClientService;
import com.codenvy.ide.ext.datasource.client.DatasourceManager;
import com.codenvy.ide.ext.datasource.client.DatasourceUiResources;
import com.codenvy.ide.ext.datasource.client.common.AlignableColumnHeader;
import com.codenvy.ide.ext.datasource.client.common.ReadableContentTextEditor;
import com.codenvy.ide.ext.datasource.client.common.TextEditorPartAdapter;
import com.codenvy.ide.ext.datasource.client.events.DatasourceListChangeEvent;
import com.codenvy.ide.ext.datasource.client.events.DatasourceListChangeHandler;
import com.codenvy.ide.ext.datasource.client.explorer.DatasourceExplorerPartPresenter;
import com.codenvy.ide.ext.datasource.client.service.MetadataNotificationConstants;
import com.codenvy.ide.ext.datasource.client.sqleditor.EditorDatasourceOracle;
import com.codenvy.ide.ext.datasource.client.sqleditor.SqlEditorProvider;
import com.codenvy.ide.ext.datasource.client.sqllauncher.RequestResultHeader.RequestResultDelegate;
import com.codenvy.ide.ext.datasource.shared.DatabaseConfigurationDTO;
import com.codenvy.ide.ext.datasource.shared.DatabaseDTO;
import com.codenvy.ide.ext.datasource.shared.MultipleRequestExecutionMode;
import com.codenvy.ide.ext.datasource.shared.request.ExecutionErrorResultDTO;
import com.codenvy.ide.ext.datasource.shared.request.RequestResultDTO;
import com.codenvy.ide.ext.datasource.shared.request.RequestResultGroupDTO;
import com.codenvy.ide.ext.datasource.shared.request.SelectResultDTO;
import com.codenvy.ide.ext.datasource.shared.request.UpdateResultDTO;
import com.codenvy.ide.rest.AsyncRequestCallback;
import com.codenvy.ide.rest.StringUnmarshaller;
import com.codenvy.ide.util.loging.Log;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.TableCellElement;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.view.client.CellPreviewEvent;
import com.google.gwt.view.client.ListDataProvider;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
public class SqlRequestLauncherPresenter extends TextEditorPartAdapter<ReadableContentTextEditor> implements
SqlRequestLauncherView.ActionDelegate,
DatasourceListChangeHandler,
RequestResultDelegate {
/** Preference property name for default result limit. */
private static final String PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT = "SqlEditor_default_request_limit";
/** Default value for request limit (when no pref is set). */
private static final int DEFAULT_REQUEST_LIMIT = 20;
private static final MultipleRequestExecutionMode DEFAULT_EXECUTION_MODE =
MultipleRequestExecutionMode.STOP_AT_FIRST_ERROR;
/** The matching view. */
private final SqlRequestLauncherView view;
/** The i18n-able constants. */
private final SqlRequestLauncherConstants constants;
private final MetadataNotificationConstants notificationConstants;
/** The DTO factory. */
private final DtoFactory dtoFactory;
private String selectedDatasourceId = null;
private int resultLimit = DEFAULT_REQUEST_LIMIT;
private MultipleRequestExecutionMode executionMode = DEFAULT_EXECUTION_MODE;
private final DatasourceClientService datasourceClientService;
private final NotificationManager notificationManager;
private final DatasourceManager datasourceManager;
private final DatabaseInfoStore databaseInfoStore;
private final EditorDatasourceOracle editorDatasourceOracle;
private final CellTableResourcesQueryResults cellTableResources;
private final DatasourceUiResources datasourceUiResources;
@Inject
public SqlRequestLauncherPresenter(final @NotNull SqlRequestLauncherView view,
final @NotNull SqlRequestLauncherConstants constants,
final @NotNull MetadataNotificationConstants notificationConstants,
final @NotNull PreferencesManager preferencesManager,
final @NotNull SqlEditorProvider sqlEditorProvider,
final @NotNull DatasourceClientService service,
final @NotNull DatabaseInfoStore databaseInfoStore,
final @NotNull NotificationManager notificationManager,
final @NotNull DatasourceManager datasourceManager,
final @NotNull EditorDatasourceOracle editorDatasourceOracle,
final @NotNull EventBus eventBus,
final @NotNull DtoFactory dtoFactory,
final @NotNull WorkspaceAgent workspaceAgent,
final @NotNull CellTableResourcesQueryResults cellTableResources,
final @NotNull DatasourceUiResources datasourceUiResources) {
super(sqlEditorProvider.getEditor(), workspaceAgent, eventBus);
this.databaseInfoStore = databaseInfoStore;
this.editorDatasourceOracle = editorDatasourceOracle;
Log.info(SqlRequestLauncherPresenter.class, "New instance of SQL request launcher presenter resquested.");
this.view = view;
this.view.setDelegate(this);
this.constants = constants;
this.notificationConstants = notificationConstants;
this.dtoFactory = dtoFactory;
this.datasourceClientService = service;
this.notificationManager = notificationManager;
this.datasourceManager = datasourceManager;
this.cellTableResources = cellTableResources;
this.datasourceUiResources = datasourceUiResources;
setupResultLimit(preferencesManager);
setupExecutionMode(preferencesManager);
// register for datasource creation events
eventBus.addHandler(DatasourceListChangeEvent.getType(), this);
}
private void setupResultLimit(final PreferencesManager preferencesManager) {
final String prefRequestLimit = preferencesManager.getValue(PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT);
if (prefRequestLimit != null) {
try {
int prefValue = Integer.valueOf(prefRequestLimit);
if (prefValue > 0) {
this.resultLimit = prefValue;
} else {
Log.warn(SqlRequestLauncherPresenter.class, "negative value stored in preference "
+ PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT);
}
} catch (final NumberFormatException e) {
StringBuilder sb = new StringBuilder("Preference stored in ")
.append(PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT)
.append(" is not an integer (")
.append(resultLimit)
.append(").");
Log.warn(SqlRequestLauncherPresenter.class, sb.toString());
}
}
// push the request limit value to the view
this.view.setResultLimit(this.resultLimit);
}
private void setupExecutionMode(final PreferencesManager preferencesManager) {
// TODO : try to read preferences
this.view.setExecutionMode(this.executionMode);
}
private void setupDatasourceComponent() {
Collection<String> datasourceIds = this.datasourceManager.getNames();
this.view.setDatasourceList(datasourceIds);
}
@Override
public void go(final AcceptsOneWidget container) {
container.setWidget(view);
getEditor().go(this.view.getEditorZone());
setupDatasourceComponent();
}
@Override
public void datasourceChanged(final String dataSourceId) {
String tempDataSourceId = dataSourceId; // we need newDataSourceId to be final so we must use a temp var here
if (dataSourceId == null || dataSourceId.isEmpty()) {
tempDataSourceId = null;
}
final String newDataSourceId = tempDataSourceId;
Log.info(SqlRequestLauncherPresenter.class, "Datasource changed to " + newDataSourceId);
this.selectedDatasourceId = newDataSourceId;
String editorFileId = getEditorInput().getFile().getId();
Log.info(SqlRequestLauncherPresenter.class, "Associating editor file id " + editorFileId + " to datasource " + newDataSourceId);
editorDatasourceOracle.setSelectedDatasourceId(editorFileId, newDataSourceId);
if (newDataSourceId == null) {
return;
}
DatabaseDTO dsMeta = databaseInfoStore.getDatabaseInfo(newDataSourceId);
if (dsMeta == null) {
try {
final Notification fetchDatabaseNotification = new Notification(notificationConstants.notificationFetchStart(),
Notification.Status.PROGRESS);
notificationManager.showNotification(fetchDatabaseNotification);
datasourceClientService.fetchDatabaseInfo(datasourceManager.getByName(newDataSourceId),
new AsyncRequestCallback<String>(new StringUnmarshaller()) {
@Override
protected void onSuccess(String result) {
DatabaseDTO database = dtoFactory.createDtoFromJson(result,
DatabaseDTO.class);
fetchDatabaseNotification.setMessage(notificationConstants.notificationFetchSuccess());
fetchDatabaseNotification.setStatus(Notification.Status.FINISHED);
notificationManager.showNotification(fetchDatabaseNotification);
databaseInfoStore.setDatabaseInfo(newDataSourceId, database);
}
@Override
protected void onFailure(Throwable exception) {
fetchDatabaseNotification.setStatus(Notification.Status.FINISHED);
notificationManager.showNotification(new Notification(
notificationConstants.notificationFetchFailure(),
Type.ERROR));
}
}
);
} catch (RequestException e) {
Log.error(DatasourceExplorerPartPresenter.class,
"Exception on database info fetch : " + e.getMessage());
notificationManager.showNotification(new Notification(notificationConstants.notificationFetchFailure(),
Type.ERROR));
}
}
}
@Override
public void resultLimitChanged(final String newResultLimitString) {
Log.info(SqlRequestLauncherPresenter.class, "Attempt to change result limit to " + newResultLimitString);
int resultLimitValue;
try {
resultLimitValue = Integer.parseInt(newResultLimitString);
if (resultLimit < 0) {
Log.debug(SqlRequestLauncherPresenter.class, " new value for result limit is negative - abort change");
this.view.setResultLimit(this.resultLimit);
} else {
Log.debug(SqlRequestLauncherPresenter.class, " valid value for result limit - changed");
this.resultLimit = resultLimitValue;
}
} catch (NumberFormatException e) {
Log.debug(SqlRequestLauncherPresenter.class, " new value for result limit is not a number - abort change");
this.view.setResultLimit(this.resultLimit);
}
}
private String getSqlRequestInput() {
final String selection = getSelectedText();
if (selection == null || "".equals(selection.trim())) {
final String content = getEditorContent();
return content;
} else {
return selection;
}
}
/**
* Return the selected content of the editor zone.
*
* @return the selected content
*/
private String getSelectedText() {
return getEditor().getSelectedContent();
}
/**
* Return the whole content of the editor zone.
*
* @return the content of the editor
*/
private String getEditorContent() {
return getEditor().getEditorContent();
}
@Override
public void executeRequested() {
Log.info(SqlRequestLauncherPresenter.class, "Execution requested.");
if (this.selectedDatasourceId == null) {
Window.alert("No datasource selected");
return;
}
if (this.executionMode == null) {
Window.alert("No execute mode selected");
return;
}
DatabaseConfigurationDTO databaseConf = this.datasourceManager.getByName(this.selectedDatasourceId);
String rawSql = getSqlRequestInput();
if (rawSql != null) {
rawSql = rawSql.trim();
if (!"".equals(rawSql)) {
try {
final Notification requestNotification = new Notification("Executing SQL request...",
Notification.Status.PROGRESS);
final Long startRequestTime = System.currentTimeMillis();
AsyncRequestCallback<String> callback = new AsyncRequestCallback<String>(new StringUnmarshaller()) {
@Override
protected void onSuccess(final String result) {
final Long endRequestTime = System.currentTimeMillis();
final Long requestDuration = endRequestTime - startRequestTime;
Log.info(SqlRequestLauncherPresenter.class, "SQL request result received (" + requestDuration + "ms)");
requestNotification.setMessage("SQL request execution completed");
requestNotification.setStatus(Notification.Status.FINISHED);
final Long startJsonTime = System.currentTimeMillis();
final RequestResultGroupDTO resultDto = dtoFactory.createDtoFromJson(result,
RequestResultGroupDTO.class);
final Long endJsonTime = System.currentTimeMillis();
final Long jsonDuration = endJsonTime - startJsonTime;
Log.info(SqlRequestLauncherPresenter.class, "Result converted from JSON(" + jsonDuration + "ms)");
final Long startDisplayTime = System.currentTimeMillis();
updateResultDisplay(resultDto);
final Long endDisplayTime = System.currentTimeMillis();
final Long displayDuration = endDisplayTime - startDisplayTime;
Log.info(SqlRequestLauncherPresenter.class, "Build display for SQL request result(" + displayDuration + "ms)");
}
@Override
protected void onFailure(final Throwable exception) {
Log.info(SqlRequestLauncherPresenter.class, "SQL request failure " + exception.getMessage());
GWT.log("Full exception :", exception);
requestNotification.setStatus(Notification.Status.FINISHED);
notificationManager.showNotification(new Notification("SQL request failed",
Type.ERROR));
updateResultDisplay(exception.getMessage());
}
};
notificationManager.showNotification(requestNotification);
datasourceClientService.executeSqlRequest(databaseConf,
this.resultLimit,
rawSql,
this.executionMode,
callback);
} catch (final RequestException e) {
Log.error(SqlRequestLauncherPresenter.class,
"Exception on SQL request execution : " + e.getMessage());
notificationManager.showNotification(new Notification("Failed execution of SQL request",
Type.ERROR));
}
} else {
Window.alert("No SQL request");
}
} else {
Window.alert("No SQL request");
}
}
protected void updateResultDisplay(final String message) {
Log.info(SqlRequestLauncherPresenter.class, "Printing request error message.");
Label messageLabel = new Label(message);
this.view.appendResult(messageLabel);
}
/**
* Update the result zone to display the last SQL execution result.
*
* @param resultDto the result data
*/
protected void updateResultDisplay(final RequestResultGroupDTO resultDto) {
Log.info(SqlRequestLauncherPresenter.class,
"Printing request results. (" + resultDto.getResults().size() + " individual results).");
this.view.clearResultZone();
for (final RequestResultDTO result : resultDto.getResults()) {
switch (result.getResultType()) {
case UpdateResultDTO.TYPE:
Log.info(SqlRequestLauncherPresenter.class, "Found one result of type 'update'.");
appendUpdateResult(result);
break;
case SelectResultDTO.TYPE:
Log.info(SqlRequestLauncherPresenter.class, "Found one result of type 'select'.");
appendSelectResult(result);
break;
case ExecutionErrorResultDTO.TYPE:
Log.info(SqlRequestLauncherPresenter.class, "Found one result of type 'error'.");
appendErrorReport(result);
break;
default:
Log.error(SqlRequestLauncherPresenter.class, "unknown result type : "
+ result.getResultType());
this.view.appendResult(new Label("Result can't be displayed"));
}
}
Log.info(SqlRequestLauncherPresenter.class, "All individual results are processed.");
}
/**
* Append a result for an failed request to the result zone.
*
* @param result the result data
*/
private void appendErrorReport(final RequestResultDTO result) {
final RequestResultHeader infoHeader = buildErrorHeader(result.getOriginRequest());
this.view.appendResult(infoHeader, new Label(Integer.toString(result.getSqlExecutionError().getErrorCode())
+ " - "
+ result.getSqlExecutionError().getErrorMessage()));
}
/**
* Append a result for an select request to the result zone.
*
* @param result the result data
*/
private void appendSelectResult(final RequestResultDTO result) {
final CellTable<List<String>> resultTable = new CellTable<List<String>>(result.getResultLines().size(), cellTableResources);
final RequestResultHeader infoHeader = buildResultHeader(result, constants.exportCsvLabel());
int i = 0;
for (final String headerEntry : result.getHeaderLine()) {
resultTable.addColumn(new FixedIndexTextColumn(i, ALIGN_LEFT),
new AlignableColumnHeader(headerEntry, ALIGN_LEFT));
i++;
}
resultTable.addCellPreviewHandler(new CellPreviewEvent.Handler<List<String>>() {
@Override
public void onCellPreview(CellPreviewEvent<List<String>> event) {
if ("click".equals(event.getNativeEvent().getType())) {
TableCellElement cellElement = resultTable.getRowElement(event.getIndex()).getCells().getItem(event.getColumn());
cellElement.setTitle(cellElement.getInnerText());
}
}
});
new ListDataProvider<List<String>>(result.getResultLines()).addDataDisplay(resultTable);
this.view.appendResult(infoHeader, resultTable);
}
/**
* Append a result for an update request to the result zone.
*
* @param result the result data
*/
private void appendUpdateResult(final RequestResultDTO result) {
final RequestResultHeader infoHeader = buildResultHeader(result, null);
this.view.appendResult(infoHeader, new Label(this.constants.updateCountMessage(result.getUpdateCount())));
}
/**
* Creates a result header for SQL requests result that succeeded.
*
* @param originRequest the SQL request
* @return a result header
*/
private RequestResultHeader buildResultHeader(final RequestResultDTO requestResult, final String text) {
final RequestResultHeader result = new RequestResultHeader(this.datasourceUiResources.datasourceUiCSS(), this);
result.setInfoHeaderTitle(constants.queryResultsTitle());
result.setRequestReminder(requestResult.getOriginRequest());
if (text != null) {
result.withExportButton(requestResult, text);
}
return result.prepare();
}
/**
* Creates a result header for SQL requests result that failed.
*
* @param originRequest the SQL request
* @return a result header
*/
private RequestResultHeader buildErrorHeader(final String originRequest) {
final RequestResultHeader result = new RequestResultHeader(this.datasourceUiResources.datasourceUiCSS(), this);
result.setInfoHeaderTitle(constants.queryErrorTitle());
result.setRequestReminder(originRequest);
return result.prepare();
}
@Override
public void onDatasourceListChange(final DatasourceListChangeEvent event) {
this.setupDatasourceComponent();
}
@Override
public void executionModeChanged(final MultipleRequestExecutionMode mode) {
this.executionMode = mode;
}
@Override
public boolean onClose() {
boolean parentResult = super.onClose();
final String editorFileId = getEditorInput().getFile().getId();
this.editorDatasourceOracle.forgetEditor(editorFileId);
return parentResult;
}
@Override
public void triggerCsvExport(final RequestResultDTO requestResult, final RequestResultHeader origin) {
final Notification requestNotification = new Notification("Generating CSV export of results...",
Notification.Status.PROGRESS);
this.notificationManager.showNotification(requestNotification);
try {
this.datasourceClientService.exportAsCsv(requestResult, new AsyncRequestCallback<String>(new StringUnmarshaller()) {
@Override
protected void onSuccess(final String result) {
Log.info(SqlRequestLauncherPresenter.class, "CSV export : success.");
requestNotification.setStatus(Notification.Status.FINISHED);
notificationManager.showNotification(new Notification("CSV export : success", Type.INFO));
origin.showCsvLink(result);
}
@Override
protected void onFailure(final Throwable e) {
Log.error(SqlRequestLauncherPresenter.class, "Exception on CSV export : " + e.getMessage());
notificationManager.showNotification(new Notification("CSV export failure", Type.ERROR));
}
});
} catch (RequestException e) {
Log.error(SqlRequestLauncherPresenter.class, "Exception on CSV export : " + e.getMessage());
this.notificationManager.showNotification(new Notification("CSV export failure", Type.ERROR));
}
}
}
|
codenvy-ext-datasource-client/src/main/java/com/codenvy/ide/ext/datasource/client/sqllauncher/SqlRequestLauncherPresenter.java
|
/*
* Copyright 2014 Codenvy, S.A.
*
* 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.codenvy.ide.ext.datasource.client.sqllauncher;
import static com.google.gwt.user.client.ui.HasHorizontalAlignment.ALIGN_LEFT;
import java.util.Collection;
import java.util.List;
import javax.validation.constraints.NotNull;
import com.codenvy.ide.api.notification.Notification;
import com.codenvy.ide.api.notification.Notification.Type;
import com.codenvy.ide.api.notification.NotificationManager;
import com.codenvy.ide.api.preferences.PreferencesManager;
import com.codenvy.ide.api.ui.workspace.WorkspaceAgent;
import com.codenvy.ide.dto.DtoFactory;
import com.codenvy.ide.ext.datasource.client.DatabaseInfoStore;
import com.codenvy.ide.ext.datasource.client.DatasourceClientService;
import com.codenvy.ide.ext.datasource.client.DatasourceManager;
import com.codenvy.ide.ext.datasource.client.DatasourceUiResources;
import com.codenvy.ide.ext.datasource.client.common.AlignableColumnHeader;
import com.codenvy.ide.ext.datasource.client.common.ReadableContentTextEditor;
import com.codenvy.ide.ext.datasource.client.common.TextEditorPartAdapter;
import com.codenvy.ide.ext.datasource.client.events.DatasourceListChangeEvent;
import com.codenvy.ide.ext.datasource.client.events.DatasourceListChangeHandler;
import com.codenvy.ide.ext.datasource.client.explorer.DatasourceExplorerPartPresenter;
import com.codenvy.ide.ext.datasource.client.service.MetadataNotificationConstants;
import com.codenvy.ide.ext.datasource.client.sqleditor.EditorDatasourceOracle;
import com.codenvy.ide.ext.datasource.client.sqleditor.SqlEditorProvider;
import com.codenvy.ide.ext.datasource.client.sqllauncher.RequestResultHeader.RequestResultDelegate;
import com.codenvy.ide.ext.datasource.shared.DatabaseConfigurationDTO;
import com.codenvy.ide.ext.datasource.shared.DatabaseDTO;
import com.codenvy.ide.ext.datasource.shared.MultipleRequestExecutionMode;
import com.codenvy.ide.ext.datasource.shared.request.ExecutionErrorResultDTO;
import com.codenvy.ide.ext.datasource.shared.request.RequestResultDTO;
import com.codenvy.ide.ext.datasource.shared.request.RequestResultGroupDTO;
import com.codenvy.ide.ext.datasource.shared.request.SelectResultDTO;
import com.codenvy.ide.ext.datasource.shared.request.UpdateResultDTO;
import com.codenvy.ide.rest.AsyncRequestCallback;
import com.codenvy.ide.rest.StringUnmarshaller;
import com.codenvy.ide.util.loging.Log;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.TableCellElement;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.view.client.CellPreviewEvent;
import com.google.gwt.view.client.ListDataProvider;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
public class SqlRequestLauncherPresenter extends TextEditorPartAdapter<ReadableContentTextEditor> implements
SqlRequestLauncherView.ActionDelegate,
DatasourceListChangeHandler,
RequestResultDelegate {
/** Preference property name for default result limit. */
private static final String PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT = "SqlEditor_default_request_limit";
/** Default value for request limit (when no pref is set). */
private static final int DEFAULT_REQUEST_LIMIT = 20;
private static final MultipleRequestExecutionMode DEFAULT_EXECUTION_MODE =
MultipleRequestExecutionMode.STOP_AT_FIRST_ERROR;
/** The matching view. */
private final SqlRequestLauncherView view;
/** The i18n-able constants. */
private final SqlRequestLauncherConstants constants;
private final MetadataNotificationConstants notificationConstants;
/** The DTO factory. */
private final DtoFactory dtoFactory;
private String selectedDatasourceId = null;
private int resultLimit = DEFAULT_REQUEST_LIMIT;
private MultipleRequestExecutionMode executionMode = DEFAULT_EXECUTION_MODE;
private final DatasourceClientService datasourceClientService;
private final NotificationManager notificationManager;
private final DatasourceManager datasourceManager;
private final DatabaseInfoStore databaseInfoStore;
private final EditorDatasourceOracle editorDatasourceOracle;
private final CellTableResourcesQueryResults cellTableResources;
private final DatasourceUiResources datasourceUiResources;
@Inject
public SqlRequestLauncherPresenter(final @NotNull SqlRequestLauncherView view,
final @NotNull SqlRequestLauncherConstants constants,
final @NotNull MetadataNotificationConstants notificationConstants,
final @NotNull PreferencesManager preferencesManager,
final @NotNull SqlEditorProvider sqlEditorProvider,
final @NotNull DatasourceClientService service,
final @NotNull DatabaseInfoStore databaseInfoStore,
final @NotNull NotificationManager notificationManager,
final @NotNull DatasourceManager datasourceManager,
final @NotNull EditorDatasourceOracle editorDatasourceOracle,
final @NotNull EventBus eventBus,
final @NotNull DtoFactory dtoFactory,
final @NotNull WorkspaceAgent workspaceAgent,
final @NotNull CellTableResourcesQueryResults cellTableResources,
final @NotNull DatasourceUiResources datasourceUiResources) {
super(sqlEditorProvider.getEditor(), workspaceAgent, eventBus);
this.databaseInfoStore = databaseInfoStore;
this.editorDatasourceOracle = editorDatasourceOracle;
Log.info(SqlRequestLauncherPresenter.class, "New instance of SQL request launcher presenter resquested.");
this.view = view;
this.view.setDelegate(this);
this.constants = constants;
this.notificationConstants = notificationConstants;
this.dtoFactory = dtoFactory;
this.datasourceClientService = service;
this.notificationManager = notificationManager;
this.datasourceManager = datasourceManager;
this.cellTableResources = cellTableResources;
this.datasourceUiResources = datasourceUiResources;
setupResultLimit(preferencesManager);
setupExecutionMode(preferencesManager);
// register for datasource creation events
eventBus.addHandler(DatasourceListChangeEvent.getType(), this);
}
private void setupResultLimit(final PreferencesManager preferencesManager) {
final String prefRequestLimit = preferencesManager.getValue(PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT);
if (prefRequestLimit != null) {
try {
int prefValue = Integer.valueOf(prefRequestLimit);
if (prefValue > 0) {
this.resultLimit = prefValue;
} else {
Log.warn(SqlRequestLauncherPresenter.class, "negative value stored in preference "
+ PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT);
}
} catch (final NumberFormatException e) {
StringBuilder sb = new StringBuilder("Preference stored in ")
.append(PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT)
.append(" is not an integer (")
.append(resultLimit)
.append(").");
Log.warn(SqlRequestLauncherPresenter.class, sb.toString());
}
}
// push the request limit value to the view
this.view.setResultLimit(this.resultLimit);
}
private void setupExecutionMode(final PreferencesManager preferencesManager) {
// TODO : try to read preferences
this.view.setExecutionMode(this.executionMode);
}
private void setupDatasourceComponent() {
Collection<String> datasourceIds = this.datasourceManager.getNames();
this.view.setDatasourceList(datasourceIds);
}
@Override
public void go(final AcceptsOneWidget container) {
container.setWidget(view);
getEditor().go(this.view.getEditorZone());
setupDatasourceComponent();
}
@Override
public void datasourceChanged(final String dataSourceId) {
String tempDataSourceId = dataSourceId; // we need newDataSourceId to be final so we must use a temp var here
if (dataSourceId == null || dataSourceId.isEmpty()) {
tempDataSourceId = null;
}
final String newDataSourceId = tempDataSourceId;
Log.info(SqlRequestLauncherPresenter.class, "Datasource changed to " + newDataSourceId);
this.selectedDatasourceId = newDataSourceId;
String editorFileId = getEditorInput().getFile().getId();
Log.info(SqlRequestLauncherPresenter.class, "Associating editor file id " + editorFileId + " to datasource " + newDataSourceId);
editorDatasourceOracle.setSelectedDatasourceId(editorFileId, newDataSourceId);
if (newDataSourceId == null) {
return;
}
DatabaseDTO dsMeta = databaseInfoStore.getDatabaseInfo(newDataSourceId);
if (dsMeta == null) {
try {
final Notification fetchDatabaseNotification = new Notification(notificationConstants.notificationFetchStart(),
Notification.Status.PROGRESS);
notificationManager.showNotification(fetchDatabaseNotification);
datasourceClientService.fetchDatabaseInfo(datasourceManager.getByName(newDataSourceId),
new AsyncRequestCallback<String>(new StringUnmarshaller()) {
@Override
protected void onSuccess(String result) {
DatabaseDTO database = dtoFactory.createDtoFromJson(result,
DatabaseDTO.class);
fetchDatabaseNotification.setMessage(notificationConstants.notificationFetchSuccess());
fetchDatabaseNotification.setStatus(Notification.Status.FINISHED);
notificationManager.showNotification(fetchDatabaseNotification);
databaseInfoStore.setDatabaseInfo(newDataSourceId, database);
}
@Override
protected void onFailure(Throwable exception) {
fetchDatabaseNotification.setStatus(Notification.Status.FINISHED);
notificationManager.showNotification(new Notification(
notificationConstants.notificationFetchFailure(),
Type.ERROR));
}
}
);
} catch (RequestException e) {
Log.error(DatasourceExplorerPartPresenter.class,
"Exception on database info fetch : " + e.getMessage());
notificationManager.showNotification(new Notification(notificationConstants.notificationFetchFailure(),
Type.ERROR));
}
}
}
@Override
public void resultLimitChanged(final String newResultLimitString) {
Log.info(SqlRequestLauncherPresenter.class, "Attempt to change result limit to " + newResultLimitString);
int resultLimitValue;
try {
resultLimitValue = Integer.parseInt(newResultLimitString);
if (resultLimit < 0) {
Log.debug(SqlRequestLauncherPresenter.class, " new value for result limit is negative - abort change");
this.view.setResultLimit(this.resultLimit);
} else {
Log.debug(SqlRequestLauncherPresenter.class, " valid value for result limit - changed");
this.resultLimit = resultLimitValue;
}
} catch (NumberFormatException e) {
Log.debug(SqlRequestLauncherPresenter.class, " new value for result limit is not a number - abort change");
this.view.setResultLimit(this.resultLimit);
}
}
private String getSqlRequestInput() {
final String selection = getSelectedText();
if (selection == null || "".equals(selection.trim())) {
final String content = getEditorContent();
return content;
} else {
return selection;
}
}
/**
* Return the selected content of the editor zone.
*
* @return the selected content
*/
private String getSelectedText() {
return getEditor().getSelectedContent();
}
/**
* Return the whole content of the editor zone.
*
* @return the content of the editor
*/
private String getEditorContent() {
return getEditor().getEditorContent();
}
@Override
public void executeRequested() {
Log.info(SqlRequestLauncherPresenter.class, "Execution requested.");
if (this.selectedDatasourceId == null) {
Window.alert("No datasource selected");
return;
}
if (this.executionMode == null) {
Window.alert("No execute mode selected");
return;
}
DatabaseConfigurationDTO databaseConf = this.datasourceManager.getByName(this.selectedDatasourceId);
String rawSql = getSqlRequestInput();
if (rawSql != null) {
rawSql = rawSql.trim();
if (!"".equals(rawSql)) {
try {
final Notification requestNotification = new Notification("Executing SQL request...",
Notification.Status.PROGRESS);
final Long startRequestTime = System.currentTimeMillis();
AsyncRequestCallback<String> callback = new AsyncRequestCallback<String>(new StringUnmarshaller()) {
@Override
protected void onSuccess(final String result) {
final Long endRequestTime = System.currentTimeMillis();
final Long requestDuration = endRequestTime - startRequestTime;
Log.info(SqlRequestLauncherPresenter.class, "SQL request result received (" + requestDuration + " ms)");
requestNotification.setMessage("SQL request execution completed");
requestNotification.setStatus(Notification.Status.FINISHED);
final RequestResultGroupDTO resultDto = dtoFactory.createDtoFromJson(result,
RequestResultGroupDTO.class);
// Log.info(SqlRequestLauncherPresenter.class, "JSON->dto conversion OK - result :" + resultDto);
final Long startDisplayTime = System.currentTimeMillis();
updateResultDisplay(resultDto);
final Long endDisplayTime = System.currentTimeMillis();
final Long displayDuration = endDisplayTime - startDisplayTime;
Log.info(SqlRequestLauncherPresenter.class, "Build display for SQL request result(" + displayDuration + " ms)");
}
@Override
protected void onFailure(final Throwable exception) {
Log.info(SqlRequestLauncherPresenter.class, "SQL request failure " + exception.getMessage());
GWT.log("Full exception :", exception);
requestNotification.setStatus(Notification.Status.FINISHED);
notificationManager.showNotification(new Notification("SQL request failed",
Type.ERROR));
updateResultDisplay(exception.getMessage());
}
};
notificationManager.showNotification(requestNotification);
datasourceClientService.executeSqlRequest(databaseConf,
this.resultLimit,
rawSql,
this.executionMode,
callback);
} catch (final RequestException e) {
Log.error(SqlRequestLauncherPresenter.class,
"Exception on SQL request execution : " + e.getMessage());
notificationManager.showNotification(new Notification("Failed execution of SQL request",
Type.ERROR));
}
} else {
Window.alert("No SQL request");
}
} else {
Window.alert("No SQL request");
}
}
protected void updateResultDisplay(final String message) {
Log.info(SqlRequestLauncherPresenter.class, "Printing request error message.");
Label messageLabel = new Label(message);
this.view.appendResult(messageLabel);
}
/**
* Update the result zone to display the last SQL execution result.
*
* @param resultDto the result data
*/
protected void updateResultDisplay(final RequestResultGroupDTO resultDto) {
Log.info(SqlRequestLauncherPresenter.class,
"Printing request results. (" + resultDto.getResults().size() + " individual results).");
this.view.clearResultZone();
for (final RequestResultDTO result : resultDto.getResults()) {
switch (result.getResultType()) {
case UpdateResultDTO.TYPE:
Log.info(SqlRequestLauncherPresenter.class, "Found one result of type 'update'.");
appendUpdateResult(result);
break;
case SelectResultDTO.TYPE:
Log.info(SqlRequestLauncherPresenter.class, "Found one result of type 'select'.");
appendSelectResult(result);
break;
case ExecutionErrorResultDTO.TYPE:
Log.info(SqlRequestLauncherPresenter.class, "Found one result of type 'error'.");
appendErrorReport(result);
break;
default:
Log.error(SqlRequestLauncherPresenter.class, "unknown result type : "
+ result.getResultType());
this.view.appendResult(new Label("Result can't be displayed"));
}
}
Log.info(SqlRequestLauncherPresenter.class, "All individual results are processed.");
}
/**
* Append a result for an failed request to the result zone.
*
* @param result the result data
*/
private void appendErrorReport(final RequestResultDTO result) {
final RequestResultHeader infoHeader = buildErrorHeader(result.getOriginRequest());
this.view.appendResult(infoHeader, new Label(Integer.toString(result.getSqlExecutionError().getErrorCode())
+ " - "
+ result.getSqlExecutionError().getErrorMessage()));
}
/**
* Append a result for an select request to the result zone.
*
* @param result the result data
*/
private void appendSelectResult(final RequestResultDTO result) {
final CellTable<List<String>> resultTable = new CellTable<List<String>>(result.getResultLines().size(), cellTableResources);
final RequestResultHeader infoHeader = buildResultHeader(result, constants.exportCsvLabel());
int i = 0;
for (final String headerEntry : result.getHeaderLine()) {
resultTable.addColumn(new FixedIndexTextColumn(i, ALIGN_LEFT),
new AlignableColumnHeader(headerEntry, ALIGN_LEFT));
i++;
}
resultTable.addCellPreviewHandler(new CellPreviewEvent.Handler<List<String>>() {
@Override
public void onCellPreview(CellPreviewEvent<List<String>> event) {
if ("click".equals(event.getNativeEvent().getType())) {
TableCellElement cellElement = resultTable.getRowElement(event.getIndex()).getCells().getItem(event.getColumn());
cellElement.setTitle(cellElement.getInnerText());
}
}
});
new ListDataProvider<List<String>>(result.getResultLines()).addDataDisplay(resultTable);
this.view.appendResult(infoHeader, resultTable);
}
/**
* Append a result for an update request to the result zone.
*
* @param result the result data
*/
private void appendUpdateResult(final RequestResultDTO result) {
final RequestResultHeader infoHeader = buildResultHeader(result, null);
this.view.appendResult(infoHeader, new Label(this.constants.updateCountMessage(result.getUpdateCount())));
}
/**
* Creates a result header for SQL requests result that succeeded.
*
* @param originRequest the SQL request
* @return a result header
*/
private RequestResultHeader buildResultHeader(final RequestResultDTO requestResult, final String text) {
final RequestResultHeader result = new RequestResultHeader(this.datasourceUiResources.datasourceUiCSS(), this);
result.setInfoHeaderTitle(constants.queryResultsTitle());
result.setRequestReminder(requestResult.getOriginRequest());
if (text != null) {
result.withExportButton(requestResult, text);
}
return result.prepare();
}
/**
* Creates a result header for SQL requests result that failed.
*
* @param originRequest the SQL request
* @return a result header
*/
private RequestResultHeader buildErrorHeader(final String originRequest) {
final RequestResultHeader result = new RequestResultHeader(this.datasourceUiResources.datasourceUiCSS(), this);
result.setInfoHeaderTitle(constants.queryErrorTitle());
result.setRequestReminder(originRequest);
return result.prepare();
}
@Override
public void onDatasourceListChange(final DatasourceListChangeEvent event) {
this.setupDatasourceComponent();
}
@Override
public void executionModeChanged(final MultipleRequestExecutionMode mode) {
this.executionMode = mode;
}
@Override
public boolean onClose() {
boolean parentResult = super.onClose();
final String editorFileId = getEditorInput().getFile().getId();
this.editorDatasourceOracle.forgetEditor(editorFileId);
return parentResult;
}
@Override
public void triggerCsvExport(final RequestResultDTO requestResult, final RequestResultHeader origin) {
final Notification requestNotification = new Notification("Generating CSV export of results...",
Notification.Status.PROGRESS);
this.notificationManager.showNotification(requestNotification);
try {
this.datasourceClientService.exportAsCsv(requestResult, new AsyncRequestCallback<String>(new StringUnmarshaller()) {
@Override
protected void onSuccess(final String result) {
Log.info(SqlRequestLauncherPresenter.class, "CSV export : success.");
requestNotification.setStatus(Notification.Status.FINISHED);
notificationManager.showNotification(new Notification("CSV export : success", Type.INFO));
origin.showCsvLink(result);
}
@Override
protected void onFailure(final Throwable e) {
Log.error(SqlRequestLauncherPresenter.class, "Exception on CSV export : " + e.getMessage());
notificationManager.showNotification(new Notification("CSV export failure", Type.ERROR));
}
});
} catch (RequestException e) {
Log.error(SqlRequestLauncherPresenter.class, "Exception on CSV export : " + e.getMessage());
this.notificationManager.showNotification(new Notification("CSV export failure", Type.ERROR));
}
}
}
|
Add json conversion time log for sql execution
|
codenvy-ext-datasource-client/src/main/java/com/codenvy/ide/ext/datasource/client/sqllauncher/SqlRequestLauncherPresenter.java
|
Add json conversion time log for sql execution
|
|
Java
|
mpl-2.0
|
1a9e9896b45a3e25839622c025b0c92e34e44091
| 0
|
carlwilson/veraPDF-library
|
package org.verapdf.gui.tools;
/**
* @author Evgeniy Muravitskiy
*/
public enum ProcessingType {
VALIDATING(GUIConstants.VALIDATING),
FEATURES(GUIConstants.FEATURES),
VALIDATING_AND_FEATURES(GUIConstants.VALIDATING_AND_FEATURES);
private final String value;
ProcessingType(String value) {
this.value = value;
}
public boolean isValidating() {
return this == VALIDATING || this == VALIDATING_AND_FEATURES;
}
public boolean isFeatures() {
return this == FEATURES || this == VALIDATING_AND_FEATURES;
}
@Override
public String toString() {
return this.value;
}
}
|
gui/src/main/java/org/verapdf/gui/tools/ProcessingType.java
|
package org.verapdf.gui.tools;
/**
* @author Evgeniy Muravitskiy
*/
public enum ProcessingType {
VALIDATING("Validation"),
FEATURES("Features"),
VALIDATING_AND_FEATURES("Validation & Features");
private final String value;
ProcessingType(String value) {
this.value = value;
}
public boolean isValidating() {
return this == VALIDATING || this == VALIDATING_AND_FEATURES;
}
public boolean isFeatures() {
return this == FEATURES || this == VALIDATING_AND_FEATURES;
}
@Override
public String toString() {
return this.value;
}
}
|
Use constants in processing type
|
gui/src/main/java/org/verapdf/gui/tools/ProcessingType.java
|
Use constants in processing type
|
|
Java
|
agpl-3.0
|
e7b9f9227bb9acf800a5970fb3f079731512954c
| 0
|
EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform
|
package im.actor.sdk.controllers.auth;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.MenuItem;
import im.actor.core.AuthState;
import im.actor.core.entity.AuthCodeRes;
import im.actor.core.entity.AuthRes;
import im.actor.core.entity.AuthStartRes;
import im.actor.core.entity.Sex;
import im.actor.core.network.RpcException;
import im.actor.core.network.RpcInternalException;
import im.actor.core.network.RpcTimeoutException;
import im.actor.runtime.actors.Actor;
import im.actor.runtime.actors.ActorCreator;
import im.actor.runtime.actors.ActorRef;
import im.actor.runtime.actors.ActorSystem;
import im.actor.runtime.actors.Props;
import im.actor.runtime.function.Consumer;
import im.actor.runtime.promise.Promise;
import im.actor.runtime.storage.PreferencesStorage;
import im.actor.sdk.ActorSDK;
import im.actor.sdk.R;
import im.actor.sdk.controllers.activity.ActorMainActivity;
import im.actor.sdk.controllers.activity.BaseFragmentActivity;
import static im.actor.sdk.util.ActorSDKMessenger.messenger;
public class AuthActivity extends BaseFragmentActivity {
public static final String AUTH_TYPE_KEY = "auth_type";
public static final String SIGN_TYPE_KEY = "sign_type";
public static final int AUTH_TYPE_PHONE = 1;
public static final int AUTH_TYPE_EMAIL = 2;
public static final int SIGN_TYPE_IN = 3;
public static final int SIGN_TYPE_UP = 4;
private static final int OAUTH_DIALOG = 1;
private ProgressDialog progressDialog;
private AlertDialog alertDialog;
private AuthState state;
private int availableAuthType = AUTH_TYPE_PHONE;
private int currentAuthType = AUTH_TYPE_PHONE;
private int signType;
private long currentPhone;
private String currentEmail;
private String transactionHash;
private String currentCode;
private boolean isRegistered = false;
private String currentName;
private Sex currentSex;
private ActorRef authActor;
private boolean codeValidated = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
authActor = ActorSystem.system().actorOf(Props.create(new ActorCreator() {
@Override
public Actor create() {
return new Actor();
}
}), "actor/auth_promises_actor");
signType = getIntent().getIntExtra(SIGN_TYPE_KEY, SIGN_TYPE_IN);
PreferencesStorage preferences = messenger().getPreferences();
currentPhone = preferences.getLong("currentPhone", 0);
currentEmail = preferences.getString("currentEmail");
transactionHash = preferences.getString("transactionHash");
isRegistered = preferences.getBool("isRegistered", false);
codeValidated = preferences.getBool("codeValidated", false);
currentName = preferences.getString("currentName");
signType = preferences.getInt("signType", signType);
String savedState = preferences.getString("auth_state");
state = Enum.valueOf(AuthState.class, savedState != null ? savedState : "AUTH_START");
updateState(state, true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
}
return super.onOptionsItemSelected(item);
}
private void updateState(AuthState state) {
updateState(state, false);
}
private void updateState(AuthState state, boolean force) {
if (this.state != null && (this.state == state && !force)) {
return;
}
PreferencesStorage preferences = messenger().getPreferences();
preferences.putLong("currentPhone", currentPhone);
preferences.putString("currentEmail", currentEmail);
preferences.putString("transactionHash", transactionHash);
preferences.putBool("isRegistered", isRegistered);
preferences.putBool("codeValidated", codeValidated);
preferences.putString("currentName", currentName);
preferences.putInt("signType", signType);
preferences.putString("auth_state", state.toString());
// if we show the next fragment when app is in background and not visible , app crashes!
// e.g when the GSM data is off and after trying to send code we go to settings to turn on, app is going invisible and ...
if (state != AuthState.LOGGED_IN && getIsResumed() == false) {
return;
}
this.state = state;
switch (state) {
case AUTH_START:
if (signType == SIGN_TYPE_UP) {
updateState(AuthState.SIGN_UP);
} else if (signType == SIGN_TYPE_IN) {
showFragment(new SignInFragment(), false, false);
}
break;
case SIGN_UP:
if (currentName != null && !currentName.isEmpty()) {
startAuth(currentName);
} else {
showFragment(new SignUpFragment(), false, false);
}
break;
case AUTH_PHONE:
currentAuthType = AUTH_TYPE_PHONE;
currentCode = "";
showFragment(ActorSDK.sharedActor().getDelegatedFragment(ActorSDK.sharedActor().getDelegate().getAuthStartIntent(), new SignPhoneFragment(), BaseAuthFragment.class), false, false);
break;
case AUTH_EMAIL:
currentCode = "";
currentAuthType = AUTH_TYPE_EMAIL;
showFragment(ActorSDK.sharedActor().getDelegatedFragment(ActorSDK.sharedActor().getDelegate().getAuthStartIntent(), new SignEmailFragment(), BaseAuthFragment.class), false, false);
break;
case CODE_VALIDATION_PHONE:
case CODE_VALIDATION_EMAIL:
Fragment signInFragment = new ValidateCodeFragment();
Bundle args = new Bundle();
args.putString("authType", state == AuthState.CODE_VALIDATION_EMAIL ? ValidateCodeFragment.AUTH_TYPE_EMAIL : ValidateCodeFragment.AUTH_TYPE_PHONE);
args.putBoolean(ValidateCodeFragment.AUTH_TYPE_SIGN, signType == SIGN_TYPE_IN);
args.putString("authId", state == AuthState.CODE_VALIDATION_EMAIL ? currentEmail : Long.toString(currentPhone));
signInFragment.setArguments(args);
showFragment(signInFragment, false, false);
break;
case LOGGED_IN:
finish();
startActivity(new Intent(this, ActorMainActivity.class));
break;
}
}
public void startAuth(String name) {
currentName = name;
currentSex = Sex.UNKNOWN;
availableAuthType = ActorSDK.sharedActor().getAuthType();
AuthState authState;
if (!codeValidated) {
if ((availableAuthType & AUTH_TYPE_PHONE) == AUTH_TYPE_PHONE) {
authState = AuthState.AUTH_PHONE;
} else if ((availableAuthType & AUTH_TYPE_EMAIL) == AUTH_TYPE_EMAIL) {
authState = AuthState.AUTH_EMAIL;
} else {
// none of valid auth types selected - force crash?
return;
}
updateState(authState);
} else {
signUp(messenger().doSignup(currentName, currentSex != null ? currentSex : Sex.UNKNOWN, transactionHash), currentName, currentSex);
}
}
public void startPhoneAuth(Promise<AuthStartRes> promise, long phone) {
currentAuthType = AUTH_TYPE_PHONE;
currentPhone = phone;
startAuth(promise);
}
public void startEmailAuth(Promise<AuthStartRes> promise, String email) {
currentAuthType = AUTH_TYPE_EMAIL;
currentEmail = email;
startAuth(promise);
}
private void startAuth(Promise<AuthStartRes> res) {
showProgress();
res.then(new Consumer<AuthStartRes>() {
@Override
public void apply(AuthStartRes authStartRes) {
if (dismissProgress()) {
transactionHash = authStartRes.getTransactionHash();
isRegistered = authStartRes.isRegistered();
switch (authStartRes.getAuthMode()) {
case OTP:
switch (currentAuthType) {
case AUTH_TYPE_PHONE:
updateState(AuthState.CODE_VALIDATION_PHONE);
break;
case AUTH_TYPE_EMAIL:
updateState(AuthState.CODE_VALIDATION_EMAIL);
break;
}
break;
default:
//not supported AuthMode - force crash?
}
}
}
}).failure(new Consumer<Exception>() {
@Override
public void apply(Exception e) {
handleAuthError(e);
}
});
}
public void validateCode(Promise<AuthCodeRes> promise, String code) {
currentCode = code;
showProgress();
promise.then(new Consumer<AuthCodeRes>() {
@Override
public void apply(AuthCodeRes authCodeRes) {
if (dismissProgress()) {
codeValidated = true;
transactionHash = authCodeRes.getTransactionHash();
if (!authCodeRes.isNeedToSignup()) {
messenger().doCompleteAuth(authCodeRes.getResult()).then(new Consumer<Boolean>() {
@Override
public void apply(Boolean aBoolean) {
updateState(AuthState.LOGGED_IN);
}
}).failure(new Consumer<Exception>() {
@Override
public void apply(Exception e) {
handleAuthError(e);
}
});
} else {
if (currentName == null || currentName.isEmpty()) {
updateState(AuthState.SIGN_UP, true);
} else {
signUp(messenger().doSignup(currentName, currentSex != null ? currentSex : Sex.UNKNOWN, transactionHash), currentName, currentSex);
}
}
}
}
}).failure(new Consumer<Exception>() {
@Override
public void apply(Exception e) {
handleAuthError(e);
}
});
}
public void signUp(Promise<AuthRes> promise, String name, Sex sex) {
currentName = name;
currentSex = sex;
promise.then(new Consumer<AuthRes>() {
@Override
public void apply(AuthRes authRes) {
dismissProgress();
messenger().doCompleteAuth(authRes).then(new Consumer<Boolean>() {
@Override
public void apply(Boolean aBoolean) {
updateState(AuthState.LOGGED_IN);
}
}).failure(new Consumer<Exception>() {
@Override
public void apply(Exception e) {
handleAuthError(e);
}
});
}
}).failure(new Consumer<Exception>() {
@Override
public void apply(Exception e) {
handleAuthError(e);
}
});
}
public void handleAuthError(final Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (dismissProgress()) {
boolean canTryAgain = false;
boolean keepState = false;
String message = getString(R.string.error_unknown);
String tag = "UNKNOWN";
if (e instanceof RpcException) {
RpcException re = (RpcException) e;
if (re instanceof RpcInternalException) {
message = getString(R.string.error_unknown);
canTryAgain = true;
} else if (re instanceof RpcTimeoutException) {
message = getString(R.string.error_connection);
canTryAgain = true;
} else {
if ("PHONE_CODE_EXPIRED".equals(re.getTag()) || "EMAIL_CODE_EXPIRED".equals(re.getTag())) {
currentCode = "";
message = getString(R.string.auth_error_code_expired);
canTryAgain = false;
} else if ("PHONE_CODE_INVALID".equals(re.getTag()) || "EMAIL_CODE_INVALID".equals(re.getTag())) {
message = getString(R.string.auth_error_code_invalid);
canTryAgain = false;
keepState = true;
} else if ("FAILED_GET_OAUTH2_TOKEN".equals(re.getTag())) {
message = getString(R.string.auth_error_failed_get_oauth2_token);
canTryAgain = false;
} else {
message = re.getMessage();
canTryAgain = re.isCanTryAgain();
}
}
}
try {
if (canTryAgain) {
new AlertDialog.Builder(AuthActivity.this)
.setMessage(message)
.setPositiveButton(R.string.dialog_try_again, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismissAlert();
switch (state) {
case AUTH_EMAIL:
case AUTH_PHONE:
switch (currentAuthType) {
case AUTH_TYPE_PHONE:
startAuth(messenger().doStartPhoneAuth(currentPhone));
break;
case AUTH_TYPE_EMAIL:
startAuth(messenger().doStartEmailAuth(currentEmail));
break;
}
break;
case CODE_VALIDATION_EMAIL:
case CODE_VALIDATION_PHONE:
validateCode(messenger().doValidateCode(currentCode, transactionHash), currentCode);
break;
case SIGN_UP:
signUp(messenger().doSignup(currentName, currentSex!=null?currentSex:Sex.UNKNOWN, transactionHash), currentName, currentSex);
break;
}
}
})
.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismissAlert();
updateState(AuthState.AUTH_START);
}
}).setCancelable(false)
.show()
.setCanceledOnTouchOutside(false);
} else {
final boolean finalKeepState = keepState;
new AlertDialog.Builder(AuthActivity.this)
.setMessage(message)
.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismissAlert();
if (finalKeepState) {
updateState(state, true);
} else if (signType == SIGN_TYPE_UP) {
if (currentAuthType == AUTH_TYPE_EMAIL) {
switchToEmailAuth();
} else if (currentAuthType == AUTH_TYPE_PHONE) {
switchToPhoneAuth();
} else {
updateState(AuthState.AUTH_START);
}
} else if (signType == SIGN_TYPE_IN) {
startSignIn();
} else {
updateState(AuthState.AUTH_START);
}
}
})
.setCancelable(false)
.show()
.setCanceledOnTouchOutside(false);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
}
public void switchToEmailAuth() {
updateState(AuthState.AUTH_EMAIL);
}
public void switchToPhoneAuth() {
updateState(AuthState.AUTH_PHONE);
}
public void startSignIn() {
signType = SIGN_TYPE_IN;
updateState(AuthState.AUTH_START, true);
}
public void startSignUp() {
signType = SIGN_TYPE_UP;
updateState(AuthState.AUTH_START, true);
}
public void showProgress() {
dismissProgress();
progressDialog = new ProgressDialog(this);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.setTitle(getString(R.string.progress_common));
progressDialog.show();
}
@Override
protected void onPause() {
super.onPause();
dismissProgress();
dismissAlert();
}
private boolean dismissProgress() {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
return true;
}
return false;
}
private void dismissAlert() {
if (alertDialog != null) {
alertDialog.dismiss();
alertDialog = null;
}
}
public String getCurrentCode() {
return currentCode;
}
public String getTransactionHash() {
return transactionHash;
}
}
|
actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/controllers/auth/AuthActivity.java
|
package im.actor.sdk.controllers.auth;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.MenuItem;
import im.actor.core.AuthState;
import im.actor.core.entity.AuthCodeRes;
import im.actor.core.entity.AuthRes;
import im.actor.core.entity.AuthStartRes;
import im.actor.core.entity.Sex;
import im.actor.core.network.RpcException;
import im.actor.core.network.RpcInternalException;
import im.actor.core.network.RpcTimeoutException;
import im.actor.runtime.actors.Actor;
import im.actor.runtime.actors.ActorCreator;
import im.actor.runtime.actors.ActorRef;
import im.actor.runtime.actors.ActorSystem;
import im.actor.runtime.actors.Props;
import im.actor.runtime.function.Consumer;
import im.actor.runtime.promise.Promise;
import im.actor.runtime.storage.PreferencesStorage;
import im.actor.sdk.ActorSDK;
import im.actor.sdk.R;
import im.actor.sdk.controllers.activity.ActorMainActivity;
import im.actor.sdk.controllers.activity.BaseFragmentActivity;
import static im.actor.sdk.util.ActorSDKMessenger.messenger;
public class AuthActivity extends BaseFragmentActivity {
public static final String AUTH_TYPE_KEY = "auth_type";
public static final String SIGN_TYPE_KEY = "sign_type";
public static final int AUTH_TYPE_PHONE = 1;
public static final int AUTH_TYPE_EMAIL = 2;
public static final int SIGN_TYPE_IN = 3;
public static final int SIGN_TYPE_UP = 4;
private static final int OAUTH_DIALOG = 1;
private ProgressDialog progressDialog;
private AlertDialog alertDialog;
private AuthState state;
private int availableAuthType = AUTH_TYPE_PHONE;
private int currentAuthType = AUTH_TYPE_PHONE;
private int signType;
private long currentPhone;
private String currentEmail;
private String transactionHash;
private String currentCode;
private boolean isRegistered = false;
private String currentName;
private Sex currentSex;
private ActorRef authActor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
authActor = ActorSystem.system().actorOf(Props.create(new ActorCreator() {
@Override
public Actor create() {
return new Actor();
}
}), "actor/auth_promises_actor");
signType = getIntent().getIntExtra(SIGN_TYPE_KEY, SIGN_TYPE_IN);
PreferencesStorage preferences = messenger().getPreferences();
currentPhone = preferences.getLong("currentPhone", 0);
currentEmail = preferences.getString("currentEmail");
transactionHash = preferences.getString("transactionHash");
isRegistered = preferences.getBool("isRegistered", false);
currentName = preferences.getString("currentName");
signType = preferences.getInt("signType", signType);
String savedState = preferences.getString("auth_state");
state = Enum.valueOf(AuthState.class, savedState != null ? savedState : "AUTH_START");
updateState(state, true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
}
return super.onOptionsItemSelected(item);
}
private void updateState(AuthState state) {
updateState(state, false);
}
private void updateState(AuthState state, boolean force) {
if (this.state != null && (this.state == state && !force)) {
return;
}
PreferencesStorage preferences = messenger().getPreferences();
preferences.putLong("currentPhone", currentPhone);
preferences.putString("currentEmail", currentEmail);
preferences.putString("transactionHash", transactionHash);
preferences.putBool("isRegistered", isRegistered);
preferences.putString("currentName", currentName);
preferences.putInt("signType", signType);
preferences.putString("auth_state", state.toString());
// if we show the next fragment when app is in background and not visible , app crashes!
// e.g when the GSM data is off and after trying to send code we go to settings to turn on, app is going invisible and ...
if (state != AuthState.LOGGED_IN && getIsResumed() == false) {
return;
}
this.state = state;
switch (state) {
case AUTH_START:
if (signType == SIGN_TYPE_UP) {
updateState(AuthState.SIGN_UP);
} else if (signType == SIGN_TYPE_IN) {
showFragment(new SignInFragment(), false, false);
}
break;
case SIGN_UP:
if (currentName != null && !currentName.isEmpty()) {
startAuth(currentName);
} else {
showFragment(new SignUpFragment(), false, false);
}
break;
case AUTH_PHONE:
currentAuthType = AUTH_TYPE_PHONE;
currentCode = "";
showFragment(ActorSDK.sharedActor().getDelegatedFragment(ActorSDK.sharedActor().getDelegate().getAuthStartIntent(), new SignPhoneFragment(), BaseAuthFragment.class), false, false);
break;
case AUTH_EMAIL:
currentCode = "";
currentAuthType = AUTH_TYPE_EMAIL;
showFragment(ActorSDK.sharedActor().getDelegatedFragment(ActorSDK.sharedActor().getDelegate().getAuthStartIntent(), new SignEmailFragment(), BaseAuthFragment.class), false, false);
break;
case CODE_VALIDATION_PHONE:
case CODE_VALIDATION_EMAIL:
Fragment signInFragment = new ValidateCodeFragment();
Bundle args = new Bundle();
args.putString("authType", state == AuthState.CODE_VALIDATION_EMAIL ? ValidateCodeFragment.AUTH_TYPE_EMAIL : ValidateCodeFragment.AUTH_TYPE_PHONE);
args.putBoolean(ValidateCodeFragment.AUTH_TYPE_SIGN, signType == SIGN_TYPE_IN);
args.putString("authId", state == AuthState.CODE_VALIDATION_EMAIL ? currentEmail : Long.toString(currentPhone));
signInFragment.setArguments(args);
showFragment(signInFragment, false, false);
break;
case LOGGED_IN:
finish();
startActivity(new Intent(this, ActorMainActivity.class));
break;
}
}
public void startAuth(String name) {
currentName = name;
currentSex = Sex.UNKNOWN;
availableAuthType = ActorSDK.sharedActor().getAuthType();
AuthState authState;
if ((availableAuthType & AUTH_TYPE_PHONE) == AUTH_TYPE_PHONE) {
authState = AuthState.AUTH_PHONE;
} else if ((availableAuthType & AUTH_TYPE_EMAIL) == AUTH_TYPE_EMAIL) {
authState = AuthState.AUTH_EMAIL;
} else {
// none of valid auth types selected - force crash?
return;
}
updateState(authState);
}
public void startPhoneAuth(Promise<AuthStartRes> promise, long phone) {
currentAuthType = AUTH_TYPE_PHONE;
currentPhone = phone;
startAuth(promise);
}
public void startEmailAuth(Promise<AuthStartRes> promise, String email) {
currentAuthType = AUTH_TYPE_EMAIL;
currentEmail = email;
startAuth(promise);
}
private void startAuth(Promise<AuthStartRes> res) {
showProgress();
res.then(new Consumer<AuthStartRes>() {
@Override
public void apply(AuthStartRes authStartRes) {
if (dismissProgress()) {
transactionHash = authStartRes.getTransactionHash();
isRegistered = authStartRes.isRegistered();
switch (authStartRes.getAuthMode()) {
case OTP:
switch (currentAuthType) {
case AUTH_TYPE_PHONE:
updateState(AuthState.CODE_VALIDATION_PHONE);
break;
case AUTH_TYPE_EMAIL:
updateState(AuthState.CODE_VALIDATION_EMAIL);
break;
}
break;
default:
//not supported AuthMode - force crash?
}
}
}
}).failure(new Consumer<Exception>() {
@Override
public void apply(Exception e) {
handleAuthError(e);
}
});
}
public void validateCode(Promise<AuthCodeRes> promise, String code) {
currentCode = code;
showProgress();
promise.then(new Consumer<AuthCodeRes>() {
@Override
public void apply(AuthCodeRes authCodeRes) {
if (dismissProgress()) {
transactionHash = authCodeRes.getTransactionHash();
if (!authCodeRes.isNeedToSignup()) {
messenger().doCompleteAuth(authCodeRes.getResult()).then(new Consumer<Boolean>() {
@Override
public void apply(Boolean aBoolean) {
updateState(AuthState.LOGGED_IN);
}
}).failure(new Consumer<Exception>() {
@Override
public void apply(Exception e) {
handleAuthError(e);
}
});
} else {
signUp(messenger().doSignup(currentName, currentSex!=null?currentSex:Sex.UNKNOWN, transactionHash), currentName, currentSex);
}
}
}
}).failure(new Consumer<Exception>() {
@Override
public void apply(Exception e) {
handleAuthError(e);
}
});
}
public void signUp(Promise<AuthRes> promise, String name, Sex sex) {
currentName = name;
currentSex = sex;
promise.then(new Consumer<AuthRes>() {
@Override
public void apply(AuthRes authRes) {
dismissProgress();
messenger().doCompleteAuth(authRes).then(new Consumer<Boolean>() {
@Override
public void apply(Boolean aBoolean) {
updateState(AuthState.LOGGED_IN);
}
}).failure(new Consumer<Exception>() {
@Override
public void apply(Exception e) {
handleAuthError(e);
}
});
}
}).failure(new Consumer<Exception>() {
@Override
public void apply(Exception e) {
handleAuthError(e);
}
});
}
public void handleAuthError(final Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (dismissProgress()) {
boolean canTryAgain = false;
boolean keepState = false;
String message = getString(R.string.error_unknown);
String tag = "UNKNOWN";
if (e instanceof RpcException) {
RpcException re = (RpcException) e;
if (re instanceof RpcInternalException) {
message = getString(R.string.error_unknown);
canTryAgain = true;
} else if (re instanceof RpcTimeoutException) {
message = getString(R.string.error_connection);
canTryAgain = true;
} else {
if ("PHONE_CODE_EXPIRED".equals(re.getTag()) || "EMAIL_CODE_EXPIRED".equals(re.getTag())) {
currentCode = "";
message = getString(R.string.auth_error_code_expired);
canTryAgain = false;
} else if ("PHONE_CODE_INVALID".equals(re.getTag()) || "EMAIL_CODE_INVALID".equals(re.getTag())) {
message = getString(R.string.auth_error_code_invalid);
canTryAgain = false;
keepState = true;
} else if ("FAILED_GET_OAUTH2_TOKEN".equals(re.getTag())) {
message = getString(R.string.auth_error_failed_get_oauth2_token);
canTryAgain = false;
} else {
message = re.getMessage();
canTryAgain = re.isCanTryAgain();
}
}
}
try {
if (canTryAgain) {
new AlertDialog.Builder(AuthActivity.this)
.setMessage(message)
.setPositiveButton(R.string.dialog_try_again, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismissAlert();
switch (state) {
case AUTH_EMAIL:
case AUTH_PHONE:
switch (currentAuthType) {
case AUTH_TYPE_PHONE:
startAuth(messenger().doStartPhoneAuth(currentPhone));
break;
case AUTH_TYPE_EMAIL:
startAuth(messenger().doStartEmailAuth(currentEmail));
break;
}
break;
case CODE_VALIDATION_EMAIL:
case CODE_VALIDATION_PHONE:
validateCode(messenger().doValidateCode(currentCode, transactionHash), currentCode);
break;
case SIGN_UP:
signUp(messenger().doSignup(currentName, currentSex!=null?currentSex:Sex.UNKNOWN, transactionHash), currentName, currentSex);
break;
}
}
})
.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismissAlert();
updateState(AuthState.AUTH_START);
}
}).setCancelable(false)
.show()
.setCanceledOnTouchOutside(false);
} else {
final boolean finalKeepState = keepState;
new AlertDialog.Builder(AuthActivity.this)
.setMessage(message)
.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismissAlert();
if (finalKeepState) {
updateState(state, true);
} else if (signType == SIGN_TYPE_UP) {
if (currentAuthType == AUTH_TYPE_EMAIL) {
switchToEmailAuth();
} else if (currentAuthType == AUTH_TYPE_PHONE) {
switchToPhoneAuth();
} else {
updateState(AuthState.AUTH_START);
}
} else if (signType == SIGN_TYPE_IN) {
startSignIn();
} else {
updateState(AuthState.AUTH_START);
}
}
})
.setCancelable(false)
.show()
.setCanceledOnTouchOutside(false);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
}
public void switchToEmailAuth() {
updateState(AuthState.AUTH_EMAIL);
}
public void switchToPhoneAuth() {
updateState(AuthState.AUTH_PHONE);
}
public void startSignIn() {
signType = SIGN_TYPE_IN;
updateState(AuthState.AUTH_START, true);
}
public void startSignUp() {
signType = SIGN_TYPE_UP;
updateState(AuthState.AUTH_START, true);
}
public void showProgress() {
dismissProgress();
progressDialog = new ProgressDialog(this);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.setTitle(getString(R.string.progress_common));
progressDialog.show();
}
@Override
protected void onPause() {
super.onPause();
dismissProgress();
dismissAlert();
}
private boolean dismissProgress() {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
return true;
}
return false;
}
private void dismissAlert() {
if (alertDialog != null) {
alertDialog.dismiss();
alertDialog = null;
}
}
public String getCurrentCode() {
return currentCode;
}
public String getTransactionHash() {
return transactionHash;
}
}
|
fix(android): send to sign up from sign in if not registered
|
actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/controllers/auth/AuthActivity.java
|
fix(android): send to sign up from sign in if not registered
|
|
Java
|
lgpl-2.1
|
341f854c4cf23d5a57ac20d0f7bc2090fe6ffe67
| 0
|
zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform
|
package org.zanata.rest;
import java.io.IOException;
import java.util.Collection;
import javax.ws.rs.core.Response.Status;
import lombok.extern.slf4j.Slf4j;
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.core.SynchronousDispatcher;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.UnhandledException;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Install;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Observer;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import org.jboss.seam.deployment.AnnotationDeploymentHandler;
import org.jboss.seam.deployment.HotDeploymentStrategy;
import org.jboss.seam.resteasy.ResteasyBootstrap;
import org.jboss.seam.resteasy.SeamResteasyProviderFactory;
@Name("org.jboss.seam.resteasy.bootstrap")
@Scope(ScopeType.APPLICATION)
@Startup
@AutoCreate
@Install(classDependencies = "org.jboss.resteasy.spi.ResteasyProviderFactory",
precedence = Install.DEPLOYMENT)
@Slf4j
public class ZanataResteasyBootstrap extends ResteasyBootstrap {
@Observer("org.jboss.seam.postReInitialization")
public void registerHotDeployedClasses() {
Collection<Component> seamComponents = findSeamComponents();
// Also scan for hot deployed components
HotDeploymentStrategy hotDeployment = HotDeploymentStrategy.instance();
if (hotDeployment != null && hotDeployment.available()) {
log.info("scanning for hot deployable JAX-RS components");
AnnotationDeploymentHandler hotDeploymentHandler =
(AnnotationDeploymentHandler) hotDeployment
.getDeploymentHandlers().get(
AnnotationDeploymentHandler.NAME);
registerProviders(seamComponents,
findProviders(hotDeploymentHandler));
registerResources(seamComponents,
findResources(hotDeploymentHandler));
}
}
@Override
protected void initDispatcher() {
super.initDispatcher();
getDispatcher().getProviderFactory()
.getServerPreProcessInterceptorRegistry()
.register(ZanataRestSecurityInterceptor.class);
getDispatcher().getProviderFactory()
.getServerPreProcessInterceptorRegistry()
.register(ZanataRestVersionInterceptor.class);
}
@Override
protected Dispatcher createDispatcher(
SeamResteasyProviderFactory providerFactory) {
return new SynchronousDispatcher(providerFactory) {
@Override
public void invoke(HttpRequest request, HttpResponse response) {
try {
super.invoke(request, response);
} catch (UnhandledException e) {
Throwable cause = e.getCause();
log.error("Failed to process REST request", cause);
try {
// see https://issues.jboss.org/browse/RESTEASY-411
if (cause instanceof IllegalArgumentException
&& cause.getMessage().contains(
"Failure parsing MediaType")) {
response.sendError(
Status.UNSUPPORTED_MEDIA_TYPE.getStatusCode(),
cause.getMessage());
} else {
response.sendError(
Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Error processing Request");
}
} catch (IOException ioe) {
log.error(
"Failed to send error on failed REST request",
ioe);
}
}
}
};
}
}
|
zanata-war/src/main/java/org/zanata/rest/ZanataResteasyBootstrap.java
|
package org.zanata.rest;
import java.io.IOException;
import java.util.Collection;
import javax.ws.rs.core.Response.Status;
import lombok.extern.slf4j.Slf4j;
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.core.SynchronousDispatcher;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.UnhandledException;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Install;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Observer;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import org.jboss.seam.deployment.AnnotationDeploymentHandler;
import org.jboss.seam.deployment.HotDeploymentStrategy;
import org.jboss.seam.resteasy.ResteasyBootstrap;
import org.jboss.seam.resteasy.SeamResteasyProviderFactory;
@Name("org.jboss.seam.resteasy.bootstrap")
@Scope(ScopeType.APPLICATION)
@Startup
@AutoCreate
@Install(classDependencies = "org.jboss.resteasy.spi.ResteasyProviderFactory",
precedence = Install.DEPLOYMENT)
@Slf4j
public class ZanataResteasyBootstrap extends ResteasyBootstrap {
@Observer("org.jboss.seam.postReInitialization")
public void registerHotDeployedClasses() {
Collection<Component> seamComponents = findSeamComponents();
// Also scan for hot deployed components
HotDeploymentStrategy hotDeployment = HotDeploymentStrategy.instance();
if (hotDeployment != null && hotDeployment.available()) {
log.info("scanning for hot deployable JAX-RS components");
AnnotationDeploymentHandler hotDeploymentHandler =
(AnnotationDeploymentHandler) hotDeployment
.getDeploymentHandlers().get(
AnnotationDeploymentHandler.NAME);
registerProviders(seamComponents,
findProviders(hotDeploymentHandler));
registerResources(seamComponents,
findResources(hotDeploymentHandler));
}
}
@Override
protected void initDispatcher() {
super.initDispatcher();
getDispatcher().getProviderFactory()
.getServerPreProcessInterceptorRegistry()
.register(ZanataRestSecurityInterceptor.class);
getDispatcher().getProviderFactory()
.getServerPreProcessInterceptorRegistry()
.register(ZanataRestVersionInterceptor.class);
}
@Override
protected Dispatcher createDispatcher(
SeamResteasyProviderFactory providerFactory) {
return new SynchronousDispatcher(providerFactory) {
@Override
public void invoke(HttpRequest request, HttpResponse response) {
try {
super.invoke(request, response);
} catch (UnhandledException e) {
log.error("Failed to process REST request", e.getCause());
try {
response.sendError(
Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Error processing Request");
} catch (IOException ioe) {
log.error(
"Failed to send error on failed REST request",
ioe);
}
}
}
};
}
}
|
rhbz1055790 - user friendlier error message for bad rest request
|
zanata-war/src/main/java/org/zanata/rest/ZanataResteasyBootstrap.java
|
rhbz1055790 - user friendlier error message for bad rest request
|
|
Java
|
lgpl-2.1
|
4b2bdcd22c2cf3df9cb3207a18d652299afbad4b
| 0
|
xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki.store;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.EntityMode;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Settings;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.impl.SessionFactoryImpl;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.slf4j.Logger;
import org.suigeneris.jrcs.rcs.Version;
import org.xwiki.bridge.event.ActionExecutingEvent;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.component.phase.InitializationException;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.DocumentReferenceResolver;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.EntityReferenceSerializer;
import org.xwiki.model.reference.SpaceReference;
import org.xwiki.model.reference.WikiReference;
import org.xwiki.observation.EventListener;
import org.xwiki.observation.ObservationManager;
import org.xwiki.observation.event.Event;
import org.xwiki.query.QueryException;
import org.xwiki.query.QueryManager;
import org.xwiki.store.UnexpectedException;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.doc.XWikiDocument.XWikiAttachmentToRemove;
import com.xpn.xwiki.doc.XWikiLink;
import com.xpn.xwiki.doc.XWikiLock;
import com.xpn.xwiki.doc.XWikiSpace;
import com.xpn.xwiki.internal.render.OldRendering;
import com.xpn.xwiki.monitor.api.MonitorPlugin;
import com.xpn.xwiki.objects.BaseCollection;
import com.xpn.xwiki.objects.BaseElement;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseProperty;
import com.xpn.xwiki.objects.BaseStringProperty;
import com.xpn.xwiki.objects.LargeStringProperty;
import com.xpn.xwiki.objects.ListProperty;
import com.xpn.xwiki.objects.PropertyInterface;
import com.xpn.xwiki.objects.StringProperty;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.objects.classes.PropertyClass;
import com.xpn.xwiki.objects.classes.StringClass;
import com.xpn.xwiki.objects.classes.TextAreaClass;
import com.xpn.xwiki.stats.impl.XWikiStats;
import com.xpn.xwiki.store.migration.MigrationRequiredException;
import com.xpn.xwiki.util.Util;
/**
* The XWiki Hibernate database driver.
*
* @version $Id$
*/
@Component
@Named(XWikiHibernateBaseStore.HINT)
@Singleton
public class XWikiHibernateStore extends XWikiHibernateBaseStore implements XWikiStoreInterface
{
@Inject
private Logger logger;
/**
* QueryManager for this store.
*/
@Inject
private QueryManager queryManager;
/** Needed so we can register an event to trap logout and delete held locks. */
@Inject
private ObservationManager observationManager;
/**
* Used to resolve a string into a proper Document Reference using the current document's reference to fill the
* blanks, except for the page name for which the default page name is used instead and for the wiki name for which
* the current wiki is used instead of the current document reference's wiki.
*/
@Inject
@Named("currentmixed")
private DocumentReferenceResolver<String> currentMixedDocumentReferenceResolver;
@Inject
private DocumentReferenceResolver<String> defaultDocumentReferenceResolver;
/**
* Used to convert a proper Document Reference to string (standard form).
*/
@Inject
private EntityReferenceSerializer<String> defaultEntityReferenceSerializer;
/**
* Used to convert a Document Reference to string (compact form without the wiki part).
*/
@Inject
@Named("compactwiki")
private EntityReferenceSerializer<String> compactWikiEntityReferenceSerializer;
/**
* Used to convert a proper Document Reference to a string but without the wiki name.
*/
@Inject
@Named("local")
private EntityReferenceSerializer<String> localEntityReferenceSerializer;
@Inject
private Provider<OldRendering> oldRenderingProvider;
@Inject
private ComponentManager componentManager;
@Inject
@Named(HINT)
private XWikiAttachmentStoreInterface attachmentContentStore;
@Inject
@Named(HINT)
private AttachmentVersioningStore attachmentArchiveStore;
private Map<String, String[]> validTypesMap = new HashMap<>();
/**
* This allows to initialize our storage engine. The hibernate config file path is taken from xwiki.cfg or directly
* in the WEB-INF directory.
*
* @param xwiki
* @param context
* @deprecated 1.6M1. Use ComponentManager.lookup(XWikiStoreInterface.class) instead.
*/
@Deprecated
public XWikiHibernateStore(XWiki xwiki, XWikiContext context)
{
super(xwiki, context);
initValidColumTypes();
}
/**
* Initialize the storage engine with a specific path. This is used for tests.
*
* @param hibpath
* @deprecated 1.6M1. Use ComponentManager.lookup(XWikiStoreInterface.class) instead.
*/
@Deprecated
public XWikiHibernateStore(String hibpath)
{
super(hibpath);
initValidColumTypes();
}
/**
* @see #XWikiHibernateStore(XWiki, XWikiContext)
* @deprecated 1.6M1. Use ComponentManager.lookup(XWikiStoreInterface.class) instead.
*/
@Deprecated
public XWikiHibernateStore(XWikiContext context)
{
this(context.getWiki(), context);
}
/**
* Empty constructor needed for component manager.
*/
public XWikiHibernateStore()
{
initValidColumTypes();
}
@Override
public void initialize() throws InitializationException
{
super.initialize();
this.registerLogoutListener();
}
/**
* This initializes the valid custom types Used for Custom Mapping
*/
private void initValidColumTypes()
{
String[] string_types = { "string", "text", "clob" };
String[] number_types =
{ "integer", "long", "float", "double", "big_decimal", "big_integer", "yes_no", "true_false" };
String[] date_types = { "date", "time", "timestamp" };
String[] boolean_types = { "boolean", "yes_no", "true_false", "integer" };
this.validTypesMap = new HashMap<>();
this.validTypesMap.put("com.xpn.xwiki.objects.classes.StringClass", string_types);
this.validTypesMap.put("com.xpn.xwiki.objects.classes.TextAreaClass", string_types);
this.validTypesMap.put("com.xpn.xwiki.objects.classes.PasswordClass", string_types);
this.validTypesMap.put("com.xpn.xwiki.objects.classes.NumberClass", number_types);
this.validTypesMap.put("com.xpn.xwiki.objects.classes.DateClass", date_types);
this.validTypesMap.put("com.xpn.xwiki.objects.classes.BooleanClass", boolean_types);
}
@Override
public boolean isWikiNameAvailable(String wikiName, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, false);
boolean available;
boolean bTransaction = true;
String database = context.getWikiId();
try {
bTransaction = beginTransaction(context);
Session session = getSession(context);
// Capture Logs since we voluntarily generate storage errors to check if the wiki already exists and
// we don't want to pollute application logs with "normal errors"...
if (!this.logger.isDebugEnabled()) {
this.loggerManager.pushLogListener(null);
}
context.setWikiId(wikiName);
try {
setDatabase(session, context);
available = false;
} catch (XWikiException e) {
// Failed to switch to database. Assume it means database does not exists.
available = !(e.getCause() instanceof MigrationRequiredException);
}
} catch (Exception e) {
Object[] args = { wikiName };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_CHECK_EXISTS_DATABASE,
"Exception while listing databases to search for {0}", e, args);
} finally {
context.setWikiId(database);
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
// Restore proper logging
if (!this.logger.isDebugEnabled()) {
this.loggerManager.popLogListener();
}
}
return available;
}
@Override
public void createWiki(String wikiName, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, false);
boolean bTransaction = true;
String database = context.getWikiId();
Statement stmt = null;
try {
bTransaction = beginTransaction(context);
Session session = getSession(context);
Connection connection = session.connection();
stmt = connection.createStatement();
String schema = getSchemaFromWikiName(wikiName, context);
String escapedSchema = escapeSchema(schema, context);
DatabaseProduct databaseProduct = getDatabaseProductName();
if (DatabaseProduct.ORACLE == databaseProduct) {
stmt.execute("create user " + escapedSchema + " identified by " + escapedSchema);
stmt.execute("grant resource to " + escapedSchema);
} else if (DatabaseProduct.DERBY == databaseProduct || DatabaseProduct.DB2 == databaseProduct
|| DatabaseProduct.H2 == databaseProduct) {
stmt.execute("CREATE SCHEMA " + escapedSchema);
} else if (DatabaseProduct.HSQLDB == databaseProduct) {
stmt.execute("CREATE SCHEMA " + escapedSchema + " AUTHORIZATION DBA");
} else if (DatabaseProduct.MYSQL == databaseProduct) {
// TODO: find a proper java lib to convert from java encoding to mysql charset name and collation
if (context.getWiki().getEncoding().equals("UTF-8")) {
stmt.execute("create database " + escapedSchema + " CHARACTER SET utf8 COLLATE utf8_bin");
} else {
stmt.execute("create database " + escapedSchema);
}
} else if (DatabaseProduct.POSTGRESQL == databaseProduct) {
if (isInSchemaMode()) {
stmt.execute("CREATE SCHEMA " + escapedSchema);
} else {
this.logger.error("Creation of a new database is currently only supported in the schema mode, "
+ "see https://jira.xwiki.org/browse/XWIKI-8753");
}
} else {
stmt.execute("create database " + escapedSchema);
}
endTransaction(context, true);
} catch (Exception e) {
Object[] args = { wikiName };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_CREATE_DATABASE, "Exception while create wiki database {0}",
e, args);
} finally {
context.setWikiId(database);
try {
if (stmt != null) {
stmt.close();
}
} catch (Exception e) {
}
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
}
}
@Override
public void deleteWiki(String wikiName, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, false);
boolean bTransaction = true;
String database = context.getWikiId();
Statement stmt = null;
try {
bTransaction = beginTransaction(context);
Session session = getSession(context);
Connection connection = session.connection();
stmt = connection.createStatement();
String schema = getSchemaFromWikiName(wikiName, context);
String escapedSchema = escapeSchema(schema, context);
executeDeleteWikiStatement(stmt, getDatabaseProductName(), escapedSchema);
endTransaction(context, true);
} catch (Exception e) {
Object[] args = { wikiName };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_DELETE_DATABASE, "Exception while delete wiki database {0}",
e, args);
} finally {
context.setWikiId(database);
try {
if (stmt != null) {
stmt.close();
}
} catch (Exception e) {
}
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
}
}
/**
* Execute the SQL statement on the database to remove a wiki.
*
* @param statement the statement object on which to execute the wiki deletion
* @param databaseProduct the database type
* @param escapedSchemaName the subwiki schema name being deleted
* @throws SQLException in case of an error while deleting the sub wiki
*/
protected void executeDeleteWikiStatement(Statement statement, DatabaseProduct databaseProduct,
String escapedSchemaName) throws SQLException
{
if (DatabaseProduct.ORACLE == databaseProduct) {
statement.execute("DROP USER " + escapedSchemaName + " CASCADE");
} else if (DatabaseProduct.DERBY == databaseProduct || DatabaseProduct.MYSQL == databaseProduct
|| DatabaseProduct.H2 == databaseProduct) {
statement.execute("DROP SCHEMA " + escapedSchemaName);
} else if (DatabaseProduct.HSQLDB == databaseProduct) {
statement.execute("DROP SCHEMA " + escapedSchemaName + " CASCADE");
} else if (DatabaseProduct.DB2 == databaseProduct) {
statement.execute("DROP SCHEMA " + escapedSchemaName + " RESTRICT");
} else if (DatabaseProduct.POSTGRESQL == databaseProduct) {
if (isInSchemaMode()) {
statement.execute("DROP SCHEMA " + escapedSchemaName + " CASCADE");
} else {
this.logger.warn("Subwiki deletion not yet supported in Database mode for PostgreSQL");
}
}
}
/**
* Verifies if a wiki document exists
*/
@Override
public boolean exists(XWikiDocument doc, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
boolean bTransaction = true;
MonitorPlugin monitor = Util.getMonitorPlugin(context);
try {
doc.setStore(this);
checkHibernate(context);
// Start monitoring timer
if (monitor != null) {
monitor.startTimer(HINT);
}
bTransaction = bTransaction && beginTransaction(null, context);
Session session = getSession(context);
String fullName = doc.getFullName();
String sql = "select doc.fullName from XWikiDocument as doc where doc.fullName=:fullName";
if (!doc.getLocale().equals(Locale.ROOT)) {
sql += " and doc.language=:language";
}
if (monitor != null) {
monitor.setTimerDesc(HINT, sql);
}
Query query = session.createQuery(sql);
query.setString("fullName", fullName);
if (!doc.getLocale().equals(Locale.ROOT)) {
query.setString("language", doc.getLocale().toString());
}
Iterator<String> it = query.list().iterator();
while (it.hasNext()) {
if (fullName.equals(it.next())) {
return true;
}
}
return false;
} catch (Exception e) {
Object[] args = { doc.getDocumentReferenceWithLocale() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_CHECK_EXISTS_DOC, "Exception while reading document {0}",
e, args);
} finally {
// End monitoring timer
if (monitor != null) {
monitor.endTimer(HINT);
}
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
}
} finally {
restoreExecutionXContext();
}
}
@Override
public void saveXWikiDoc(XWikiDocument doc, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
MonitorPlugin monitor = Util.getMonitorPlugin(context);
try {
// Start monitoring timer
if (monitor != null) {
monitor.startTimer(HINT);
}
doc.setStore(this);
// Make sure the database name is stored
doc.setDatabase(context.getWikiId());
// If the comment is larger than the max size supported by the Storage, then abbreviate it
String comment = doc.getComment();
if (comment != null && comment.length() > 1023) {
doc.setComment(StringUtils.abbreviate(comment, 1023));
}
if (bTransaction) {
checkHibernate(context);
SessionFactory sfactory = injectCustomMappingsInSessionFactory(doc, context);
bTransaction = beginTransaction(sfactory, context);
}
Session session = getSession(context);
session.setFlushMode(FlushMode.COMMIT);
// These informations will allow to not look for attachments and objects on loading
doc.setElement(XWikiDocument.HAS_ATTACHMENTS, !doc.getAttachmentList().isEmpty());
doc.setElement(XWikiDocument.HAS_OBJECTS, !doc.getXObjects().isEmpty());
// Let's update the class XML since this is the new way to store it
// TODO If all the properties are removed, the old xml stays?
BaseClass bclass = doc.getXClass();
if (bclass != null) {
if (bclass.getFieldList().isEmpty()) {
doc.setXClassXML("");
} else {
// Don't format the XML to reduce the size of the stored data as much as possible
doc.setXClassXML(bclass.toXMLString(false));
}
bclass.setDirty(false);
}
if (doc.hasElement(XWikiDocument.HAS_ATTACHMENTS)) {
saveAttachmentList(doc, context);
}
// Remove attachments planned for removal
if (!doc.getAttachmentsToRemove().isEmpty()) {
for (XWikiAttachmentToRemove attachmentToRemove : doc.getAttachmentsToRemove()) {
XWikiAttachment attachment = attachmentToRemove.getAttachment();
XWikiAttachmentStoreInterface store = getXWikiAttachmentStoreInterface(attachment);
store.deleteXWikiAttachment(attachment, false, context, false);
}
doc.clearAttachmentsToRemove();
}
// Handle the latest text file
if (doc.isContentDirty() || doc.isMetaDataDirty()) {
Date ndate = new Date();
doc.setDate(ndate);
if (doc.isContentDirty()) {
doc.setContentUpdateDate(ndate);
doc.setContentAuthorReference(doc.getAuthorReference());
}
doc.incrementVersion();
if (context.getWiki().hasVersioning(context)) {
context.getWiki().getVersioningStore().updateXWikiDocArchive(doc, false, context);
}
doc.setContentDirty(false);
doc.setMetaDataDirty(false);
} else {
if (doc.getDocumentArchive() != null) {
// A custom document archive has been provided, we assume it's right
// (we also assume it's custom but that's another matter...)
// Let's make sure we save the archive if we have one
// This is especially needed if we load a document from XML
if (context.getWiki().hasVersioning(context)) {
context.getWiki().getVersioningStore().saveXWikiDocArchive(doc.getDocumentArchive(), false,
context);
// If the version does not exist it means it's a new version so add it to the history
if (!containsVersion(doc, doc.getRCSVersion(), context)) {
context.getWiki().getVersioningStore().updateXWikiDocArchive(doc, false, context);
}
}
} else {
// Make sure the getArchive call has been made once
// with a valid context
try {
if (context.getWiki().hasVersioning(context)) {
doc.getDocumentArchive(context);
// If the version does not exist it means it's a new version so register it in the
// history
if (!containsVersion(doc, doc.getRCSVersion(), context)) {
context.getWiki().getVersioningStore().updateXWikiDocArchive(doc, false, context);
}
}
} catch (XWikiException e) {
// this is a non critical error
}
}
}
// Verify if the document already exists
Query query =
session.createQuery("select xwikidoc.id from XWikiDocument as xwikidoc where xwikidoc.id = :id");
query.setLong("id", doc.getId());
// Note: we don't use session.saveOrUpdate(doc) because it used to be slower in Hibernate than calling
// session.save() and session.update() separately.
if (query.uniqueResult() == null) {
if (doc.isContentDirty() || doc.isMetaDataDirty()) {
// Reset the creationDate to reflect the date of the first save, not the date of the object
// creation
doc.setCreationDate(new Date());
}
session.save(doc);
} else {
session.update(doc);
}
// Remove objects planned for removal
if (doc.getXObjectsToRemove().size() > 0) {
for (BaseObject removedObject : doc.getXObjectsToRemove()) {
deleteXWikiCollection(removedObject, context, false, false);
}
doc.setXObjectsToRemove(new ArrayList<BaseObject>());
}
if (bclass != null) {
bclass.setDocumentReference(doc.getDocumentReference());
// Store this XWikiClass in the context so that we can use it in case of recursive usage of classes
context.addBaseClass(bclass);
}
if (doc.hasElement(XWikiDocument.HAS_OBJECTS)) {
// TODO: Delete all objects for which we don't have a name in the Map
for (List<BaseObject> objects : doc.getXObjects().values()) {
for (BaseObject obj : objects) {
if (obj != null) {
obj.setDocumentReference(doc.getDocumentReference());
/* If the object doesn't have a GUID, create it before saving */
if (StringUtils.isEmpty(obj.getGuid())) {
obj.setGuid(null);
}
saveXWikiCollection(obj, context, false);
}
}
}
}
if (context.getWiki().hasBacklinks(context)) {
try {
saveLinks(doc, context, true);
} catch (Exception e) {
this.logger.error("Failed to save links for document [{}]",
doc.getDocumentReferenceWithLocale(), e);
}
}
// Update space table
updateXWikiSpaceTable(doc, session);
if (bTransaction) {
endTransaction(context, true);
}
doc.setNew(false);
// We need to ensure that the saved document becomes the original document
doc.setOriginalDocument(doc.clone());
} catch (Exception e) {
Object[] args = { this.defaultEntityReferenceSerializer.serialize(doc.getDocumentReference()) };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_DOC, "Exception while saving document {0}", e,
args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
// End monitoring timer
if (monitor != null) {
monitor.endTimer(HINT);
}
}
} finally {
restoreExecutionXContext();
}
}
private void updateXWikiSpaceTable(XWikiDocument document, Session session)
{
if (document.getLocale().equals(Locale.ROOT)) {
if (!document.isNew()) {
// If the hidden state of an existing document did not changed there is nothing to do
if (document.isHidden() != document.getOriginalDocument().isHidden()) {
if (document.isHidden()) {
// If the document became hidden it's possible the space did too
maybeMakeSpaceHidden(document.getDocumentReference().getLastSpaceReference(),
document.getFullName(), session);
} else {
// If the document became visible then all its parents should be visible as well
makeSpaceVisible(document.getDocumentReference().getLastSpaceReference(), session);
}
}
} else {
// It's possible the space of a new document does not yet exist
maybeCreateSpace(document.getDocumentReference().getLastSpaceReference(), document.isHidden(),
document.getFullName(), session);
}
}
}
private void insertXWikiSpace(XWikiSpace space, String newDocument, Session session)
{
// Insert the space
session.save(space);
// Update parent space
if (space.getSpaceReference().getParent() instanceof SpaceReference) {
maybeCreateSpace((SpaceReference) space.getSpaceReference().getParent(), space.isHidden(), newDocument,
session);
}
}
private void makeSpaceVisible(SpaceReference spaceReference, Session session)
{
XWikiSpace space = loadXWikiSpace(spaceReference, session);
makeSpaceVisible(space, session);
}
private void makeSpaceVisible(XWikiSpace space, Session session)
{
if (space.isHidden()) {
space.setHidden(false);
session.update(space);
// Update parent
if (space.getSpaceReference().getParent() instanceof SpaceReference) {
makeSpaceVisible((SpaceReference) space.getSpaceReference().getParent(), session);
}
}
}
private void maybeMakeSpaceHidden(SpaceReference spaceReference, String modifiedDocument, Session session)
{
XWikiSpace space = loadXWikiSpace(spaceReference, session);
// The space is supposed to exist
if (space == null) {
this.logger.warn(
"Space [{}] does not exist. Usually means the spaces table is not in sync with the documents table.",
spaceReference);
return;
}
// If the space is already hidden return
if (space.isHidden()) {
return;
}
if (calculateHiddenStatus(spaceReference, modifiedDocument, session)) {
// Make the space hidden
space.setHidden(true);
session.update(space);
// Update space parent
if (spaceReference.getParent() instanceof SpaceReference) {
maybeMakeSpaceHidden((SpaceReference) spaceReference.getParent(), modifiedDocument, session);
}
}
}
private void maybeCreateSpace(SpaceReference spaceReference, boolean hidden, String newDocument, Session session)
{
XWikiSpace space = loadXWikiSpace(spaceReference, session);
if (space != null) {
if (space.isHidden() && !hidden) {
makeSpaceVisible(space, session);
}
} else {
insertXWikiSpace(new XWikiSpace(spaceReference, hidden), newDocument, session);
}
}
private long countAllDocuments(SpaceReference spaceReference, Session session, String extraWhere,
Object... extraParameters)
{
StringBuilder builder =
new StringBuilder("select count(*) from XWikiDocument as xwikidoc where (space = ? OR space LIKE ?)");
if (StringUtils.isNotEmpty(extraWhere)) {
builder.append(" AND ");
builder.append('(');
builder.append(extraWhere);
builder.append(')');
}
Query query = session.createQuery(builder.toString());
String localSpaceReference = this.localEntityReferenceSerializer.serialize(spaceReference);
int index = 0;
query.setString(index++, localSpaceReference);
query.setString(index++, localSpaceReference + ".%");
if (extraParameters != null) {
for (Object parameter : extraParameters) {
query.setParameter(index++, parameter);
}
}
return (Long) query.uniqueResult();
}
/**
* Find hidden status of a space from its children.
*/
private boolean calculateHiddenStatus(SpaceReference spaceReference, String documentToIngore, Session session)
{
// If there is at least one visible document then the space is visible
StringBuilder builder = new StringBuilder("(hidden = false OR hidden IS NULL)");
Object[] parameters;
if (documentToIngore != null) {
builder.append(" AND fullName <> ?");
parameters = new Object[] { documentToIngore };
} else {
parameters = null;
}
return !(countAllDocuments(spaceReference, session, builder.toString(), parameters) > 0);
}
private boolean containsVersion(XWikiDocument doc, Version targetversion, XWikiContext context)
throws XWikiException
{
for (Version version : doc.getRevisions(context)) {
if (version.equals(targetversion)) {
return true;
}
}
return false;
}
@Override
public void saveXWikiDoc(XWikiDocument doc, XWikiContext context) throws XWikiException
{
saveXWikiDoc(doc, context, true);
}
@Override
public XWikiDocument loadXWikiDoc(XWikiDocument doc, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
// To change body of implemented methods use Options | File Templates.
boolean bTransaction = true;
MonitorPlugin monitor = Util.getMonitorPlugin(context);
try {
// Start monitoring timer
if (monitor != null) {
monitor.startTimer(HINT);
}
doc.setStore(this);
checkHibernate(context);
SessionFactory sfactory = injectCustomMappingsInSessionFactory(doc, context);
bTransaction = bTransaction && beginTransaction(sfactory, context);
Session session = getSession(context);
session.setFlushMode(FlushMode.MANUAL);
try {
session.load(doc, Long.valueOf(doc.getId()));
doc.setNew(false);
doc.setMostRecent(true);
// Fix for XWIKI-1651
doc.setDate(new Date(doc.getDate().getTime()));
doc.setCreationDate(new Date(doc.getCreationDate().getTime()));
doc.setContentUpdateDate(new Date(doc.getContentUpdateDate().getTime()));
} catch (ObjectNotFoundException e) { // No document
doc.setNew(true);
// Make sure to always return a document with an original version, even for one that does not exist.
// Allow writing more generic code.
doc.setOriginalDocument(new XWikiDocument(doc.getDocumentReference(), doc.getLocale()));
return doc;
}
// Loading the attachment list
if (doc.hasElement(XWikiDocument.HAS_ATTACHMENTS)) {
loadAttachmentList(doc, context, false);
}
// TODO: handle the case where there are no xWikiClass and xWikiObject in the Database
BaseClass bclass = new BaseClass();
String cxml = doc.getXClassXML();
if (cxml != null) {
bclass.fromXML(cxml);
doc.setXClass(bclass);
bclass.setDirty(false);
}
// Store this XWikiClass in the context so that we can use it in case of recursive usage
// of classes
context.addBaseClass(bclass);
if (doc.hasElement(XWikiDocument.HAS_OBJECTS)) {
Query query = session
.createQuery("from BaseObject as bobject where bobject.name = :name order by bobject.number");
query.setText("name", doc.getFullName());
@SuppressWarnings("unchecked")
Iterator<BaseObject> it = query.list().iterator();
EntityReference localGroupEntityReference = new EntityReference("XWikiGroups", EntityType.DOCUMENT,
new EntityReference("XWiki", EntityType.SPACE));
DocumentReference groupsDocumentReference = new DocumentReference(context.getWikiId(),
localGroupEntityReference.getParent().getName(), localGroupEntityReference.getName());
boolean hasGroups = false;
while (it.hasNext()) {
BaseObject object = it.next();
DocumentReference classReference = object.getXClassReference();
if (classReference == null) {
continue;
}
// It seems to search before is case insensitive. And this would break the loading if we get an
// object which doesn't really belong to this document
if (!object.getDocumentReference().equals(doc.getDocumentReference())) {
continue;
}
BaseObject newobject;
if (classReference.equals(doc.getDocumentReference())) {
newobject = bclass.newCustomClassInstance(context);
} else {
newobject = BaseClass.newCustomClassInstance(classReference, context);
}
if (newobject != null) {
newobject.setId(object.getId());
newobject.setXClassReference(object.getRelativeXClassReference());
newobject.setDocumentReference(object.getDocumentReference());
newobject.setNumber(object.getNumber());
newobject.setGuid(object.getGuid());
object = newobject;
}
if (classReference.equals(groupsDocumentReference)) {
// Groups objects are handled differently.
hasGroups = true;
} else {
loadXWikiCollectionInternal(object, doc, context, false, true);
}
doc.setXObject(object.getNumber(), object);
}
// AFAICT this was added as an emergency patch because loading of objects has proven
// too slow and the objects which cause the most overhead are the XWikiGroups objects
// as each group object (each group member) would otherwise cost 2 database queries.
// This will do every group member in a single query.
if (hasGroups) {
Query query2 =
session.createQuery("select bobject.number, prop.value from StringProperty as prop,"
+ "BaseObject as bobject where bobject.name = :name and bobject.className='XWiki.XWikiGroups' "
+ "and bobject.id=prop.id.id and prop.id.name='member' order by bobject.number");
query2.setText("name", doc.getFullName());
@SuppressWarnings("unchecked")
Iterator<Object[]> it2 = query2.list().iterator();
while (it2.hasNext()) {
Object[] result = it2.next();
Integer number = (Integer) result[0];
String member = (String) result[1];
BaseObject obj = BaseClass.newCustomClassInstance(groupsDocumentReference, context);
obj.setDocumentReference(doc.getDocumentReference());
obj.setXClassReference(localGroupEntityReference);
obj.setNumber(number.intValue());
obj.setStringValue("member", member);
doc.setXObject(obj.getNumber(), obj);
}
}
}
doc.setContentDirty(false);
doc.setMetaDataDirty(false);
// We need to ensure that the loaded document becomes the original document
doc.setOriginalDocument(doc.clone());
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
Object[] args = { doc.getDocumentReference() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_READING_DOC, "Exception while reading document [{0}]", e,
args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
// End monitoring timer
if (monitor != null) {
monitor.endTimer(HINT);
}
}
this.logger.debug("Loaded XWikiDocument: [{}]", doc.getDocumentReference());
return doc;
} finally {
restoreExecutionXContext();
}
}
@Override
public void deleteXWikiDoc(XWikiDocument doc, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
boolean bTransaction = true;
MonitorPlugin monitor = Util.getMonitorPlugin(context);
try {
// Start monitoring timer
if (monitor != null) {
monitor.startTimer(HINT);
}
checkHibernate(context);
SessionFactory sfactory = injectCustomMappingsInSessionFactory(doc, context);
bTransaction = bTransaction && beginTransaction(sfactory, context);
Session session = getSession(context);
session.setFlushMode(FlushMode.COMMIT);
if (doc.getStore() == null) {
Object[] args = { doc.getDocumentReference() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_CANNOT_DELETE_UNLOADED_DOC,
"Impossible to delete document {0} if it is not loaded", null, args);
}
// Let's delete any attachment this document might have
for (XWikiAttachment attachment : doc.getAttachmentList()) {
XWikiAttachmentStoreInterface store = getXWikiAttachmentStoreInterface(attachment);
store.deleteXWikiAttachment(attachment, false, context, false);
}
// deleting XWikiLinks
if (context.getWiki().hasBacklinks(context)) {
deleteLinks(doc.getId(), context, true);
}
// Find the list of classes for which we have an object
// Remove properties planned for removal
if (!doc.getXObjectsToRemove().isEmpty()) {
for (BaseObject bobj : doc.getXObjectsToRemove()) {
if (bobj != null) {
deleteXWikiCollection(bobj, context, false, false);
}
}
doc.setXObjectsToRemove(new ArrayList<BaseObject>());
}
for (List<BaseObject> objects : doc.getXObjects().values()) {
for (BaseObject obj : objects) {
if (obj != null) {
deleteXWikiCollection(obj, context, false, false);
}
}
}
context.getWiki().getVersioningStore().deleteArchive(doc, false, context);
session.delete(doc);
// We need to ensure that the deleted document becomes the original document
doc.setOriginalDocument(doc.clone());
// Update space table if needed
maybeDeleteXWikiSpace(doc, session);
if (bTransaction) {
endTransaction(context, true);
}
} catch (Exception e) {
Object[] args = { doc.getDocumentReference() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_DELETING_DOC, "Exception while deleting document {0}", e,
args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
// End monitoring timer
if (monitor != null) {
monitor.endTimer(HINT);
}
}
} finally {
restoreExecutionXContext();
}
}
private void maybeDeleteXWikiSpace(XWikiDocument deletedDocument, Session session)
{
if (deletedDocument.getLocale().equals(Locale.ROOT)) {
DocumentReference documentReference = deletedDocument.getDocumentReference();
maybeDeleteXWikiSpace(documentReference.getLastSpaceReference(),
this.localEntityReferenceSerializer.serialize(documentReference), session);
}
}
private void maybeDeleteXWikiSpace(SpaceReference spaceReference, String deletedDocument, Session session)
{
if (countAllDocuments(spaceReference, session, "fullName <> ? AND (language IS NULL OR language = '')",
deletedDocument) == 0) {
// The document was the last document in the space
XWikiSpace space = new XWikiSpace(spaceReference, this);
session.delete(space);
// Update parent
if (spaceReference.getParent() instanceof SpaceReference) {
maybeDeleteXWikiSpace((SpaceReference) spaceReference.getParent(), deletedDocument, session);
}
} else {
// Update space hidden property if needed
maybeMakeSpaceHidden(spaceReference, deletedDocument, session);
}
}
private XWikiSpace loadXWikiSpace(SpaceReference spaceReference, Session session)
{
XWikiSpace space = new XWikiSpace(spaceReference, this);
try {
session.load(space, Long.valueOf(space.getId()));
} catch (ObjectNotFoundException e) {
// No space
return null;
}
return space;
}
private void checkObjectClassIsLocal(BaseCollection object, XWikiContext context) throws XWikiException
{
DocumentReference xclass = object.getXClassReference();
WikiReference wikiReference = xclass.getWikiReference();
String db = context.getWikiId();
if (!wikiReference.getName().equals(db)) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_OBJECT,
"XObject [{0}] is an instance of an external XClass and cannot be persisted in this wiki [{1}].", null,
new Object[] { this.localEntityReferenceSerializer.serialize(object.getReference()), db });
}
}
/**
* @deprecated This is internal to XWikiHibernateStore and may be removed in the future.
*/
@Deprecated
public void saveXWikiCollection(BaseCollection object, XWikiContext inputxcontext, boolean bTransaction)
throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
if (object == null) {
return;
}
// We need a slightly different behavior here
boolean stats = (object instanceof XWikiStats);
if (!stats) {
checkObjectClassIsLocal(object, context);
}
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(context);
}
Session session = getSession(context);
// Verify if the property already exists
Query query;
if (stats) {
query = session
.createQuery("select obj.id from " + object.getClass().getName() + " as obj where obj.id = :id");
} else {
query = session.createQuery("select obj.id from BaseObject as obj where obj.id = :id");
}
query.setLong("id", object.getId());
if (query.uniqueResult() == null) {
if (stats) {
session.save(object);
} else {
session.save("com.xpn.xwiki.objects.BaseObject", object);
}
} else {
if (stats) {
session.update(object);
} else {
session.update("com.xpn.xwiki.objects.BaseObject", object);
}
}
/*
* if (stats) session.saveOrUpdate(object); else
* session.saveOrUpdate((String)"com.xpn.xwiki.objects.BaseObject", (Object)object);
*/
BaseClass bclass = object.getXClass(context);
List<String> handledProps = new ArrayList<>();
if ((bclass != null) && (bclass.hasCustomMapping()) && context.getWiki().hasCustomMappings()) {
// save object using the custom mapping
Map<String, Object> objmap = object.getCustomMappingMap();
handledProps = bclass.getCustomMappingPropertyList(context);
Session dynamicSession = session.getSession(EntityMode.MAP);
query = session.createQuery("select obj.id from " + bclass.getName() + " as obj where obj.id = :id");
query.setLong("id", object.getId());
if (query.uniqueResult() == null) {
dynamicSession.save(bclass.getName(), objmap);
} else {
dynamicSession.update(bclass.getName(), objmap);
}
// dynamicSession.saveOrUpdate((String) bclass.getName(), objmap);
}
if (object.getXClassReference() != null) {
// Remove all existing properties
if (object.getFieldsToRemove().size() > 0) {
for (int i = 0; i < object.getFieldsToRemove().size(); i++) {
BaseProperty prop = (BaseProperty) object.getFieldsToRemove().get(i);
if (!handledProps.contains(prop.getName())) {
session.delete(prop);
}
}
object.setFieldsToRemove(new ArrayList<BaseProperty>());
}
Iterator<String> it = object.getPropertyList().iterator();
while (it.hasNext()) {
String key = it.next();
BaseProperty prop = (BaseProperty) object.getField(key);
if (!prop.getName().equals(key)) {
Object[] args = { key, object.getName() };
throw new XWikiException(XWikiException.MODULE_XWIKI_CLASSES,
XWikiException.ERROR_XWIKI_CLASSES_FIELD_INVALID,
"Field {0} in object {1} has an invalid name", null, args);
}
String pname = prop.getName();
if (pname != null && !pname.trim().equals("") && !handledProps.contains(pname)) {
saveXWikiPropertyInternal(prop, context, false);
}
}
}
if (bTransaction) {
endTransaction(context, true);
}
} catch (XWikiException xe) {
throw xe;
} catch (Exception e) {
Object[] args = { object.getName() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_OBJECT, "Exception while saving object {0}", e, args);
} finally {
try {
if (bTransaction) {
endTransaction(context, true);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
}
/**
* @deprecated This is internal to XWikiHibernateStore and may be removed in the future.
*/
@Deprecated
public void loadXWikiCollection(BaseCollection object, XWikiContext context, boolean bTransaction)
throws XWikiException
{
loadXWikiCollectionInternal(object, context, bTransaction, false);
}
private void loadXWikiCollectionInternal(BaseCollection object, XWikiContext context, boolean bTransaction,
boolean alreadyLoaded) throws XWikiException
{
loadXWikiCollectionInternal(object, null, context, bTransaction, alreadyLoaded);
}
private void loadXWikiCollectionInternal(BaseCollection object1, XWikiDocument doc, XWikiContext inputxcontext,
boolean bTransaction, boolean alreadyLoaded) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
BaseCollection object = object1;
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(false, context);
}
Session session = getSession(context);
if (!alreadyLoaded) {
try {
session.load(object, object1.getId());
} catch (ObjectNotFoundException e) {
// There is no object data saved
object = null;
return;
}
}
DocumentReference classReference = object.getXClassReference();
// If the class reference is null in the loaded object then skip loading properties
if (classReference != null) {
BaseClass bclass = null;
if (!classReference.equals(object.getDocumentReference())) {
// Let's check if the class has a custom mapping
bclass = object.getXClass(context);
} else {
// We need to get it from the document otherwise
// we will go in an endless loop
if (doc != null) {
bclass = doc.getXClass();
}
}
List<String> handledProps = new ArrayList<String>();
try {
if ((bclass != null) && (bclass.hasCustomMapping()) && context.getWiki().hasCustomMappings()) {
Session dynamicSession = session.getSession(EntityMode.MAP);
String className = this.localEntityReferenceSerializer.serialize(bclass.getDocumentReference());
@SuppressWarnings("unchecked")
Map<String, ?> map = (Map<String, ?>) dynamicSession.load(className, object.getId());
// Let's make sure to look for null fields in the dynamic mapping
bclass.fromValueMap(map, object);
for (String prop : bclass.getCustomMappingPropertyList(context)) {
if (map.get(prop) != null) {
handledProps.add(prop);
}
}
}
} catch (HibernateException e) {
this.logger.error("Failed loading custom mapping for doc [{}], class [{}], nb [{}]",
object.getDocumentReference(), object.getXClassReference(), object.getNumber(), e);
}
// Load strings, integers, dates all at once
Query query = session
.createQuery("select prop.name, prop.classType from BaseProperty as prop where prop.id.id = :id");
query.setLong("id", object.getId());
for (Object[] result : (List<Object[]>) query.list()) {
String name = (String) result[0];
// No need to load fields already loaded from
// custom mapping
if (handledProps.contains(name)) {
continue;
}
String classType = (String) result[1];
BaseProperty property = null;
try {
property = (BaseProperty) Class.forName(classType).newInstance();
property.setObject(object);
property.setName(name);
loadXWikiProperty(property, context, false);
} catch (Exception e) {
// WORKAROUND IN CASE OF MIXMATCH BETWEEN STRING AND LARGESTRING
try {
if (property instanceof StringProperty) {
LargeStringProperty property2 = new LargeStringProperty();
property2.setObject(object);
property2.setName(name);
loadXWikiProperty(property2, context, false);
property.setValue(property2.getValue());
if (bclass != null) {
if (bclass.get(name) instanceof TextAreaClass) {
property = property2;
}
}
} else if (property instanceof LargeStringProperty) {
StringProperty property2 = new StringProperty();
property2.setObject(object);
property2.setName(name);
loadXWikiProperty(property2, context, false);
property.setValue(property2.getValue());
if (bclass != null) {
if (bclass.get(name) instanceof StringClass) {
property = property2;
}
}
} else {
throw e;
}
} catch (Throwable e2) {
Object[] args =
{ object.getName(), object.getClass(), Integer.valueOf(object.getNumber() + ""), name };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_OBJECT,
"Exception while loading object '{0}' of class '{1}', number '{2}' and property '{3}'",
e, args);
}
}
object.addField(name, property);
}
}
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
Object[] args = { object.getName(), object.getClass(), Integer.valueOf(object.getNumber() + "") };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_OBJECT,
"Exception while loading object '{0}' of class '{1}' and number '{2}'", e, args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
}
/**
* @deprecated This is internal to XWikiHibernateStore and may be removed in the future.
*/
@Deprecated
public void deleteXWikiCollection(BaseCollection object, XWikiContext inputxcontext, boolean bTransaction,
boolean evict) throws XWikiException
{
if (object == null) {
return;
}
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(context);
}
Session session = getSession(context);
// Let's check if the class has a custom mapping
BaseClass bclass = object.getXClass(context);
List<String> handledProps = new ArrayList<String>();
if ((bclass != null) && (bclass.hasCustomMapping()) && context.getWiki().hasCustomMappings()) {
handledProps = bclass.getCustomMappingPropertyList(context);
Session dynamicSession = session.getSession(EntityMode.MAP);
Object map = dynamicSession.get(bclass.getName(), object.getId());
if (map != null) {
if (evict) {
dynamicSession.evict(map);
}
dynamicSession.delete(map);
}
}
if (object.getXClassReference() != null) {
for (BaseElement property : (Collection<BaseElement>) object.getFieldList()) {
if (!handledProps.contains(property.getName())) {
if (evict) {
session.evict(property);
}
if (session.get(property.getClass(), property) != null) {
session.delete(property);
}
}
}
}
// In case of custom class we need to force it as BaseObject to delete the xwikiobject row
if (!"".equals(bclass.getCustomClass())) {
BaseObject cobject = new BaseObject();
cobject.setDocumentReference(object.getDocumentReference());
cobject.setClassName(object.getClassName());
cobject.setNumber(object.getNumber());
if (object instanceof BaseObject) {
cobject.setGuid(((BaseObject) object).getGuid());
}
cobject.setId(object.getId());
if (evict) {
session.evict(cobject);
}
session.delete(cobject);
} else {
if (evict) {
session.evict(object);
}
session.delete(object);
}
if (bTransaction) {
endTransaction(context, true);
}
} catch (Exception e) {
Object[] args = { object.getName() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_DELETING_OBJECT, "Exception while deleting object {0}", e,
args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
}
private void loadXWikiProperty(PropertyInterface property, XWikiContext context, boolean bTransaction)
throws XWikiException
{
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(false, context);
}
Session session = getSession(context);
try {
session.load(property, (Serializable) property);
// In Oracle, empty string are converted to NULL. Since an undefined property is not found at all, it is
// safe to assume that a retrieved NULL value should actually be an empty string.
if (property instanceof BaseStringProperty) {
BaseStringProperty stringProperty = (BaseStringProperty) property;
if (stringProperty.getValue() == null) {
stringProperty.setValue("");
}
}
((BaseProperty) property).setValueDirty(false);
} catch (ObjectNotFoundException e) {
// Let's accept that there is no data in property tables but log it
this.logger.error("No data for property [{}] of object id [{}]", property.getName(), property.getId());
}
// TODO: understand why collections are lazy loaded
// Let's force reading lists if there is a list
// This seems to be an issue since Hibernate 3.0
// Without this test ViewEditTest.testUpdateAdvanceObjectProp fails
if (property instanceof ListProperty) {
((ListProperty) property).getList();
}
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
BaseCollection obj = property.getObject();
Object[] args = { (obj != null) ? obj.getName() : "unknown", property.getName() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_OBJECT,
"Exception while loading property {1} of object {0}", e, args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
}
}
private void saveXWikiPropertyInternal(final PropertyInterface property, final XWikiContext context,
final boolean runInOwnTransaction) throws XWikiException
{
// Clone runInOwnTransaction so the value passed is not altered.
boolean bTransaction = runInOwnTransaction;
try {
if (bTransaction) {
this.checkHibernate(context);
bTransaction = this.beginTransaction(context);
}
final Session session = this.getSession(context);
Query query = session.createQuery(
"select prop.classType from BaseProperty as prop " + "where prop.id.id = :id and prop.id.name= :name");
query.setLong("id", property.getId());
query.setString("name", property.getName());
String oldClassType = (String) query.uniqueResult();
String newClassType = ((BaseProperty) property).getClassType();
if (oldClassType == null) {
session.save(property);
} else if (oldClassType.equals(newClassType)) {
session.update(property);
} else {
// The property type has changed. We cannot simply update its value because the new value and the old
// value are stored in different tables (we're using joined-subclass to map different property types).
// We must delete the old property value before saving the new one and for this we must load the old
// property from the table that corresponds to the old property type (we cannot delete and save the new
// property or delete a clone of the new property; loading the old property from the BaseProperty table
// doesn't work either).
query = session.createQuery(
"select prop from " + oldClassType + " as prop where prop.id.id = :id and prop.id.name= :name");
query.setLong("id", property.getId());
query.setString("name", property.getName());
session.delete(query.uniqueResult());
session.save(property);
}
((BaseProperty) property).setValueDirty(false);
if (bTransaction) {
endTransaction(context, true);
}
} catch (Exception e) {
// Something went wrong, collect some information.
final BaseCollection obj = property.getObject();
final Object[] args = { (obj != null) ? obj.getName() : "unknown", property.getName() };
// Try to roll back the transaction if this is in it's own transaction.
try {
if (bTransaction) {
this.endTransaction(context, false);
}
} catch (Exception ee) {
// Not a lot we can do here if there was an exception committing and an exception rolling back.
}
// Throw the exception.
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_OBJECT,
"Exception while saving property {1} of object {0}", e, args);
}
}
private void loadAttachmentList(XWikiDocument doc, XWikiContext context, boolean bTransaction) throws XWikiException
{
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(null, context);
}
Session session = getSession(context);
Query query = session.createQuery("from XWikiAttachment as attach where attach.docId=:docid");
query.setLong("docid", doc.getId());
@SuppressWarnings("unchecked")
List<XWikiAttachment> list = query.list();
for (XWikiAttachment attachment : list) {
doc.setAttachment(attachment);
}
} catch (Exception e) {
this.logger.error("Failed to load attachments of document [{}]", doc.getDocumentReference(), e);
Object[] args = { doc.getDocumentReference() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCHING_ATTACHMENT,
"Exception while searching attachments for documents {0}", e, args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
}
}
private void saveAttachmentList(XWikiDocument doc, XWikiContext context) throws XWikiException
{
try {
getSession(context);
List<XWikiAttachment> list = doc.getAttachmentList();
for (XWikiAttachment attachment : list) {
saveAttachment(attachment, context);
}
} catch (Exception e) {
Object[] args = { doc.getDocumentReference() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_ATTACHMENT_LIST,
"Exception while saving attachments attachment list of document {0}", e, args);
}
}
private void saveAttachment(XWikiAttachment attachment, XWikiContext context) throws XWikiException
{
try {
// If the comment is larger than the max size supported by the Storage, then abbreviate it
String comment = attachment.getComment();
if (comment != null && comment.length() > 1023) {
attachment.setComment(StringUtils.abbreviate(comment, 1023));
}
// The version number must be increased and the date must be set before the attachment meta data is saved.
// Changing the version and date after calling session.save()/session.update() "worked" (the altered version
// was what Hibernate saved) but only if everything is done in the same transaction and as far as I know it
// depended on undefined behavior.
// Note that the second condition is required because there are cases when we want the attachment content to
// be saved (see below) but we don't want the version to be increased (e.g. restore a document from recycle
// bin, copy or import a document).
// See XWIKI-9421: Attachment version is incremented when a document is restored from recycle bin
if (attachment.isContentDirty() && !attachment.getDoc().isNew()) {
attachment.updateContentArchive(context);
}
Session session = getSession(context);
Query query = session.createQuery("select attach.id from XWikiAttachment as attach where attach.id = :id");
query.setLong("id", attachment.getId());
boolean exist = query.uniqueResult() != null;
if (exist) {
session.update(attachment);
} else {
if (attachment.getContentStore() == null) {
// Set content store
attachment.setContentStore(getDefaultAttachmentContentStore(context));
}
if (attachment.getArchiveStore() == null) {
// Set archive store
attachment.setArchiveStore(getDefaultAttachmentArchiveStore(context));
}
session.save(attachment);
}
// Save the attachment content if it's marked as "dirty" (out of sync with the database).
if (attachment.isContentDirty()) {
// updateParent and bTransaction must be false because the content should be saved in the same
// transaction as the attachment and if the parent doc needs to be updated, this function will do it.
XWikiAttachmentStoreInterface store = getXWikiAttachmentStoreInterface(attachment);
store.saveAttachmentContent(attachment, false, context, false);
}
// Mark the attachment content and metadata as not dirty.
// Ideally this would only happen if the transaction is committed successfully but since an unsuccessful
// transaction will most likely be accompanied by an exception, the cache will not have a chance to save
// the copy of the document with erronious information. If this is not set here, the cache will return
// a copy of the attachment which claims to be dirty although it isn't.
attachment.setMetaDataDirty(false);
if (attachment.isContentDirty()) {
attachment.getAttachment_content().setContentDirty(false);
}
} catch (Exception e) {
Object[] args = { attachment.getReference() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_ATTACHMENT, "Exception while saving attachment [{0}]",
e, args);
}
}
// ---------------------------------------
// Locks
// ---------------------------------------
@Override
public XWikiLock loadLock(long docId, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
XWikiLock lock = null;
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(false, context);
}
Session session = getSession(context);
Query query = session.createQuery("select lock.docId from XWikiLock as lock where lock.docId = :docId");
query.setLong("docId", docId);
if (query.uniqueResult() != null) {
lock = new XWikiLock();
session.load(lock, Long.valueOf(docId));
}
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_LOCK, "Exception while loading lock", e);
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
return lock;
}
@Override
public void saveLock(XWikiLock lock, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(context);
}
Session session = getSession(context);
Query query = session.createQuery("select lock.docId from XWikiLock as lock where lock.docId = :docId");
query.setLong("docId", lock.getDocId());
if (query.uniqueResult() == null) {
session.save(lock);
} else {
session.update(lock);
}
if (bTransaction) {
endTransaction(context, true);
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_LOCK, "Exception while locking document", e);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
}
@Override
public void deleteLock(XWikiLock lock, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(context);
}
Session session = getSession(context);
session.delete(lock);
if (bTransaction) {
endTransaction(context, true);
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_DELETING_LOCK, "Exception while deleting lock", e);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
}
private void registerLogoutListener()
{
this.observationManager.addListener(new EventListener()
{
private final Event ev = new ActionExecutingEvent();
@Override
public String getName()
{
return "deleteLocksOnLogoutListener";
}
@Override
public List<Event> getEvents()
{
return Collections.<Event>singletonList(this.ev);
}
@Override
public void onEvent(Event event, Object source, Object data)
{
if ("logout".equals(((ActionExecutingEvent) event).getActionName())) {
final XWikiContext ctx = (XWikiContext) data;
if (ctx.getUserReference() != null) {
releaseAllLocksForCurrentUser(ctx);
}
}
}
});
}
/**
* Release all of the locks held by the currently logged in user.
*
* @param ctx the XWikiContext, used to start the connection and get the user name.
*/
private void releaseAllLocksForCurrentUser(final XWikiContext ctx)
{
try {
this.beginTransaction(ctx);
Session session = this.getSession(ctx);
final Query query = session.createQuery("delete from XWikiLock as lock where lock.userName=:userName");
// Using deprecated getUser() because this is how locks are created.
// It would be a maintainibility disaster to use different code paths
// for calculating names when creating and removing.
query.setString("userName", ctx.getUser());
query.executeUpdate();
this.endTransaction(ctx, true);
} catch (Exception e) {
String msg = "Error while deleting active locks held by user.";
try {
this.endTransaction(ctx, false);
} catch (Exception utoh) {
msg += " Failed to commit OR rollback [" + utoh.getMessage() + "]";
}
throw new UnexpectedException(msg, e);
}
// If we're in a non-main wiki & the user is global,
// switch to the global wiki and delete locks held there.
if (!ctx.isMainWiki() && ctx.isMainWiki(ctx.getUserReference().getWikiReference().getName())) {
final String cdb = ctx.getWikiId();
try {
ctx.setWikiId(ctx.getMainXWiki());
this.releaseAllLocksForCurrentUser(ctx);
} finally {
ctx.setWikiId(cdb);
}
}
}
// ---------------------------------------
// Links
// ---------------------------------------
@Override
public List<XWikiLink> loadLinks(long docId, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
List<XWikiLink> links = new ArrayList<XWikiLink>();
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(false, context);
}
Session session = getSession(context);
Query query = session.createQuery(" from XWikiLink as link where link.id.docId = :docId");
query.setLong("docId", docId);
links = query.list();
if (bTransaction) {
endTransaction(context, false, false);
bTransaction = false;
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_LINKS, "Exception while loading links", e);
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
return links;
}
@Override
public List<DocumentReference> loadBacklinks(DocumentReference documentReference, boolean bTransaction,
XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
// Note: Ideally the method should return a Set but it would break the current API.
// TODO: We use a Set here so that we don't get duplicates. In the future, when we can reference a page in
// another language using a syntax, we should modify this code to return one DocumentReference per language
// found. To implement this we need to be able to either serialize the reference with the language information
// or add some new column for the XWikiLink table in the database.
Set<DocumentReference> backlinkReferences = new HashSet<DocumentReference>();
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(false, context);
}
Session session = getSession(context);
// the select clause is compulsory to reach the fullName i.e. the page pointed
Query query = session
.createQuery("select backlink.fullName from XWikiLink as backlink where backlink.id.link = :backlink");
query.setString("backlink", this.localEntityReferenceSerializer.serialize(documentReference));
@SuppressWarnings("unchecked")
List<String> backlinkNames = query.list();
// Convert strings into references
for (String backlinkName : backlinkNames) {
backlinkReferences.add(this.currentMixedDocumentReferenceResolver.resolve(backlinkName));
}
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_BACKLINKS, "Exception while loading backlinks", e);
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
return new ArrayList<DocumentReference>(backlinkReferences);
}
/**
* @deprecated since 2.2M2 use {@link #loadBacklinks(DocumentReference, boolean, XWikiContext)}
*/
@Deprecated
@Override
public List<String> loadBacklinks(String fullName, XWikiContext inputxcontext, boolean bTransaction)
throws XWikiException
{
List<String> backlinkNames = new ArrayList<String>();
List<DocumentReference> backlinkReferences =
loadBacklinks(this.currentMixedDocumentReferenceResolver.resolve(fullName), bTransaction, inputxcontext);
for (DocumentReference backlinkReference : backlinkReferences) {
backlinkNames.add(this.localEntityReferenceSerializer.serialize(backlinkReference));
}
return backlinkNames;
}
@Override
public void saveLinks(XWikiDocument doc, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(context);
}
Session session = getSession(context);
// need to delete existing links before saving the page's one
deleteLinks(doc.getId(), context, bTransaction);
// necessary to blank links from doc
context.remove("links");
// Extract the links.
Set<XWikiLink> links = new LinkedHashSet<>();
// Add wiki syntax links.
// FIXME: replace with doc.getUniqueWikiLinkedPages(context) when OldRendering is dropped.
links.addAll(this.oldRenderingProvider.get().extractLinks(doc, context));
// Add included pages.
List<String> includedPages = doc.getIncludedPages(context);
for (String includedPage : includedPages) {
XWikiLink wikiLink = new XWikiLink();
wikiLink.setDocId(doc.getId());
wikiLink.setFullName(this.localEntityReferenceSerializer.serialize(doc.getDocumentReference()));
wikiLink.setLink(includedPage);
links.add(wikiLink);
}
// Save the links.
for (XWikiLink wikiLink : links) {
// Verify that the link reference isn't larger than 255 characters (and truncate it if that's the case)
// since otherwise that would lead to a DB error that would result in a fatal error, and the user would
// have a hard time understanding why his page failed to be saved.
wikiLink.setLink(StringUtils.substring(wikiLink.getLink(), 0, 255));
session.save(wikiLink);
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_LINKS, "Exception while saving links", e);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
}
@Override
public void deleteLinks(long docId, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(context);
}
Session session = getSession(context);
Query query = session.createQuery("delete from XWikiLink as link where link.id.docId = :docId");
query.setLong("docId", docId);
query.executeUpdate();
if (bTransaction) {
endTransaction(context, true);
bTransaction = false;
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_DELETING_LINKS, "Exception while deleting links", e);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
}
public void getContent(XWikiDocument doc, StringBuffer buf)
{
buf.append(doc.getContent());
}
@Override
public List<String> getClassList(XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
boolean bTransaction = true;
try {
checkHibernate(context);
bTransaction = beginTransaction(false, context);
Session session = getSession(context);
Query query = session.createQuery("select doc.fullName from XWikiDocument as doc "
+ "where (doc.xWikiClassXML is not null and doc.xWikiClassXML like '<%')");
List<String> list = new ArrayList<String>();
list.addAll(query.list());
if (bTransaction) {
endTransaction(context, false, false);
}
return list;
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCH, "Exception while searching class list", e);
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
}
/**
* Add values into named query.
*
* @param parameterId the parameter id to increment.
* @param query the query to fill.
* @param parameterValues the values to add to query.
* @return the id of the next parameter to add.
*/
private int injectParameterListToQuery(int parameterId, Query query, Collection<?> parameterValues)
{
int index = parameterId;
if (parameterValues != null) {
for (Iterator<?> valueIt = parameterValues.iterator(); valueIt.hasNext(); ++index) {
injectParameterToQuery(index, query, valueIt.next());
}
}
return index;
}
/**
* Add value into named query.
*
* @param parameterId the parameter id to increment.
* @param query the query to fill.
* @param parameterValue the values to add to query.
*/
private void injectParameterToQuery(int parameterId, Query query, Object parameterValue)
{
query.setParameter(parameterId, parameterValue);
}
@Override
public List<DocumentReference> searchDocumentReferences(String parametrizedSqlClause, List<?> parameterValues,
XWikiContext context) throws XWikiException
{
return searchDocumentReferences(parametrizedSqlClause, 0, 0, parameterValues, context);
}
@Override
public List<String> searchDocumentsNames(String parametrizedSqlClause, List<?> parameterValues,
XWikiContext context) throws XWikiException
{
return searchDocumentsNames(parametrizedSqlClause, 0, 0, parameterValues, context);
}
@Override
public List<DocumentReference> searchDocumentReferences(String parametrizedSqlClause, int nb, int start,
List<?> parameterValues, XWikiContext context) throws XWikiException
{
String sql = createSQLQuery("select distinct doc.fullName", parametrizedSqlClause);
return searchDocumentReferencesInternal(sql, nb, start, parameterValues, context);
}
@Override
public List<String> searchDocumentsNames(String parametrizedSqlClause, int nb, int start, List<?> parameterValues,
XWikiContext context) throws XWikiException
{
String sql = createSQLQuery("select distinct doc.fullName", parametrizedSqlClause);
return searchDocumentsNamesInternal(sql, nb, start, parameterValues, context);
}
@Override
public List<DocumentReference> searchDocumentReferences(String wheresql, XWikiContext context) throws XWikiException
{
return searchDocumentReferences(wheresql, 0, 0, "", context);
}
@Override
public List<String> searchDocumentsNames(String wheresql, XWikiContext context) throws XWikiException
{
return searchDocumentsNames(wheresql, 0, 0, "", context);
}
@Override
public List<DocumentReference> searchDocumentReferences(String wheresql, int nb, int start, XWikiContext context)
throws XWikiException
{
return searchDocumentReferences(wheresql, nb, start, "", context);
}
@Override
public List<String> searchDocumentsNames(String wheresql, int nb, int start, XWikiContext context)
throws XWikiException
{
return searchDocumentsNames(wheresql, nb, start, "", context);
}
@Override
public List<DocumentReference> searchDocumentReferences(String wheresql, int nb, int start, String selectColumns,
XWikiContext context) throws XWikiException
{
String sql = createSQLQuery("select distinct doc.fullName", wheresql);
return searchDocumentReferencesInternal(sql, nb, start, Collections.EMPTY_LIST, context);
}
@Override
public List<String> searchDocumentsNames(String wheresql, int nb, int start, String selectColumns,
XWikiContext context) throws XWikiException
{
String sql = createSQLQuery("select distinct doc.fullName", wheresql);
return searchDocumentsNamesInternal(sql, nb, start, Collections.EMPTY_LIST, context);
}
@Override
public <T> List<T> search(String sql, int nb, int start, XWikiContext context) throws XWikiException
{
return search(sql, nb, start, (List<?>) null, context);
}
@Override
public <T> List<T> search(String sql, int nb, int start, List<?> parameterValues, XWikiContext context)
throws XWikiException
{
return search(sql, nb, start, null, parameterValues, context);
}
@Override
public <T> List<T> search(String sql, int nb, int start, Object[][] whereParams, XWikiContext context)
throws XWikiException
{
return search(sql, nb, start, whereParams, null, context);
}
@Override
public <T> List<T> search(String sql, int nb, int start, Object[][] whereParams, List<?> parameterValues,
XWikiContext inputxcontext) throws XWikiException
{
boolean bTransaction = true;
if (sql == null) {
return null;
}
XWikiContext context = getExecutionXContext(inputxcontext, true);
MonitorPlugin monitor = Util.getMonitorPlugin(context);
try {
// Start monitoring timer
if (monitor != null) {
monitor.startTimer(HINT);
}
checkHibernate(context);
bTransaction = beginTransaction(false, context);
Session session = getSession(context);
if (whereParams != null) {
sql += generateWhereStatement(whereParams);
}
Query query = session.createQuery(filterSQL(sql));
// Add values for provided HQL request containing "?" characters where to insert real
// values.
int parameterId = injectParameterListToQuery(0, query, parameterValues);
if (whereParams != null) {
for (Object[] whereParam : whereParams) {
query.setString(parameterId++, (String) whereParam[1]);
}
}
if (start != 0) {
query.setFirstResult(start);
}
if (nb != 0) {
query.setMaxResults(nb);
}
List<T> list = new ArrayList<T>();
list.addAll(query.list());
return list;
} catch (Exception e) {
Object[] args = { sql };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCH, "Exception while searching documents with sql {0}",
e, args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
// End monitoring timer
if (monitor != null) {
monitor.endTimer(HINT);
}
}
}
private String generateWhereStatement(Object[][] whereParams)
{
StringBuilder str = new StringBuilder();
str.append(" where ");
for (int i = 0; i < whereParams.length; i++) {
if (i > 0) {
if (whereParams[i - 1].length >= 4 && whereParams[i - 1][3] != "" && whereParams[i - 1][3] != null) {
str.append(" ");
str.append(whereParams[i - 1][3]);
str.append(" ");
} else {
str.append(" and ");
}
}
str.append(whereParams[i][0]);
if (whereParams[i].length >= 3 && whereParams[i][2] != "" && whereParams[i][2] != null) {
str.append(" ");
str.append(whereParams[i][2]);
str.append(" ");
} else {
str.append(" = ");
}
str.append(" ?");
}
return str.toString();
}
public List search(Query query, int nb, int start, XWikiContext inputxcontext) throws XWikiException
{
boolean bTransaction = true;
if (query == null) {
return null;
}
XWikiContext context = getExecutionXContext(inputxcontext, true);
MonitorPlugin monitor = Util.getMonitorPlugin(context);
try {
// Start monitoring timer
if (monitor != null) {
monitor.startTimer(HINT, query.getQueryString());
}
checkHibernate(context);
bTransaction = beginTransaction(false, context);
if (start != 0) {
query.setFirstResult(start);
}
if (nb != 0) {
query.setMaxResults(nb);
}
Iterator it = query.list().iterator();
List list = new ArrayList();
while (it.hasNext()) {
list.add(it.next());
}
if (bTransaction) {
// The session is closed here, too.
endTransaction(context, false, false);
bTransaction = false;
}
return list;
} catch (Exception e) {
Object[] args = { query.toString() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCH, "Exception while searching documents with sql {0}",
e, args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
// End monitoring timer
if (monitor != null) {
monitor.endTimer(HINT);
}
}
}
@Override
public int countDocuments(String wheresql, XWikiContext context) throws XWikiException
{
String sql = createSQLQuery("select count(distinct doc.fullName)", wheresql);
List<Number> l = search(sql, 0, 0, context);
return l.get(0).intValue();
}
@Override
public int countDocuments(String parametrizedSqlClause, List<?> parameterValues, XWikiContext context)
throws XWikiException
{
String sql = createSQLQuery("select count(distinct doc.fullName)", parametrizedSqlClause);
List l = search(sql, 0, 0, parameterValues, context);
return ((Number) l.get(0)).intValue();
}
/**
* @deprecated since 2.2M1 used {@link #searchDocumentReferencesInternal(String, int, int, List, XWikiContext)}
*/
@Deprecated
private List<String> searchDocumentsNamesInternal(String sql, int nb, int start, List parameterValues,
XWikiContext context) throws XWikiException
{
List<String> documentNames = new ArrayList<String>();
for (DocumentReference reference : searchDocumentReferencesInternal(sql, nb, start, parameterValues, context)) {
documentNames.add(this.compactWikiEntityReferenceSerializer.serialize(reference));
}
return documentNames;
}
/**
* @since 2.2M1
*/
private List<DocumentReference> searchDocumentReferencesInternal(String sql, int nb, int start,
List<?> parameterValues, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
List<DocumentReference> documentReferences = new ArrayList<DocumentReference>();
// Construct a reference, using the current wiki as the wiki reference name. This is because the wiki
// name is not stored in the database for document references.
WikiReference wikiReference = new WikiReference(context.getWikiId());
for (Object result : this.searchGenericInternal(sql, nb, start, parameterValues, context)) {
// The select always contains several elements in case of order by so we have to support both Object[]
// and
// String
String referenceString;
if (result instanceof String) {
referenceString = (String) result;
} else {
referenceString = (String) ((Object[]) result)[0];
}
DocumentReference reference =
this.defaultDocumentReferenceResolver.resolve(referenceString, wikiReference);
documentReferences.add(reference);
}
return documentReferences;
} finally {
restoreExecutionXContext();
}
}
/**
* @since 2.2M1
*/
private <T> List<T> searchGenericInternal(String sql, int nb, int start, List<?> parameterValues,
XWikiContext context) throws XWikiException
{
boolean bTransaction = false;
MonitorPlugin monitor = Util.getMonitorPlugin(context);
try {
// Start monitoring timer
if (monitor != null) {
monitor.startTimer(HINT, sql);
}
checkHibernate(context);
bTransaction = beginTransaction(false, context);
Session session = getSession(context);
Query query = session.createQuery(filterSQL(sql));
injectParameterListToQuery(0, query, parameterValues);
if (start != 0) {
query.setFirstResult(start);
}
if (nb != 0) {
query.setMaxResults(nb);
}
Iterator it = query.list().iterator();
List list = new ArrayList<>();
while (it.hasNext()) {
list.add(it.next());
}
return list;
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCH, "Exception while searching documents with SQL [{0}]",
e, new Object[] { sql });
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
// End monitoring timer
if (monitor != null) {
monitor.endTimer(HINT);
}
}
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, boolean customMapping,
boolean checkRight, int nb, int start, XWikiContext context) throws XWikiException
{
return searchDocuments(wheresql, distinctbylanguage, customMapping, checkRight, nb, start, null, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, boolean customMapping,
boolean checkRight, int nb, int start, List<?> parameterValues, XWikiContext inputxcontext)
throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
// Search documents
List documentDatas = new ArrayList();
boolean bTransaction = true;
MonitorPlugin monitor = Util.getMonitorPlugin(context);
try {
String sql;
if (distinctbylanguage) {
sql = createSQLQuery("select distinct doc.fullName, doc.language", wheresql);
} else {
sql = createSQLQuery("select distinct doc.fullName", wheresql);
}
// Start monitoring timer
if (monitor != null) {
monitor.startTimer(HINT, sql);
}
checkHibernate(context);
if (bTransaction) {
// Inject everything until we know what's needed
SessionFactory sfactory =
customMapping ? injectCustomMappingsInSessionFactory(context) : getSessionFactory();
bTransaction = beginTransaction(sfactory, context);
}
Session session = getSession(context);
Query query = session.createQuery(filterSQL(sql));
injectParameterListToQuery(0, query, parameterValues);
if (start != 0) {
query.setFirstResult(start);
}
if (nb != 0) {
query.setMaxResults(nb);
}
documentDatas.addAll(query.list());
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCH, "Exception while searching documents with SQL [{0}]",
e, new Object[] { wheresql });
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
// End monitoring timer
if (monitor != null) {
monitor.endTimer(HINT);
}
}
// Resolve documents. We use two separated sessions because rights service could need to switch database to
// check rights
List<XWikiDocument> documents = new ArrayList<>();
WikiReference currentWikiReference = new WikiReference(context.getWikiId());
for (Object result : documentDatas) {
String fullName;
String locale = null;
if (result instanceof String) {
fullName = (String) result;
} else {
fullName = (String) ((Object[]) result)[0];
if (distinctbylanguage) {
locale = (String) ((Object[]) result)[1];
}
}
XWikiDocument doc =
new XWikiDocument(this.defaultDocumentReferenceResolver.resolve(fullName, currentWikiReference));
if (checkRight) {
if (!context.getWiki().getRightService().hasAccessLevel("view", context.getUser(), doc.getFullName(),
context)) {
continue;
}
}
DocumentReference documentReference = doc.getDocumentReference();
if (distinctbylanguage) {
XWikiDocument document = context.getWiki().getDocument(documentReference, context);
if (StringUtils.isEmpty(locale)) {
documents.add(document);
} else {
documents.add(document.getTranslatedDocument(locale, context));
}
} else {
documents.add(context.getWiki().getDocument(documentReference, context));
}
}
return documents;
}
/**
* @param queryPrefix the start of the SQL query (for example "select distinct doc.space, doc.name")
* @param whereSQL the where clause to append
* @return the full formed SQL query, to which the order by columns have been added as returned columns (this is
* required for example for HSQLDB).
*/
protected String createSQLQuery(String queryPrefix, String whereSQL)
{
StringBuilder sql = new StringBuilder(queryPrefix);
String normalizedWhereSQL;
if (StringUtils.isBlank(whereSQL)) {
normalizedWhereSQL = "";
} else {
normalizedWhereSQL = whereSQL.trim();
}
sql.append(getColumnsForSelectStatement(normalizedWhereSQL));
sql.append(" from XWikiDocument as doc");
if (!normalizedWhereSQL.equals("")) {
if ((!normalizedWhereSQL.startsWith("where")) && (!normalizedWhereSQL.startsWith(","))) {
sql.append(" where ");
} else {
sql.append(" ");
}
sql.append(normalizedWhereSQL);
}
return sql.toString();
}
/**
* @param whereSQL the SQL where clause
* @return the list of columns to return in the select clause as a string starting with ", " if there are columns or
* an empty string otherwise. The returned columns are extracted from the where clause. One reason for doing
* so is because HSQLDB only support SELECT DISTINCT SQL statements where the columns operated on are
* returned from the query.
*/
protected String getColumnsForSelectStatement(String whereSQL)
{
StringBuilder columns = new StringBuilder();
int orderByPos = whereSQL.toLowerCase().indexOf("order by");
if (orderByPos >= 0) {
String orderByStatement = whereSQL.substring(orderByPos + "order by".length() + 1);
StringTokenizer tokenizer = new StringTokenizer(orderByStatement, ",");
while (tokenizer.hasMoreTokens()) {
String column = tokenizer.nextToken().trim();
// Remove "desc" or "asc" from the column found
column = StringUtils.removeEndIgnoreCase(column, " desc");
column = StringUtils.removeEndIgnoreCase(column, " asc");
columns.append(", ").append(column.trim());
}
}
return columns.toString();
}
@Override
public boolean isCustomMappingValid(BaseClass bclass, String custommapping1, XWikiContext context)
{
try {
Configuration hibconfig = getMapping(bclass.getName(), custommapping1);
return isValidCustomMapping(bclass, hibconfig);
} catch (Exception e) {
return false;
}
}
private SessionFactory injectCustomMappingsInSessionFactory(XWikiDocument doc, XWikiContext context)
throws XWikiException
{
// If we haven't turned of dynamic custom mappings we should not inject them
if (!context.getWiki().hasDynamicCustomMappings()) {
return getSessionFactory();
}
boolean result = injectCustomMappings(doc, context);
if (!result) {
return getSessionFactory();
}
Configuration config = getConfiguration();
SessionFactoryImpl sfactory = (SessionFactoryImpl) config.buildSessionFactory();
Settings settings = sfactory.getSettings();
ConnectionProvider provider = ((SessionFactoryImpl) getSessionFactory()).getSettings().getConnectionProvider();
Field field = null;
try {
field = settings.getClass().getDeclaredField("connectionProvider");
field.setAccessible(true);
field.set(settings, provider);
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_MAPPING_INJECTION_FAILED, "Mapping injection failed", e);
}
return sfactory;
}
@Override
public void injectCustomMappings(XWikiContext context) throws XWikiException
{
SessionFactory sfactory = injectCustomMappingsInSessionFactory(context);
setSessionFactory(sfactory);
}
@Override
public void injectUpdatedCustomMappings(XWikiContext context) throws XWikiException
{
Configuration config = getConfiguration();
setSessionFactory(injectInSessionFactory(config));
}
public SessionFactory injectCustomMappingsInSessionFactory(BaseClass bclass, XWikiContext context)
throws XWikiException
{
boolean result = injectCustomMapping(bclass, context);
if (result == false) {
return getSessionFactory();
}
Configuration config = getConfiguration();
return injectInSessionFactory(config);
}
private SessionFactory injectInSessionFactory(Configuration config) throws XWikiException
{
SessionFactoryImpl sfactory = (SessionFactoryImpl) config.buildSessionFactory();
Settings settings = sfactory.getSettings();
ConnectionProvider provider = ((SessionFactoryImpl) getSessionFactory()).getSettings().getConnectionProvider();
Field field = null;
try {
field = settings.getClass().getDeclaredField("connectionProvider");
field.setAccessible(true);
field.set(settings, provider);
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_MAPPING_INJECTION_FAILED, "Mapping injection failed", e);
}
return sfactory;
}
public SessionFactory injectCustomMappingsInSessionFactory(XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
// If we haven't turned of dynamic custom mappings we should not inject them
if (context.getWiki().hasDynamicCustomMappings() == false) {
return getSessionFactory();
}
List<XWikiDocument> list;
list = searchDocuments(" where (doc.xWikiClassXML is not null and doc.xWikiClassXML like '<%')", true,
false, false, 0, 0, context);
boolean result = false;
for (XWikiDocument doc : list) {
if (!doc.getXClass().getFieldList().isEmpty()) {
result |= injectCustomMapping(doc.getXClass(), context);
}
}
if (!result) {
return getSessionFactory();
}
Configuration config = getConfiguration();
return injectInSessionFactory(config);
} finally {
restoreExecutionXContext();
}
}
@Override
public boolean injectCustomMappings(XWikiDocument doc, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
// If we haven't turned of dynamic custom mappings we should not inject them
if (context.getWiki().hasDynamicCustomMappings() == false) {
return false;
}
boolean result = false;
for (List<BaseObject> objectsOfType : doc.getXObjects().values()) {
for (BaseObject object : objectsOfType) {
if (object != null) {
result |= injectCustomMapping(object.getXClass(context), context);
// Each class must be mapped only once
break;
}
}
}
return result;
} finally {
restoreExecutionXContext();
}
}
/**
* @param className the name of the class to map
* @param custommapping the custom mapping to inject for this class
* @param inputxcontext the current XWikiContext
* @return a boolean indicating if the mapping has been added to the current hibernate configuration, and a reload
* of the factory is required.
* @throws XWikiException if an error occurs
* @since 4.0M1
*/
public boolean injectCustomMapping(String className, String custommapping, XWikiContext inputxcontext)
throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
// If we haven't turned of dynamic custom mappings we should not inject them
if (!context.getWiki().hasDynamicCustomMappings()) {
return false;
}
Configuration config = getConfiguration();
// don't add a mapping that's already there
if (config.getClassMapping(className) != null) {
return false;
}
config.addXML(makeMapping(className, custommapping));
config.buildMappings();
return true;
} finally {
restoreExecutionXContext();
}
}
@Override
public boolean injectCustomMapping(BaseClass doc1class, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
if (!doc1class.hasExternalCustomMapping()) {
return false;
}
if (injectCustomMapping(doc1class.getName(), doc1class.getCustomMapping(), context)) {
if (!isValidCustomMapping(doc1class, getConfiguration())) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_INVALID_MAPPING, "Invalid Custom Mapping");
}
return true;
}
return false;
} finally {
restoreExecutionXContext();
}
}
private boolean isValidCustomMapping(BaseClass bclass, Configuration config)
{
PersistentClass mapping = config.getClassMapping(bclass.getName());
if (mapping == null) {
return true;
}
Iterator it = mapping.getPropertyIterator();
while (it.hasNext()) {
Property hibprop = (Property) it.next();
String propname = hibprop.getName();
PropertyClass propclass = (PropertyClass) bclass.getField(propname);
if (propclass == null) {
this.logger.warn("Mapping contains invalid field name [{}]", propname);
return false;
}
boolean result = isValidColumnType(hibprop.getValue().getType().getName(), propclass.getClassName());
if (result == false) {
this.logger.warn("Mapping contains invalid type in field [{}]", propname);
return false;
}
}
return true;
}
@Override
public List<String> getCustomMappingPropertyList(BaseClass bclass)
{
List<String> list = new ArrayList<>();
Configuration hibconfig;
if (bclass.hasExternalCustomMapping()) {
hibconfig = getMapping(bclass.getName(), bclass.getCustomMapping());
} else {
hibconfig = getConfiguration();
}
PersistentClass mapping = hibconfig.getClassMapping(bclass.getName());
if (mapping == null) {
return null;
}
Iterator it = mapping.getPropertyIterator();
while (it.hasNext()) {
Property hibprop = (Property) it.next();
String propname = hibprop.getName();
list.add(propname);
}
return list;
}
private boolean isValidColumnType(String name, String className)
{
String[] validtypes = this.validTypesMap.get(className);
if (validtypes == null) {
return true;
} else {
return ArrayUtils.contains(validtypes, name);
}
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, XWikiContext context) throws XWikiException
{
return searchDocuments(wheresql, null, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, List<?> parameterValues, XWikiContext context)
throws XWikiException
{
return searchDocuments(wheresql, 0, 0, parameterValues, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, XWikiContext context)
throws XWikiException
{
return searchDocuments(wheresql, distinctbylanguage, 0, 0, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, boolean customMapping,
XWikiContext context) throws XWikiException
{
return searchDocuments(wheresql, distinctbylanguage, customMapping, 0, 0, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, int nb, int start, XWikiContext context)
throws XWikiException
{
return searchDocuments(wheresql, nb, start, null, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, int nb, int start, List<?> parameterValues,
XWikiContext context) throws XWikiException
{
return searchDocuments(wheresql, true, nb, start, parameterValues, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, int nb, int start,
List<?> parameterValues, XWikiContext context) throws XWikiException
{
return searchDocuments(wheresql, distinctbylanguage, false, nb, start, parameterValues, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, int nb, int start,
XWikiContext context) throws XWikiException
{
return searchDocuments(wheresql, distinctbylanguage, nb, start, null, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, boolean customMapping,
int nb, int start, XWikiContext context) throws XWikiException
{
return searchDocuments(wheresql, distinctbylanguage, customMapping, nb, start, null, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, boolean customMapping,
int nb, int start, List<?> parameterValues, XWikiContext context) throws XWikiException
{
return searchDocuments(wheresql, distinctbylanguage, customMapping, true, nb, start, parameterValues, context);
}
@Override
public List<String> getTranslationList(XWikiDocument doc, XWikiContext context) throws XWikiException
{
try {
return getTranslationList(doc.getDocumentReference());
} catch (QueryException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCH,
"Failed to retrieve the list of translations for [{0}]", e,
new Object[] { doc.getDocumentReference() });
}
}
private List<String> getTranslationList(DocumentReference documentReference) throws QueryException
{
// Note that the query is made to work with Oracle which treats empty strings as null.
String hql = "select doc.language from XWikiDocument as doc where doc.space = :space and doc.name = :name "
+ "and (doc.language <> '' or (doc.language is not null and '' is null))";
org.xwiki.query.Query query = getQueryManager().createQuery(hql, org.xwiki.query.Query.HQL);
query.setWiki(documentReference.getWikiReference().getName());
query.bindValue("space", this.localEntityReferenceSerializer.serialize(documentReference.getParent()));
query.bindValue("name", documentReference.getName());
return query.execute();
}
@Override
public QueryManager getQueryManager()
{
return this.queryManager;
}
/**
* This is in response to the fact that Hibernate interprets backslashes differently from the database. Our solution
* is to simply replace all instances of \ with \\ which makes the first backslash escape the second.
*
* @param sql the uncleaned sql.
* @return same as sql except it is guarenteed not to contain groups of odd numbers of backslashes.
* @since 2.4M1
*/
private String filterSQL(String sql)
{
return StringUtils.replace(sql, "\\", "\\\\");
}
private String getDefaultAttachmentContentStore(XWikiContext xcontext)
{
XWikiAttachmentStoreInterface store = xcontext.getWiki().getDefaultAttachmentContentStore();
if (store != null && store != this.attachmentContentStore) {
return store.getHint();
}
return null;
}
private String getDefaultAttachmentArchiveStore(XWikiContext xcontext)
{
AttachmentVersioningStore store = xcontext.getWiki().getDefaultAttachmentArchiveStore();
if (store != null && store != this.attachmentArchiveStore) {
return store.getHint();
}
return null;
}
private XWikiAttachmentStoreInterface getXWikiAttachmentStoreInterface(XWikiAttachment attachment)
throws ComponentLookupException
{
String storeHint = attachment.getContentStore();
if (storeHint != null && !storeHint.equals(HINT)) {
return this.componentManager.getInstance(XWikiAttachmentStoreInterface.class, storeHint);
}
return this.attachmentContentStore;
}
}
|
xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateStore.java
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki.store;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.EntityMode;
import org.hibernate.FlushMode;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Settings;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.impl.SessionFactoryImpl;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.slf4j.Logger;
import org.suigeneris.jrcs.rcs.Version;
import org.xwiki.bridge.event.ActionExecutingEvent;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.component.phase.InitializationException;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.DocumentReferenceResolver;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.EntityReferenceSerializer;
import org.xwiki.model.reference.SpaceReference;
import org.xwiki.model.reference.WikiReference;
import org.xwiki.observation.EventListener;
import org.xwiki.observation.ObservationManager;
import org.xwiki.observation.event.Event;
import org.xwiki.query.QueryException;
import org.xwiki.query.QueryManager;
import org.xwiki.store.UnexpectedException;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.doc.XWikiDocument.XWikiAttachmentToRemove;
import com.xpn.xwiki.doc.XWikiLink;
import com.xpn.xwiki.doc.XWikiLock;
import com.xpn.xwiki.doc.XWikiSpace;
import com.xpn.xwiki.internal.render.OldRendering;
import com.xpn.xwiki.monitor.api.MonitorPlugin;
import com.xpn.xwiki.objects.BaseCollection;
import com.xpn.xwiki.objects.BaseElement;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseProperty;
import com.xpn.xwiki.objects.BaseStringProperty;
import com.xpn.xwiki.objects.LargeStringProperty;
import com.xpn.xwiki.objects.ListProperty;
import com.xpn.xwiki.objects.PropertyInterface;
import com.xpn.xwiki.objects.StringProperty;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.objects.classes.PropertyClass;
import com.xpn.xwiki.objects.classes.StringClass;
import com.xpn.xwiki.objects.classes.TextAreaClass;
import com.xpn.xwiki.stats.impl.XWikiStats;
import com.xpn.xwiki.store.migration.MigrationRequiredException;
import com.xpn.xwiki.util.Util;
/**
* The XWiki Hibernate database driver.
*
* @version $Id$
*/
@Component
@Named(XWikiHibernateBaseStore.HINT)
@Singleton
public class XWikiHibernateStore extends XWikiHibernateBaseStore implements XWikiStoreInterface
{
@Inject
private Logger logger;
/**
* QueryManager for this store.
*/
@Inject
private QueryManager queryManager;
/** Needed so we can register an event to trap logout and delete held locks. */
@Inject
private ObservationManager observationManager;
/**
* Used to resolve a string into a proper Document Reference using the current document's reference to fill the
* blanks, except for the page name for which the default page name is used instead and for the wiki name for which
* the current wiki is used instead of the current document reference's wiki.
*/
@Inject
@Named("currentmixed")
private DocumentReferenceResolver<String> currentMixedDocumentReferenceResolver;
@Inject
private DocumentReferenceResolver<String> defaultDocumentReferenceResolver;
/**
* Used to convert a proper Document Reference to string (standard form).
*/
@Inject
private EntityReferenceSerializer<String> defaultEntityReferenceSerializer;
/**
* Used to convert a Document Reference to string (compact form without the wiki part).
*/
@Inject
@Named("compactwiki")
private EntityReferenceSerializer<String> compactWikiEntityReferenceSerializer;
/**
* Used to convert a proper Document Reference to a string but without the wiki name.
*/
@Inject
@Named("local")
private EntityReferenceSerializer<String> localEntityReferenceSerializer;
@Inject
private Provider<OldRendering> oldRenderingProvider;
@Inject
private ComponentManager componentManager;
@Inject
@Named(HINT)
private XWikiAttachmentStoreInterface attachmentContentStore;
@Inject
@Named(HINT)
private AttachmentVersioningStore attachmentArchiveStore;
private Map<String, String[]> validTypesMap = new HashMap<>();
/**
* This allows to initialize our storage engine. The hibernate config file path is taken from xwiki.cfg or directly
* in the WEB-INF directory.
*
* @param xwiki
* @param context
* @deprecated 1.6M1. Use ComponentManager.lookup(XWikiStoreInterface.class) instead.
*/
@Deprecated
public XWikiHibernateStore(XWiki xwiki, XWikiContext context)
{
super(xwiki, context);
initValidColumTypes();
}
/**
* Initialize the storage engine with a specific path. This is used for tests.
*
* @param hibpath
* @deprecated 1.6M1. Use ComponentManager.lookup(XWikiStoreInterface.class) instead.
*/
@Deprecated
public XWikiHibernateStore(String hibpath)
{
super(hibpath);
initValidColumTypes();
}
/**
* @see #XWikiHibernateStore(XWiki, XWikiContext)
* @deprecated 1.6M1. Use ComponentManager.lookup(XWikiStoreInterface.class) instead.
*/
@Deprecated
public XWikiHibernateStore(XWikiContext context)
{
this(context.getWiki(), context);
}
/**
* Empty constructor needed for component manager.
*/
public XWikiHibernateStore()
{
initValidColumTypes();
}
@Override
public void initialize() throws InitializationException
{
super.initialize();
this.registerLogoutListener();
}
/**
* This initializes the valid custom types Used for Custom Mapping
*/
private void initValidColumTypes()
{
String[] string_types = { "string", "text", "clob" };
String[] number_types =
{ "integer", "long", "float", "double", "big_decimal", "big_integer", "yes_no", "true_false" };
String[] date_types = { "date", "time", "timestamp" };
String[] boolean_types = { "boolean", "yes_no", "true_false", "integer" };
this.validTypesMap = new HashMap<>();
this.validTypesMap.put("com.xpn.xwiki.objects.classes.StringClass", string_types);
this.validTypesMap.put("com.xpn.xwiki.objects.classes.TextAreaClass", string_types);
this.validTypesMap.put("com.xpn.xwiki.objects.classes.PasswordClass", string_types);
this.validTypesMap.put("com.xpn.xwiki.objects.classes.NumberClass", number_types);
this.validTypesMap.put("com.xpn.xwiki.objects.classes.DateClass", date_types);
this.validTypesMap.put("com.xpn.xwiki.objects.classes.BooleanClass", boolean_types);
}
@Override
public boolean isWikiNameAvailable(String wikiName, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, false);
boolean available;
boolean bTransaction = true;
String database = context.getWikiId();
try {
bTransaction = beginTransaction(context);
Session session = getSession(context);
// Capture Logs since we voluntarily generate storage errors to check if the wiki already exists and
// we don't want to pollute application logs with "normal errors"...
if (!this.logger.isDebugEnabled()) {
this.loggerManager.pushLogListener(null);
}
context.setWikiId(wikiName);
try {
setDatabase(session, context);
available = false;
} catch (XWikiException e) {
// Failed to switch to database. Assume it means database does not exists.
available = !(e.getCause() instanceof MigrationRequiredException);
}
} catch (Exception e) {
Object[] args = { wikiName };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_CHECK_EXISTS_DATABASE,
"Exception while listing databases to search for {0}", e, args);
} finally {
context.setWikiId(database);
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
// Restore proper logging
if (!this.logger.isDebugEnabled()) {
this.loggerManager.popLogListener();
}
}
return available;
}
@Override
public void createWiki(String wikiName, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, false);
boolean bTransaction = true;
String database = context.getWikiId();
Statement stmt = null;
try {
bTransaction = beginTransaction(context);
Session session = getSession(context);
Connection connection = session.connection();
stmt = connection.createStatement();
String schema = getSchemaFromWikiName(wikiName, context);
String escapedSchema = escapeSchema(schema, context);
DatabaseProduct databaseProduct = getDatabaseProductName();
if (DatabaseProduct.ORACLE == databaseProduct) {
stmt.execute("create user " + escapedSchema + " identified by " + escapedSchema);
stmt.execute("grant resource to " + escapedSchema);
} else if (DatabaseProduct.DERBY == databaseProduct || DatabaseProduct.DB2 == databaseProduct
|| DatabaseProduct.H2 == databaseProduct) {
stmt.execute("CREATE SCHEMA " + escapedSchema);
} else if (DatabaseProduct.HSQLDB == databaseProduct) {
stmt.execute("CREATE SCHEMA " + escapedSchema + " AUTHORIZATION DBA");
} else if (DatabaseProduct.MYSQL == databaseProduct) {
// TODO: find a proper java lib to convert from java encoding to mysql charset name and collation
if (context.getWiki().getEncoding().equals("UTF-8")) {
stmt.execute("create database " + escapedSchema + " CHARACTER SET utf8 COLLATE utf8_bin");
} else {
stmt.execute("create database " + escapedSchema);
}
} else if (DatabaseProduct.POSTGRESQL == databaseProduct) {
if (isInSchemaMode()) {
stmt.execute("CREATE SCHEMA " + escapedSchema);
} else {
this.logger.error("Creation of a new database is currently only supported in the schema mode, "
+ "see https://jira.xwiki.org/browse/XWIKI-8753");
}
} else {
stmt.execute("create database " + escapedSchema);
}
endTransaction(context, true);
} catch (Exception e) {
Object[] args = { wikiName };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_CREATE_DATABASE, "Exception while create wiki database {0}",
e, args);
} finally {
context.setWikiId(database);
try {
if (stmt != null) {
stmt.close();
}
} catch (Exception e) {
}
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
}
}
@Override
public void deleteWiki(String wikiName, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, false);
boolean bTransaction = true;
String database = context.getWikiId();
Statement stmt = null;
try {
bTransaction = beginTransaction(context);
Session session = getSession(context);
Connection connection = session.connection();
stmt = connection.createStatement();
String schema = getSchemaFromWikiName(wikiName, context);
String escapedSchema = escapeSchema(schema, context);
executeDeleteWikiStatement(stmt, getDatabaseProductName(), escapedSchema);
endTransaction(context, true);
} catch (Exception e) {
Object[] args = { wikiName };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_DELETE_DATABASE, "Exception while delete wiki database {0}",
e, args);
} finally {
context.setWikiId(database);
try {
if (stmt != null) {
stmt.close();
}
} catch (Exception e) {
}
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
}
}
/**
* Execute the SQL statement on the database to remove a wiki.
*
* @param statement the statement object on which to execute the wiki deletion
* @param databaseProduct the database type
* @param escapedSchemaName the subwiki schema name being deleted
* @throws SQLException in case of an error while deleting the sub wiki
*/
protected void executeDeleteWikiStatement(Statement statement, DatabaseProduct databaseProduct,
String escapedSchemaName) throws SQLException
{
if (DatabaseProduct.ORACLE == databaseProduct) {
statement.execute("DROP USER " + escapedSchemaName + " CASCADE");
} else if (DatabaseProduct.DERBY == databaseProduct || DatabaseProduct.MYSQL == databaseProduct
|| DatabaseProduct.H2 == databaseProduct) {
statement.execute("DROP SCHEMA " + escapedSchemaName);
} else if (DatabaseProduct.HSQLDB == databaseProduct) {
statement.execute("DROP SCHEMA " + escapedSchemaName + " CASCADE");
} else if (DatabaseProduct.DB2 == databaseProduct) {
statement.execute("DROP SCHEMA " + escapedSchemaName + " RESTRICT");
} else if (DatabaseProduct.POSTGRESQL == databaseProduct) {
if (isInSchemaMode()) {
statement.execute("DROP SCHEMA " + escapedSchemaName + " CASCADE");
} else {
this.logger.warn("Subwiki deletion not yet supported in Database mode for PostgreSQL");
}
}
}
/**
* Verifies if a wiki document exists
*/
@Override
public boolean exists(XWikiDocument doc, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
boolean bTransaction = true;
MonitorPlugin monitor = Util.getMonitorPlugin(context);
try {
doc.setStore(this);
checkHibernate(context);
// Start monitoring timer
if (monitor != null) {
monitor.startTimer(HINT);
}
bTransaction = bTransaction && beginTransaction(null, context);
Session session = getSession(context);
String fullName = doc.getFullName();
String sql = "select doc.fullName from XWikiDocument as doc where doc.fullName=:fullName";
if (!doc.getLocale().equals(Locale.ROOT)) {
sql += " and doc.language=:language";
}
if (monitor != null) {
monitor.setTimerDesc(HINT, sql);
}
Query query = session.createQuery(sql);
query.setString("fullName", fullName);
if (!doc.getLocale().equals(Locale.ROOT)) {
query.setString("language", doc.getLocale().toString());
}
Iterator<String> it = query.list().iterator();
while (it.hasNext()) {
if (fullName.equals(it.next())) {
return true;
}
}
return false;
} catch (Exception e) {
Object[] args = { doc.getDocumentReferenceWithLocale() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_CHECK_EXISTS_DOC, "Exception while reading document {0}",
e, args);
} finally {
// End monitoring timer
if (monitor != null) {
monitor.endTimer(HINT);
}
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
}
} finally {
restoreExecutionXContext();
}
}
@Override
public void saveXWikiDoc(XWikiDocument doc, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
MonitorPlugin monitor = Util.getMonitorPlugin(context);
try {
// Start monitoring timer
if (monitor != null) {
monitor.startTimer(HINT);
}
doc.setStore(this);
// Make sure the database name is stored
doc.setDatabase(context.getWikiId());
// If the comment is larger than the max size supported by the Storage, then abbreviate it
String comment = doc.getComment();
if (comment != null && comment.length() > 1023) {
doc.setComment(StringUtils.abbreviate(comment, 1023));
}
if (bTransaction) {
checkHibernate(context);
SessionFactory sfactory = injectCustomMappingsInSessionFactory(doc, context);
bTransaction = beginTransaction(sfactory, context);
}
Session session = getSession(context);
session.setFlushMode(FlushMode.COMMIT);
// These informations will allow to not look for attachments and objects on loading
doc.setElement(XWikiDocument.HAS_ATTACHMENTS, !doc.getAttachmentList().isEmpty());
doc.setElement(XWikiDocument.HAS_OBJECTS, !doc.getXObjects().isEmpty());
// Let's update the class XML since this is the new way to store it
// TODO If all the properties are removed, the old xml stays?
BaseClass bclass = doc.getXClass();
if (bclass != null) {
if (bclass.getFieldList().isEmpty()) {
doc.setXClassXML("");
} else {
// Don't format the XML to reduce the size of the stored data as much as possible
doc.setXClassXML(bclass.toXMLString(false));
}
bclass.setDirty(false);
}
if (doc.hasElement(XWikiDocument.HAS_ATTACHMENTS)) {
saveAttachmentList(doc, context);
}
// Remove attachments planned for removal
if (!doc.getAttachmentsToRemove().isEmpty()) {
for (XWikiAttachmentToRemove attachmentToRemove : doc.getAttachmentsToRemove()) {
XWikiAttachment attachment = attachmentToRemove.getAttachment();
XWikiAttachmentStoreInterface store = getXWikiAttachmentStoreInterface(attachment);
store.deleteXWikiAttachment(attachment, false, context, false);
}
doc.clearAttachmentsToRemove();
}
// Handle the latest text file
if (doc.isContentDirty() || doc.isMetaDataDirty()) {
Date ndate = new Date();
doc.setDate(ndate);
if (doc.isContentDirty()) {
doc.setContentUpdateDate(ndate);
doc.setContentAuthorReference(doc.getAuthorReference());
}
doc.incrementVersion();
if (context.getWiki().hasVersioning(context)) {
context.getWiki().getVersioningStore().updateXWikiDocArchive(doc, false, context);
}
doc.setContentDirty(false);
doc.setMetaDataDirty(false);
} else {
if (doc.getDocumentArchive() != null) {
// A custom document archive has been provided, we assume it's right
// (we also assume it's custom but that's another matter...)
// Let's make sure we save the archive if we have one
// This is especially needed if we load a document from XML
if (context.getWiki().hasVersioning(context)) {
context.getWiki().getVersioningStore().saveXWikiDocArchive(doc.getDocumentArchive(), false,
context);
// If the version does not exist it means it's a new version so add it to the history
if (!containsVersion(doc, doc.getRCSVersion(), context)) {
context.getWiki().getVersioningStore().updateXWikiDocArchive(doc, false, context);
}
}
} else {
// Make sure the getArchive call has been made once
// with a valid context
try {
if (context.getWiki().hasVersioning(context)) {
doc.getDocumentArchive(context);
// If the version does not exist it means it's a new version so register it in the
// history
if (!containsVersion(doc, doc.getRCSVersion(), context)) {
context.getWiki().getVersioningStore().updateXWikiDocArchive(doc, false, context);
}
}
} catch (XWikiException e) {
// this is a non critical error
}
}
}
// Verify if the document already exists
Query query =
session.createQuery("select xwikidoc.id from XWikiDocument as xwikidoc where xwikidoc.id = :id");
query.setLong("id", doc.getId());
// Note: we don't use session.saveOrUpdate(doc) because it used to be slower in Hibernate than calling
// session.save() and session.update() separately.
if (query.uniqueResult() == null) {
if (doc.isContentDirty() || doc.isMetaDataDirty()) {
// Reset the creationDate to reflect the date of the first save, not the date of the object
// creation
doc.setCreationDate(new Date());
}
session.save(doc);
} else {
session.update(doc);
}
// Remove objects planned for removal
if (doc.getXObjectsToRemove().size() > 0) {
for (BaseObject removedObject : doc.getXObjectsToRemove()) {
deleteXWikiCollection(removedObject, context, false, false);
}
doc.setXObjectsToRemove(new ArrayList<BaseObject>());
}
if (bclass != null) {
bclass.setDocumentReference(doc.getDocumentReference());
// Store this XWikiClass in the context so that we can use it in case of recursive usage of classes
context.addBaseClass(bclass);
}
if (doc.hasElement(XWikiDocument.HAS_OBJECTS)) {
// TODO: Delete all objects for which we don't have a name in the Map
for (List<BaseObject> objects : doc.getXObjects().values()) {
for (BaseObject obj : objects) {
if (obj != null) {
obj.setDocumentReference(doc.getDocumentReference());
/* If the object doesn't have a GUID, create it before saving */
if (StringUtils.isEmpty(obj.getGuid())) {
obj.setGuid(null);
}
saveXWikiCollection(obj, context, false);
}
}
}
}
if (context.getWiki().hasBacklinks(context)) {
try {
saveLinks(doc, context, true);
} catch (Exception e) {
this.logger.error("Failed to save links for document [{}]",
doc.getDocumentReferenceWithLocale(), e);
}
}
// Update space table
updateXWikiSpaceTable(doc, session);
if (bTransaction) {
endTransaction(context, true);
}
doc.setNew(false);
// We need to ensure that the saved document becomes the original document
doc.setOriginalDocument(doc.clone());
} catch (Exception e) {
Object[] args = { this.defaultEntityReferenceSerializer.serialize(doc.getDocumentReference()) };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_DOC, "Exception while saving document {0}", e,
args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
// End monitoring timer
if (monitor != null) {
monitor.endTimer(HINT);
}
}
} finally {
restoreExecutionXContext();
}
}
private void updateXWikiSpaceTable(XWikiDocument document, Session session)
{
if (document.getLocale().equals(Locale.ROOT)) {
if (!document.isNew()) {
// If the hidden state of an existing document did not changed there is nothing to do
if (document.isHidden() != document.getOriginalDocument().isHidden()) {
if (document.isHidden()) {
// If the document became hidden it's possible the space did too
maybeMakeSpaceHidden(document.getDocumentReference().getLastSpaceReference(),
document.getFullName(), session);
} else {
// If the document became visible then all its parents should be visible as well
makeSpaceVisible(document.getDocumentReference().getLastSpaceReference(), session);
}
}
} else {
// It's possible the space of a new document does not yet exist
maybeCreateSpace(document.getDocumentReference().getLastSpaceReference(), document.isHidden(),
document.getFullName(), session);
}
}
}
private void insertXWikiSpace(XWikiSpace space, String newDocument, Session session)
{
// Insert the space
session.save(space);
// Update parent space
if (space.getSpaceReference().getParent() instanceof SpaceReference) {
maybeCreateSpace((SpaceReference) space.getSpaceReference().getParent(), space.isHidden(), newDocument,
session);
}
}
private void makeSpaceVisible(SpaceReference spaceReference, Session session)
{
XWikiSpace space = loadXWikiSpace(spaceReference, session);
makeSpaceVisible(space, session);
}
private void makeSpaceVisible(XWikiSpace space, Session session)
{
if (space.isHidden()) {
space.setHidden(false);
session.update(space);
// Update parent
if (space.getSpaceReference().getParent() instanceof SpaceReference) {
makeSpaceVisible((SpaceReference) space.getSpaceReference().getParent(), session);
}
}
}
private void maybeMakeSpaceHidden(SpaceReference spaceReference, String modifiedDocument, Session session)
{
XWikiSpace space = loadXWikiSpace(spaceReference, session);
// The space is supposed to exist
if (space == null) {
this.logger.warn(
"Space [{}] does not exist. Usually means the spaces table is not in sync with the documents table.",
spaceReference);
return;
}
// If the space is already hidden return
if (space.isHidden()) {
return;
}
if (calculateHiddenStatus(spaceReference, modifiedDocument, session)) {
// Make the space hidden
space.setHidden(true);
session.update(space);
// Update space parent
if (spaceReference.getParent() instanceof SpaceReference) {
maybeMakeSpaceHidden((SpaceReference) spaceReference.getParent(), modifiedDocument, session);
}
}
}
private void maybeCreateSpace(SpaceReference spaceReference, boolean hidden, String newDocument, Session session)
{
XWikiSpace space = loadXWikiSpace(spaceReference, session);
if (space != null) {
if (space.isHidden() && !hidden) {
makeSpaceVisible(space, session);
}
} else {
insertXWikiSpace(new XWikiSpace(spaceReference, hidden), newDocument, session);
}
}
private long countAllDocuments(SpaceReference spaceReference, Session session, String extraWhere,
Object... extraParameters)
{
StringBuilder builder =
new StringBuilder("select count(*) from XWikiDocument as xwikidoc where (space = ? OR space LIKE ?)");
if (StringUtils.isNotEmpty(extraWhere)) {
builder.append(" AND ");
builder.append('(');
builder.append(extraWhere);
builder.append(')');
}
Query query = session.createQuery(builder.toString());
String localSpaceReference = this.localEntityReferenceSerializer.serialize(spaceReference);
int index = 0;
query.setString(index++, localSpaceReference);
query.setString(index++, localSpaceReference + ".%");
if (extraParameters != null) {
for (Object parameter : extraParameters) {
query.setParameter(index++, parameter);
}
}
return (Long) query.uniqueResult();
}
/**
* Find hidden status of a space from its children.
*/
private boolean calculateHiddenStatus(SpaceReference spaceReference, String documentToIngore, Session session)
{
// If there is at least one visible document then the space is visible
StringBuilder builder = new StringBuilder("(hidden = false OR hidden IS NULL)");
Object[] parameters;
if (documentToIngore != null) {
builder.append(" AND fullName <> ?");
parameters = new Object[] { documentToIngore };
} else {
parameters = null;
}
return !(countAllDocuments(spaceReference, session, builder.toString(), parameters) > 0);
}
private boolean containsVersion(XWikiDocument doc, Version targetversion, XWikiContext context)
throws XWikiException
{
for (Version version : doc.getRevisions(context)) {
if (version.equals(targetversion)) {
return true;
}
}
return false;
}
@Override
public void saveXWikiDoc(XWikiDocument doc, XWikiContext context) throws XWikiException
{
saveXWikiDoc(doc, context, true);
}
@Override
public XWikiDocument loadXWikiDoc(XWikiDocument doc, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
// To change body of implemented methods use Options | File Templates.
boolean bTransaction = true;
MonitorPlugin monitor = Util.getMonitorPlugin(context);
try {
// Start monitoring timer
if (monitor != null) {
monitor.startTimer(HINT);
}
doc.setStore(this);
checkHibernate(context);
SessionFactory sfactory = injectCustomMappingsInSessionFactory(doc, context);
bTransaction = bTransaction && beginTransaction(sfactory, context);
Session session = getSession(context);
session.setFlushMode(FlushMode.MANUAL);
try {
session.load(doc, Long.valueOf(doc.getId()));
doc.setNew(false);
doc.setMostRecent(true);
// Fix for XWIKI-1651
doc.setDate(new Date(doc.getDate().getTime()));
doc.setCreationDate(new Date(doc.getCreationDate().getTime()));
doc.setContentUpdateDate(new Date(doc.getContentUpdateDate().getTime()));
} catch (ObjectNotFoundException e) { // No document
doc.setNew(true);
// Make sure to always return a document with an original version, even for one that does not exist.
// Allow writing more generic code.
doc.setOriginalDocument(new XWikiDocument(doc.getDocumentReference(), doc.getLocale()));
return doc;
}
// Loading the attachment list
if (doc.hasElement(XWikiDocument.HAS_ATTACHMENTS)) {
loadAttachmentList(doc, context, false);
}
// TODO: handle the case where there are no xWikiClass and xWikiObject in the Database
BaseClass bclass = new BaseClass();
String cxml = doc.getXClassXML();
if (cxml != null) {
bclass.fromXML(cxml);
doc.setXClass(bclass);
bclass.setDirty(false);
}
// Store this XWikiClass in the context so that we can use it in case of recursive usage
// of classes
context.addBaseClass(bclass);
if (doc.hasElement(XWikiDocument.HAS_OBJECTS)) {
Query query = session
.createQuery("from BaseObject as bobject where bobject.name = :name order by bobject.number");
query.setText("name", doc.getFullName());
@SuppressWarnings("unchecked")
Iterator<BaseObject> it = query.list().iterator();
EntityReference localGroupEntityReference = new EntityReference("XWikiGroups", EntityType.DOCUMENT,
new EntityReference("XWiki", EntityType.SPACE));
DocumentReference groupsDocumentReference = new DocumentReference(context.getWikiId(),
localGroupEntityReference.getParent().getName(), localGroupEntityReference.getName());
boolean hasGroups = false;
while (it.hasNext()) {
BaseObject object = it.next();
DocumentReference classReference = object.getXClassReference();
if (classReference == null) {
continue;
}
// It seems to search before is case insensitive. And this would break the loading if we get an
// object which doesn't really belong to this document
if (!object.getDocumentReference().equals(doc.getDocumentReference())) {
continue;
}
BaseObject newobject;
if (classReference.equals(doc.getDocumentReference())) {
newobject = bclass.newCustomClassInstance(context);
} else {
newobject = BaseClass.newCustomClassInstance(classReference, context);
}
if (newobject != null) {
newobject.setId(object.getId());
newobject.setXClassReference(object.getRelativeXClassReference());
newobject.setDocumentReference(object.getDocumentReference());
newobject.setNumber(object.getNumber());
newobject.setGuid(object.getGuid());
object = newobject;
}
if (classReference.equals(groupsDocumentReference)) {
// Groups objects are handled differently.
hasGroups = true;
} else {
loadXWikiCollectionInternal(object, doc, context, false, true);
}
doc.setXObject(object.getNumber(), object);
}
// AFAICT this was added as an emergency patch because loading of objects has proven
// too slow and the objects which cause the most overhead are the XWikiGroups objects
// as each group object (each group member) would otherwise cost 2 database queries.
// This will do every group member in a single query.
if (hasGroups) {
Query query2 =
session.createQuery("select bobject.number, prop.value from StringProperty as prop,"
+ "BaseObject as bobject where bobject.name = :name and bobject.className='XWiki.XWikiGroups' "
+ "and bobject.id=prop.id.id and prop.id.name='member' order by bobject.number");
query2.setText("name", doc.getFullName());
@SuppressWarnings("unchecked")
Iterator<Object[]> it2 = query2.list().iterator();
while (it2.hasNext()) {
Object[] result = it2.next();
Integer number = (Integer) result[0];
String member = (String) result[1];
BaseObject obj = BaseClass.newCustomClassInstance(groupsDocumentReference, context);
obj.setDocumentReference(doc.getDocumentReference());
obj.setXClassReference(localGroupEntityReference);
obj.setNumber(number.intValue());
obj.setStringValue("member", member);
doc.setXObject(obj.getNumber(), obj);
}
}
}
doc.setContentDirty(false);
doc.setMetaDataDirty(false);
// We need to ensure that the loaded document becomes the original document
doc.setOriginalDocument(doc.clone());
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
Object[] args = { doc.getDocumentReference() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_READING_DOC, "Exception while reading document [{0}]", e,
args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
// End monitoring timer
if (monitor != null) {
monitor.endTimer(HINT);
}
}
this.logger.debug("Loaded XWikiDocument: [{}]", doc.getDocumentReference());
return doc;
} finally {
restoreExecutionXContext();
}
}
@Override
public void deleteXWikiDoc(XWikiDocument doc, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
boolean bTransaction = true;
MonitorPlugin monitor = Util.getMonitorPlugin(context);
try {
// Start monitoring timer
if (monitor != null) {
monitor.startTimer(HINT);
}
checkHibernate(context);
SessionFactory sfactory = injectCustomMappingsInSessionFactory(doc, context);
bTransaction = bTransaction && beginTransaction(sfactory, context);
Session session = getSession(context);
session.setFlushMode(FlushMode.COMMIT);
if (doc.getStore() == null) {
Object[] args = { doc.getDocumentReference() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_CANNOT_DELETE_UNLOADED_DOC,
"Impossible to delete document {0} if it is not loaded", null, args);
}
// Let's delete any attachment this document might have
for (XWikiAttachment attachment : doc.getAttachmentList()) {
XWikiAttachmentStoreInterface store = getXWikiAttachmentStoreInterface(attachment);
store.deleteXWikiAttachment(attachment, false, context, false);
}
// deleting XWikiLinks
if (context.getWiki().hasBacklinks(context)) {
deleteLinks(doc.getId(), context, true);
}
// Find the list of classes for which we have an object
// Remove properties planned for removal
if (!doc.getXObjectsToRemove().isEmpty()) {
for (BaseObject bobj : doc.getXObjectsToRemove()) {
if (bobj != null) {
deleteXWikiCollection(bobj, context, false, false);
}
}
doc.setXObjectsToRemove(new ArrayList<BaseObject>());
}
for (List<BaseObject> objects : doc.getXObjects().values()) {
for (BaseObject obj : objects) {
if (obj != null) {
deleteXWikiCollection(obj, context, false, false);
}
}
}
context.getWiki().getVersioningStore().deleteArchive(doc, false, context);
session.delete(doc);
// We need to ensure that the deleted document becomes the original document
doc.setOriginalDocument(doc.clone());
// Update space table if needed
maybeDeleteXWikiSpace(doc, session);
if (bTransaction) {
endTransaction(context, true);
}
} catch (Exception e) {
Object[] args = { doc.getDocumentReference() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_DELETING_DOC, "Exception while deleting document {0}", e,
args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
// End monitoring timer
if (monitor != null) {
monitor.endTimer(HINT);
}
}
} finally {
restoreExecutionXContext();
}
}
private void maybeDeleteXWikiSpace(XWikiDocument deletedDocument, Session session)
{
if (deletedDocument.getLocale().equals(Locale.ROOT)) {
DocumentReference documentReference = deletedDocument.getDocumentReference();
maybeDeleteXWikiSpace(documentReference.getLastSpaceReference(),
this.localEntityReferenceSerializer.serialize(documentReference), session);
}
}
private void maybeDeleteXWikiSpace(SpaceReference spaceReference, String deletedDocument, Session session)
{
if (countAllDocuments(spaceReference, session, "fullName <> ? AND (language IS NULL OR language = '')",
deletedDocument) == 0) {
// The document was the last document in the space
XWikiSpace space = new XWikiSpace(spaceReference, this);
session.delete(space);
// Update parent
if (spaceReference.getParent() instanceof SpaceReference) {
maybeDeleteXWikiSpace((SpaceReference) spaceReference.getParent(), deletedDocument, session);
}
} else {
// Update space hidden property if needed
maybeMakeSpaceHidden(spaceReference, deletedDocument, session);
}
}
private XWikiSpace loadXWikiSpace(SpaceReference spaceReference, Session session)
{
XWikiSpace space = new XWikiSpace(spaceReference, this);
try {
session.load(space, Long.valueOf(space.getId()));
} catch (ObjectNotFoundException e) {
// No space
return null;
}
return space;
}
private void checkObjectClassIsLocal(BaseCollection object, XWikiContext context) throws XWikiException
{
DocumentReference xclass = object.getXClassReference();
WikiReference wikiReference = xclass.getWikiReference();
String db = context.getWikiId();
if (!wikiReference.getName().equals(db)) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_OBJECT,
"XObject [{0}] is an instance of an external XClass and cannot be persisted in this wiki [{1}].", null,
new Object[] { this.localEntityReferenceSerializer.serialize(object.getReference()), db });
}
}
/**
* @deprecated This is internal to XWikiHibernateStore and may be removed in the future.
*/
@Deprecated
public void saveXWikiCollection(BaseCollection object, XWikiContext inputxcontext, boolean bTransaction)
throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
if (object == null) {
return;
}
// We need a slightly different behavior here
boolean stats = (object instanceof XWikiStats);
if (!stats) {
checkObjectClassIsLocal(object, context);
}
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(context);
}
Session session = getSession(context);
// Verify if the property already exists
Query query;
if (stats) {
query = session
.createQuery("select obj.id from " + object.getClass().getName() + " as obj where obj.id = :id");
} else {
query = session.createQuery("select obj.id from BaseObject as obj where obj.id = :id");
}
query.setLong("id", object.getId());
if (query.uniqueResult() == null) {
if (stats) {
session.save(object);
} else {
session.save("com.xpn.xwiki.objects.BaseObject", object);
}
} else {
if (stats) {
session.update(object);
} else {
session.update("com.xpn.xwiki.objects.BaseObject", object);
}
}
/*
* if (stats) session.saveOrUpdate(object); else
* session.saveOrUpdate((String)"com.xpn.xwiki.objects.BaseObject", (Object)object);
*/
BaseClass bclass = object.getXClass(context);
List<String> handledProps = new ArrayList<>();
if ((bclass != null) && (bclass.hasCustomMapping()) && context.getWiki().hasCustomMappings()) {
// save object using the custom mapping
Map<String, Object> objmap = object.getCustomMappingMap();
handledProps = bclass.getCustomMappingPropertyList(context);
Session dynamicSession = session.getSession(EntityMode.MAP);
query = session.createQuery("select obj.id from " + bclass.getName() + " as obj where obj.id = :id");
query.setLong("id", object.getId());
if (query.uniqueResult() == null) {
dynamicSession.save(bclass.getName(), objmap);
} else {
dynamicSession.update(bclass.getName(), objmap);
}
// dynamicSession.saveOrUpdate((String) bclass.getName(), objmap);
}
if (object.getXClassReference() != null) {
// Remove all existing properties
if (object.getFieldsToRemove().size() > 0) {
for (int i = 0; i < object.getFieldsToRemove().size(); i++) {
BaseProperty prop = (BaseProperty) object.getFieldsToRemove().get(i);
if (!handledProps.contains(prop.getName())) {
session.delete(prop);
}
}
object.setFieldsToRemove(new ArrayList<BaseProperty>());
}
Iterator<String> it = object.getPropertyList().iterator();
while (it.hasNext()) {
String key = it.next();
BaseProperty prop = (BaseProperty) object.getField(key);
if (!prop.getName().equals(key)) {
Object[] args = { key, object.getName() };
throw new XWikiException(XWikiException.MODULE_XWIKI_CLASSES,
XWikiException.ERROR_XWIKI_CLASSES_FIELD_INVALID,
"Field {0} in object {1} has an invalid name", null, args);
}
String pname = prop.getName();
if (pname != null && !pname.trim().equals("") && !handledProps.contains(pname)) {
saveXWikiPropertyInternal(prop, context, false);
}
}
}
if (bTransaction) {
endTransaction(context, true);
}
} catch (XWikiException xe) {
throw xe;
} catch (Exception e) {
Object[] args = { object.getName() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_OBJECT, "Exception while saving object {0}", e, args);
} finally {
try {
if (bTransaction) {
endTransaction(context, true);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
}
/**
* @deprecated This is internal to XWikiHibernateStore and may be removed in the future.
*/
@Deprecated
public void loadXWikiCollection(BaseCollection object, XWikiContext context, boolean bTransaction)
throws XWikiException
{
loadXWikiCollectionInternal(object, context, bTransaction, false);
}
private void loadXWikiCollectionInternal(BaseCollection object, XWikiContext context, boolean bTransaction,
boolean alreadyLoaded) throws XWikiException
{
loadXWikiCollectionInternal(object, null, context, bTransaction, alreadyLoaded);
}
private void loadXWikiCollectionInternal(BaseCollection object1, XWikiDocument doc, XWikiContext inputxcontext,
boolean bTransaction, boolean alreadyLoaded) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
BaseCollection object = object1;
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(false, context);
}
Session session = getSession(context);
if (!alreadyLoaded) {
try {
session.load(object, object1.getId());
} catch (ObjectNotFoundException e) {
// There is no object data saved
object = null;
return;
}
}
DocumentReference classReference = object.getXClassReference();
// If the class reference is null in the loaded object then skip loading properties
if (classReference != null) {
BaseClass bclass = null;
if (!classReference.equals(object.getDocumentReference())) {
// Let's check if the class has a custom mapping
bclass = object.getXClass(context);
} else {
// We need to get it from the document otherwise
// we will go in an endless loop
if (doc != null) {
bclass = doc.getXClass();
}
}
List<String> handledProps = new ArrayList<String>();
try {
if ((bclass != null) && (bclass.hasCustomMapping()) && context.getWiki().hasCustomMappings()) {
Session dynamicSession = session.getSession(EntityMode.MAP);
Object map = dynamicSession.load(bclass.getName(), object.getId());
// Let's make sure to look for null fields in the dynamic mapping
bclass.fromValueMap((Map) map, object);
handledProps = bclass.getCustomMappingPropertyList(context);
for (String prop : handledProps) {
if (((Map) map).get(prop) == null) {
handledProps.remove(prop);
}
}
}
} catch (Exception e) {
}
// Load strings, integers, dates all at once
Query query = session
.createQuery("select prop.name, prop.classType from BaseProperty as prop where prop.id.id = :id");
query.setLong("id", object.getId());
for (Object[] result : (List<Object[]>) query.list()) {
String name = (String) result[0];
// No need to load fields already loaded from
// custom mapping
if (handledProps.contains(name)) {
continue;
}
String classType = (String) result[1];
BaseProperty property = null;
try {
property = (BaseProperty) Class.forName(classType).newInstance();
property.setObject(object);
property.setName(name);
loadXWikiProperty(property, context, false);
} catch (Exception e) {
// WORKAROUND IN CASE OF MIXMATCH BETWEEN STRING AND LARGESTRING
try {
if (property instanceof StringProperty) {
LargeStringProperty property2 = new LargeStringProperty();
property2.setObject(object);
property2.setName(name);
loadXWikiProperty(property2, context, false);
property.setValue(property2.getValue());
if (bclass != null) {
if (bclass.get(name) instanceof TextAreaClass) {
property = property2;
}
}
} else if (property instanceof LargeStringProperty) {
StringProperty property2 = new StringProperty();
property2.setObject(object);
property2.setName(name);
loadXWikiProperty(property2, context, false);
property.setValue(property2.getValue());
if (bclass != null) {
if (bclass.get(name) instanceof StringClass) {
property = property2;
}
}
} else {
throw e;
}
} catch (Throwable e2) {
Object[] args =
{ object.getName(), object.getClass(), Integer.valueOf(object.getNumber() + ""), name };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_OBJECT,
"Exception while loading object '{0}' of class '{1}', number '{2}' and property '{3}'",
e, args);
}
}
object.addField(name, property);
}
}
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
Object[] args = { object.getName(), object.getClass(), Integer.valueOf(object.getNumber() + "") };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_OBJECT,
"Exception while loading object '{0}' of class '{1}' and number '{2}'", e, args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
}
/**
* @deprecated This is internal to XWikiHibernateStore and may be removed in the future.
*/
@Deprecated
public void deleteXWikiCollection(BaseCollection object, XWikiContext inputxcontext, boolean bTransaction,
boolean evict) throws XWikiException
{
if (object == null) {
return;
}
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(context);
}
Session session = getSession(context);
// Let's check if the class has a custom mapping
BaseClass bclass = object.getXClass(context);
List<String> handledProps = new ArrayList<String>();
if ((bclass != null) && (bclass.hasCustomMapping()) && context.getWiki().hasCustomMappings()) {
handledProps = bclass.getCustomMappingPropertyList(context);
Session dynamicSession = session.getSession(EntityMode.MAP);
Object map = dynamicSession.get(bclass.getName(), object.getId());
if (map != null) {
if (evict) {
dynamicSession.evict(map);
}
dynamicSession.delete(map);
}
}
if (object.getXClassReference() != null) {
for (BaseElement property : (Collection<BaseElement>) object.getFieldList()) {
if (!handledProps.contains(property.getName())) {
if (evict) {
session.evict(property);
}
if (session.get(property.getClass(), property) != null) {
session.delete(property);
}
}
}
}
// In case of custom class we need to force it as BaseObject to delete the xwikiobject row
if (!"".equals(bclass.getCustomClass())) {
BaseObject cobject = new BaseObject();
cobject.setDocumentReference(object.getDocumentReference());
cobject.setClassName(object.getClassName());
cobject.setNumber(object.getNumber());
if (object instanceof BaseObject) {
cobject.setGuid(((BaseObject) object).getGuid());
}
cobject.setId(object.getId());
if (evict) {
session.evict(cobject);
}
session.delete(cobject);
} else {
if (evict) {
session.evict(object);
}
session.delete(object);
}
if (bTransaction) {
endTransaction(context, true);
}
} catch (Exception e) {
Object[] args = { object.getName() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_DELETING_OBJECT, "Exception while deleting object {0}", e,
args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
}
private void loadXWikiProperty(PropertyInterface property, XWikiContext context, boolean bTransaction)
throws XWikiException
{
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(false, context);
}
Session session = getSession(context);
try {
session.load(property, (Serializable) property);
// In Oracle, empty string are converted to NULL. Since an undefined property is not found at all, it is
// safe to assume that a retrieved NULL value should actually be an empty string.
if (property instanceof BaseStringProperty) {
BaseStringProperty stringProperty = (BaseStringProperty) property;
if (stringProperty.getValue() == null) {
stringProperty.setValue("");
}
}
((BaseProperty) property).setValueDirty(false);
} catch (ObjectNotFoundException e) {
// Let's accept that there is no data in property tables but log it
this.logger.error("No data for property [{}] of object id [{}]", property.getName(), property.getId());
}
// TODO: understand why collections are lazy loaded
// Let's force reading lists if there is a list
// This seems to be an issue since Hibernate 3.0
// Without this test ViewEditTest.testUpdateAdvanceObjectProp fails
if (property instanceof ListProperty) {
((ListProperty) property).getList();
}
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
BaseCollection obj = property.getObject();
Object[] args = { (obj != null) ? obj.getName() : "unknown", property.getName() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_OBJECT,
"Exception while loading property {1} of object {0}", e, args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
}
}
private void saveXWikiPropertyInternal(final PropertyInterface property, final XWikiContext context,
final boolean runInOwnTransaction) throws XWikiException
{
// Clone runInOwnTransaction so the value passed is not altered.
boolean bTransaction = runInOwnTransaction;
try {
if (bTransaction) {
this.checkHibernate(context);
bTransaction = this.beginTransaction(context);
}
final Session session = this.getSession(context);
Query query = session.createQuery(
"select prop.classType from BaseProperty as prop " + "where prop.id.id = :id and prop.id.name= :name");
query.setLong("id", property.getId());
query.setString("name", property.getName());
String oldClassType = (String) query.uniqueResult();
String newClassType = ((BaseProperty) property).getClassType();
if (oldClassType == null) {
session.save(property);
} else if (oldClassType.equals(newClassType)) {
session.update(property);
} else {
// The property type has changed. We cannot simply update its value because the new value and the old
// value are stored in different tables (we're using joined-subclass to map different property types).
// We must delete the old property value before saving the new one and for this we must load the old
// property from the table that corresponds to the old property type (we cannot delete and save the new
// property or delete a clone of the new property; loading the old property from the BaseProperty table
// doesn't work either).
query = session.createQuery(
"select prop from " + oldClassType + " as prop where prop.id.id = :id and prop.id.name= :name");
query.setLong("id", property.getId());
query.setString("name", property.getName());
session.delete(query.uniqueResult());
session.save(property);
}
((BaseProperty) property).setValueDirty(false);
if (bTransaction) {
endTransaction(context, true);
}
} catch (Exception e) {
// Something went wrong, collect some information.
final BaseCollection obj = property.getObject();
final Object[] args = { (obj != null) ? obj.getName() : "unknown", property.getName() };
// Try to roll back the transaction if this is in it's own transaction.
try {
if (bTransaction) {
this.endTransaction(context, false);
}
} catch (Exception ee) {
// Not a lot we can do here if there was an exception committing and an exception rolling back.
}
// Throw the exception.
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_OBJECT,
"Exception while saving property {1} of object {0}", e, args);
}
}
private void loadAttachmentList(XWikiDocument doc, XWikiContext context, boolean bTransaction) throws XWikiException
{
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(null, context);
}
Session session = getSession(context);
Query query = session.createQuery("from XWikiAttachment as attach where attach.docId=:docid");
query.setLong("docid", doc.getId());
@SuppressWarnings("unchecked")
List<XWikiAttachment> list = query.list();
for (XWikiAttachment attachment : list) {
doc.setAttachment(attachment);
}
} catch (Exception e) {
this.logger.error("Failed to load attachments of document [{}]", doc.getDocumentReference(), e);
Object[] args = { doc.getDocumentReference() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCHING_ATTACHMENT,
"Exception while searching attachments for documents {0}", e, args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
}
}
private void saveAttachmentList(XWikiDocument doc, XWikiContext context) throws XWikiException
{
try {
getSession(context);
List<XWikiAttachment> list = doc.getAttachmentList();
for (XWikiAttachment attachment : list) {
saveAttachment(attachment, context);
}
} catch (Exception e) {
Object[] args = { doc.getDocumentReference() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_ATTACHMENT_LIST,
"Exception while saving attachments attachment list of document {0}", e, args);
}
}
private void saveAttachment(XWikiAttachment attachment, XWikiContext context) throws XWikiException
{
try {
// If the comment is larger than the max size supported by the Storage, then abbreviate it
String comment = attachment.getComment();
if (comment != null && comment.length() > 1023) {
attachment.setComment(StringUtils.abbreviate(comment, 1023));
}
// The version number must be increased and the date must be set before the attachment meta data is saved.
// Changing the version and date after calling session.save()/session.update() "worked" (the altered version
// was what Hibernate saved) but only if everything is done in the same transaction and as far as I know it
// depended on undefined behavior.
// Note that the second condition is required because there are cases when we want the attachment content to
// be saved (see below) but we don't want the version to be increased (e.g. restore a document from recycle
// bin, copy or import a document).
// See XWIKI-9421: Attachment version is incremented when a document is restored from recycle bin
if (attachment.isContentDirty() && !attachment.getDoc().isNew()) {
attachment.updateContentArchive(context);
}
Session session = getSession(context);
Query query = session.createQuery("select attach.id from XWikiAttachment as attach where attach.id = :id");
query.setLong("id", attachment.getId());
boolean exist = query.uniqueResult() != null;
if (exist) {
session.update(attachment);
} else {
if (attachment.getContentStore() == null) {
// Set content store
attachment.setContentStore(getDefaultAttachmentContentStore(context));
}
if (attachment.getArchiveStore() == null) {
// Set archive store
attachment.setArchiveStore(getDefaultAttachmentArchiveStore(context));
}
session.save(attachment);
}
// Save the attachment content if it's marked as "dirty" (out of sync with the database).
if (attachment.isContentDirty()) {
// updateParent and bTransaction must be false because the content should be saved in the same
// transaction as the attachment and if the parent doc needs to be updated, this function will do it.
XWikiAttachmentStoreInterface store = getXWikiAttachmentStoreInterface(attachment);
store.saveAttachmentContent(attachment, false, context, false);
}
// Mark the attachment content and metadata as not dirty.
// Ideally this would only happen if the transaction is committed successfully but since an unsuccessful
// transaction will most likely be accompanied by an exception, the cache will not have a chance to save
// the copy of the document with erronious information. If this is not set here, the cache will return
// a copy of the attachment which claims to be dirty although it isn't.
attachment.setMetaDataDirty(false);
if (attachment.isContentDirty()) {
attachment.getAttachment_content().setContentDirty(false);
}
} catch (Exception e) {
Object[] args = { attachment.getReference() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_ATTACHMENT, "Exception while saving attachment [{0}]",
e, args);
}
}
// ---------------------------------------
// Locks
// ---------------------------------------
@Override
public XWikiLock loadLock(long docId, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
XWikiLock lock = null;
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(false, context);
}
Session session = getSession(context);
Query query = session.createQuery("select lock.docId from XWikiLock as lock where lock.docId = :docId");
query.setLong("docId", docId);
if (query.uniqueResult() != null) {
lock = new XWikiLock();
session.load(lock, Long.valueOf(docId));
}
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_LOCK, "Exception while loading lock", e);
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
return lock;
}
@Override
public void saveLock(XWikiLock lock, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(context);
}
Session session = getSession(context);
Query query = session.createQuery("select lock.docId from XWikiLock as lock where lock.docId = :docId");
query.setLong("docId", lock.getDocId());
if (query.uniqueResult() == null) {
session.save(lock);
} else {
session.update(lock);
}
if (bTransaction) {
endTransaction(context, true);
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_LOCK, "Exception while locking document", e);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
}
@Override
public void deleteLock(XWikiLock lock, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(context);
}
Session session = getSession(context);
session.delete(lock);
if (bTransaction) {
endTransaction(context, true);
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_DELETING_LOCK, "Exception while deleting lock", e);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
}
private void registerLogoutListener()
{
this.observationManager.addListener(new EventListener()
{
private final Event ev = new ActionExecutingEvent();
@Override
public String getName()
{
return "deleteLocksOnLogoutListener";
}
@Override
public List<Event> getEvents()
{
return Collections.<Event>singletonList(this.ev);
}
@Override
public void onEvent(Event event, Object source, Object data)
{
if ("logout".equals(((ActionExecutingEvent) event).getActionName())) {
final XWikiContext ctx = (XWikiContext) data;
if (ctx.getUserReference() != null) {
releaseAllLocksForCurrentUser(ctx);
}
}
}
});
}
/**
* Release all of the locks held by the currently logged in user.
*
* @param ctx the XWikiContext, used to start the connection and get the user name.
*/
private void releaseAllLocksForCurrentUser(final XWikiContext ctx)
{
try {
this.beginTransaction(ctx);
Session session = this.getSession(ctx);
final Query query = session.createQuery("delete from XWikiLock as lock where lock.userName=:userName");
// Using deprecated getUser() because this is how locks are created.
// It would be a maintainibility disaster to use different code paths
// for calculating names when creating and removing.
query.setString("userName", ctx.getUser());
query.executeUpdate();
this.endTransaction(ctx, true);
} catch (Exception e) {
String msg = "Error while deleting active locks held by user.";
try {
this.endTransaction(ctx, false);
} catch (Exception utoh) {
msg += " Failed to commit OR rollback [" + utoh.getMessage() + "]";
}
throw new UnexpectedException(msg, e);
}
// If we're in a non-main wiki & the user is global,
// switch to the global wiki and delete locks held there.
if (!ctx.isMainWiki() && ctx.isMainWiki(ctx.getUserReference().getWikiReference().getName())) {
final String cdb = ctx.getWikiId();
try {
ctx.setWikiId(ctx.getMainXWiki());
this.releaseAllLocksForCurrentUser(ctx);
} finally {
ctx.setWikiId(cdb);
}
}
}
// ---------------------------------------
// Links
// ---------------------------------------
@Override
public List<XWikiLink> loadLinks(long docId, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
List<XWikiLink> links = new ArrayList<XWikiLink>();
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(false, context);
}
Session session = getSession(context);
Query query = session.createQuery(" from XWikiLink as link where link.id.docId = :docId");
query.setLong("docId", docId);
links = query.list();
if (bTransaction) {
endTransaction(context, false, false);
bTransaction = false;
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_LINKS, "Exception while loading links", e);
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
return links;
}
@Override
public List<DocumentReference> loadBacklinks(DocumentReference documentReference, boolean bTransaction,
XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
// Note: Ideally the method should return a Set but it would break the current API.
// TODO: We use a Set here so that we don't get duplicates. In the future, when we can reference a page in
// another language using a syntax, we should modify this code to return one DocumentReference per language
// found. To implement this we need to be able to either serialize the reference with the language information
// or add some new column for the XWikiLink table in the database.
Set<DocumentReference> backlinkReferences = new HashSet<DocumentReference>();
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(false, context);
}
Session session = getSession(context);
// the select clause is compulsory to reach the fullName i.e. the page pointed
Query query = session
.createQuery("select backlink.fullName from XWikiLink as backlink where backlink.id.link = :backlink");
query.setString("backlink", this.localEntityReferenceSerializer.serialize(documentReference));
@SuppressWarnings("unchecked")
List<String> backlinkNames = query.list();
// Convert strings into references
for (String backlinkName : backlinkNames) {
backlinkReferences.add(this.currentMixedDocumentReferenceResolver.resolve(backlinkName));
}
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_BACKLINKS, "Exception while loading backlinks", e);
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
return new ArrayList<DocumentReference>(backlinkReferences);
}
/**
* @deprecated since 2.2M2 use {@link #loadBacklinks(DocumentReference, boolean, XWikiContext)}
*/
@Deprecated
@Override
public List<String> loadBacklinks(String fullName, XWikiContext inputxcontext, boolean bTransaction)
throws XWikiException
{
List<String> backlinkNames = new ArrayList<String>();
List<DocumentReference> backlinkReferences =
loadBacklinks(this.currentMixedDocumentReferenceResolver.resolve(fullName), bTransaction, inputxcontext);
for (DocumentReference backlinkReference : backlinkReferences) {
backlinkNames.add(this.localEntityReferenceSerializer.serialize(backlinkReference));
}
return backlinkNames;
}
@Override
public void saveLinks(XWikiDocument doc, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(context);
}
Session session = getSession(context);
// need to delete existing links before saving the page's one
deleteLinks(doc.getId(), context, bTransaction);
// necessary to blank links from doc
context.remove("links");
// Extract the links.
Set<XWikiLink> links = new LinkedHashSet<>();
// Add wiki syntax links.
// FIXME: replace with doc.getUniqueWikiLinkedPages(context) when OldRendering is dropped.
links.addAll(this.oldRenderingProvider.get().extractLinks(doc, context));
// Add included pages.
List<String> includedPages = doc.getIncludedPages(context);
for (String includedPage : includedPages) {
XWikiLink wikiLink = new XWikiLink();
wikiLink.setDocId(doc.getId());
wikiLink.setFullName(this.localEntityReferenceSerializer.serialize(doc.getDocumentReference()));
wikiLink.setLink(includedPage);
links.add(wikiLink);
}
// Save the links.
for (XWikiLink wikiLink : links) {
// Verify that the link reference isn't larger than 255 characters (and truncate it if that's the case)
// since otherwise that would lead to a DB error that would result in a fatal error, and the user would
// have a hard time understanding why his page failed to be saved.
wikiLink.setLink(StringUtils.substring(wikiLink.getLink(), 0, 255));
session.save(wikiLink);
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_LINKS, "Exception while saving links", e);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
}
@Override
public void deleteLinks(long docId, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
if (bTransaction) {
checkHibernate(context);
bTransaction = beginTransaction(context);
}
Session session = getSession(context);
Query query = session.createQuery("delete from XWikiLink as link where link.id.docId = :docId");
query.setLong("docId", docId);
query.executeUpdate();
if (bTransaction) {
endTransaction(context, true);
bTransaction = false;
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_DELETING_LINKS, "Exception while deleting links", e);
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
}
public void getContent(XWikiDocument doc, StringBuffer buf)
{
buf.append(doc.getContent());
}
@Override
public List<String> getClassList(XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
boolean bTransaction = true;
try {
checkHibernate(context);
bTransaction = beginTransaction(false, context);
Session session = getSession(context);
Query query = session.createQuery("select doc.fullName from XWikiDocument as doc "
+ "where (doc.xWikiClassXML is not null and doc.xWikiClassXML like '<%')");
List<String> list = new ArrayList<String>();
list.addAll(query.list());
if (bTransaction) {
endTransaction(context, false, false);
}
return list;
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCH, "Exception while searching class list", e);
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
}
}
/**
* Add values into named query.
*
* @param parameterId the parameter id to increment.
* @param query the query to fill.
* @param parameterValues the values to add to query.
* @return the id of the next parameter to add.
*/
private int injectParameterListToQuery(int parameterId, Query query, Collection<?> parameterValues)
{
int index = parameterId;
if (parameterValues != null) {
for (Iterator<?> valueIt = parameterValues.iterator(); valueIt.hasNext(); ++index) {
injectParameterToQuery(index, query, valueIt.next());
}
}
return index;
}
/**
* Add value into named query.
*
* @param parameterId the parameter id to increment.
* @param query the query to fill.
* @param parameterValue the values to add to query.
*/
private void injectParameterToQuery(int parameterId, Query query, Object parameterValue)
{
query.setParameter(parameterId, parameterValue);
}
@Override
public List<DocumentReference> searchDocumentReferences(String parametrizedSqlClause, List<?> parameterValues,
XWikiContext context) throws XWikiException
{
return searchDocumentReferences(parametrizedSqlClause, 0, 0, parameterValues, context);
}
@Override
public List<String> searchDocumentsNames(String parametrizedSqlClause, List<?> parameterValues,
XWikiContext context) throws XWikiException
{
return searchDocumentsNames(parametrizedSqlClause, 0, 0, parameterValues, context);
}
@Override
public List<DocumentReference> searchDocumentReferences(String parametrizedSqlClause, int nb, int start,
List<?> parameterValues, XWikiContext context) throws XWikiException
{
String sql = createSQLQuery("select distinct doc.fullName", parametrizedSqlClause);
return searchDocumentReferencesInternal(sql, nb, start, parameterValues, context);
}
@Override
public List<String> searchDocumentsNames(String parametrizedSqlClause, int nb, int start, List<?> parameterValues,
XWikiContext context) throws XWikiException
{
String sql = createSQLQuery("select distinct doc.fullName", parametrizedSqlClause);
return searchDocumentsNamesInternal(sql, nb, start, parameterValues, context);
}
@Override
public List<DocumentReference> searchDocumentReferences(String wheresql, XWikiContext context) throws XWikiException
{
return searchDocumentReferences(wheresql, 0, 0, "", context);
}
@Override
public List<String> searchDocumentsNames(String wheresql, XWikiContext context) throws XWikiException
{
return searchDocumentsNames(wheresql, 0, 0, "", context);
}
@Override
public List<DocumentReference> searchDocumentReferences(String wheresql, int nb, int start, XWikiContext context)
throws XWikiException
{
return searchDocumentReferences(wheresql, nb, start, "", context);
}
@Override
public List<String> searchDocumentsNames(String wheresql, int nb, int start, XWikiContext context)
throws XWikiException
{
return searchDocumentsNames(wheresql, nb, start, "", context);
}
@Override
public List<DocumentReference> searchDocumentReferences(String wheresql, int nb, int start, String selectColumns,
XWikiContext context) throws XWikiException
{
String sql = createSQLQuery("select distinct doc.fullName", wheresql);
return searchDocumentReferencesInternal(sql, nb, start, Collections.EMPTY_LIST, context);
}
@Override
public List<String> searchDocumentsNames(String wheresql, int nb, int start, String selectColumns,
XWikiContext context) throws XWikiException
{
String sql = createSQLQuery("select distinct doc.fullName", wheresql);
return searchDocumentsNamesInternal(sql, nb, start, Collections.EMPTY_LIST, context);
}
@Override
public <T> List<T> search(String sql, int nb, int start, XWikiContext context) throws XWikiException
{
return search(sql, nb, start, (List<?>) null, context);
}
@Override
public <T> List<T> search(String sql, int nb, int start, List<?> parameterValues, XWikiContext context)
throws XWikiException
{
return search(sql, nb, start, null, parameterValues, context);
}
@Override
public <T> List<T> search(String sql, int nb, int start, Object[][] whereParams, XWikiContext context)
throws XWikiException
{
return search(sql, nb, start, whereParams, null, context);
}
@Override
public <T> List<T> search(String sql, int nb, int start, Object[][] whereParams, List<?> parameterValues,
XWikiContext inputxcontext) throws XWikiException
{
boolean bTransaction = true;
if (sql == null) {
return null;
}
XWikiContext context = getExecutionXContext(inputxcontext, true);
MonitorPlugin monitor = Util.getMonitorPlugin(context);
try {
// Start monitoring timer
if (monitor != null) {
monitor.startTimer(HINT);
}
checkHibernate(context);
bTransaction = beginTransaction(false, context);
Session session = getSession(context);
if (whereParams != null) {
sql += generateWhereStatement(whereParams);
}
Query query = session.createQuery(filterSQL(sql));
// Add values for provided HQL request containing "?" characters where to insert real
// values.
int parameterId = injectParameterListToQuery(0, query, parameterValues);
if (whereParams != null) {
for (Object[] whereParam : whereParams) {
query.setString(parameterId++, (String) whereParam[1]);
}
}
if (start != 0) {
query.setFirstResult(start);
}
if (nb != 0) {
query.setMaxResults(nb);
}
List<T> list = new ArrayList<T>();
list.addAll(query.list());
return list;
} catch (Exception e) {
Object[] args = { sql };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCH, "Exception while searching documents with sql {0}",
e, args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
// End monitoring timer
if (monitor != null) {
monitor.endTimer(HINT);
}
}
}
private String generateWhereStatement(Object[][] whereParams)
{
StringBuilder str = new StringBuilder();
str.append(" where ");
for (int i = 0; i < whereParams.length; i++) {
if (i > 0) {
if (whereParams[i - 1].length >= 4 && whereParams[i - 1][3] != "" && whereParams[i - 1][3] != null) {
str.append(" ");
str.append(whereParams[i - 1][3]);
str.append(" ");
} else {
str.append(" and ");
}
}
str.append(whereParams[i][0]);
if (whereParams[i].length >= 3 && whereParams[i][2] != "" && whereParams[i][2] != null) {
str.append(" ");
str.append(whereParams[i][2]);
str.append(" ");
} else {
str.append(" = ");
}
str.append(" ?");
}
return str.toString();
}
public List search(Query query, int nb, int start, XWikiContext inputxcontext) throws XWikiException
{
boolean bTransaction = true;
if (query == null) {
return null;
}
XWikiContext context = getExecutionXContext(inputxcontext, true);
MonitorPlugin monitor = Util.getMonitorPlugin(context);
try {
// Start monitoring timer
if (monitor != null) {
monitor.startTimer(HINT, query.getQueryString());
}
checkHibernate(context);
bTransaction = beginTransaction(false, context);
if (start != 0) {
query.setFirstResult(start);
}
if (nb != 0) {
query.setMaxResults(nb);
}
Iterator it = query.list().iterator();
List list = new ArrayList();
while (it.hasNext()) {
list.add(it.next());
}
if (bTransaction) {
// The session is closed here, too.
endTransaction(context, false, false);
bTransaction = false;
}
return list;
} catch (Exception e) {
Object[] args = { query.toString() };
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCH, "Exception while searching documents with sql {0}",
e, args);
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
// End monitoring timer
if (monitor != null) {
monitor.endTimer(HINT);
}
}
}
@Override
public int countDocuments(String wheresql, XWikiContext context) throws XWikiException
{
String sql = createSQLQuery("select count(distinct doc.fullName)", wheresql);
List<Number> l = search(sql, 0, 0, context);
return l.get(0).intValue();
}
@Override
public int countDocuments(String parametrizedSqlClause, List<?> parameterValues, XWikiContext context)
throws XWikiException
{
String sql = createSQLQuery("select count(distinct doc.fullName)", parametrizedSqlClause);
List l = search(sql, 0, 0, parameterValues, context);
return ((Number) l.get(0)).intValue();
}
/**
* @deprecated since 2.2M1 used {@link #searchDocumentReferencesInternal(String, int, int, List, XWikiContext)}
*/
@Deprecated
private List<String> searchDocumentsNamesInternal(String sql, int nb, int start, List parameterValues,
XWikiContext context) throws XWikiException
{
List<String> documentNames = new ArrayList<String>();
for (DocumentReference reference : searchDocumentReferencesInternal(sql, nb, start, parameterValues, context)) {
documentNames.add(this.compactWikiEntityReferenceSerializer.serialize(reference));
}
return documentNames;
}
/**
* @since 2.2M1
*/
private List<DocumentReference> searchDocumentReferencesInternal(String sql, int nb, int start,
List<?> parameterValues, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
List<DocumentReference> documentReferences = new ArrayList<DocumentReference>();
// Construct a reference, using the current wiki as the wiki reference name. This is because the wiki
// name is not stored in the database for document references.
WikiReference wikiReference = new WikiReference(context.getWikiId());
for (Object result : this.searchGenericInternal(sql, nb, start, parameterValues, context)) {
// The select always contains several elements in case of order by so we have to support both Object[]
// and
// String
String referenceString;
if (result instanceof String) {
referenceString = (String) result;
} else {
referenceString = (String) ((Object[]) result)[0];
}
DocumentReference reference =
this.defaultDocumentReferenceResolver.resolve(referenceString, wikiReference);
documentReferences.add(reference);
}
return documentReferences;
} finally {
restoreExecutionXContext();
}
}
/**
* @since 2.2M1
*/
private <T> List<T> searchGenericInternal(String sql, int nb, int start, List<?> parameterValues,
XWikiContext context) throws XWikiException
{
boolean bTransaction = false;
MonitorPlugin monitor = Util.getMonitorPlugin(context);
try {
// Start monitoring timer
if (monitor != null) {
monitor.startTimer(HINT, sql);
}
checkHibernate(context);
bTransaction = beginTransaction(false, context);
Session session = getSession(context);
Query query = session.createQuery(filterSQL(sql));
injectParameterListToQuery(0, query, parameterValues);
if (start != 0) {
query.setFirstResult(start);
}
if (nb != 0) {
query.setMaxResults(nb);
}
Iterator it = query.list().iterator();
List list = new ArrayList<>();
while (it.hasNext()) {
list.add(it.next());
}
return list;
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCH, "Exception while searching documents with SQL [{0}]",
e, new Object[] { sql });
} finally {
try {
if (bTransaction) {
endTransaction(context, false, false);
}
} catch (Exception e) {
}
// End monitoring timer
if (monitor != null) {
monitor.endTimer(HINT);
}
}
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, boolean customMapping,
boolean checkRight, int nb, int start, XWikiContext context) throws XWikiException
{
return searchDocuments(wheresql, distinctbylanguage, customMapping, checkRight, nb, start, null, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, boolean customMapping,
boolean checkRight, int nb, int start, List<?> parameterValues, XWikiContext inputxcontext)
throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
// Search documents
List documentDatas = new ArrayList();
boolean bTransaction = true;
MonitorPlugin monitor = Util.getMonitorPlugin(context);
try {
String sql;
if (distinctbylanguage) {
sql = createSQLQuery("select distinct doc.fullName, doc.language", wheresql);
} else {
sql = createSQLQuery("select distinct doc.fullName", wheresql);
}
// Start monitoring timer
if (monitor != null) {
monitor.startTimer(HINT, sql);
}
checkHibernate(context);
if (bTransaction) {
// Inject everything until we know what's needed
SessionFactory sfactory =
customMapping ? injectCustomMappingsInSessionFactory(context) : getSessionFactory();
bTransaction = beginTransaction(sfactory, context);
}
Session session = getSession(context);
Query query = session.createQuery(filterSQL(sql));
injectParameterListToQuery(0, query, parameterValues);
if (start != 0) {
query.setFirstResult(start);
}
if (nb != 0) {
query.setMaxResults(nb);
}
documentDatas.addAll(query.list());
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCH, "Exception while searching documents with SQL [{0}]",
e, new Object[] { wheresql });
} finally {
try {
if (bTransaction) {
endTransaction(context, false);
}
} catch (Exception e) {
}
restoreExecutionXContext();
// End monitoring timer
if (monitor != null) {
monitor.endTimer(HINT);
}
}
// Resolve documents. We use two separated sessions because rights service could need to switch database to
// check rights
List<XWikiDocument> documents = new ArrayList<>();
WikiReference currentWikiReference = new WikiReference(context.getWikiId());
for (Object result : documentDatas) {
String fullName;
String locale = null;
if (result instanceof String) {
fullName = (String) result;
} else {
fullName = (String) ((Object[]) result)[0];
if (distinctbylanguage) {
locale = (String) ((Object[]) result)[1];
}
}
XWikiDocument doc =
new XWikiDocument(this.defaultDocumentReferenceResolver.resolve(fullName, currentWikiReference));
if (checkRight) {
if (!context.getWiki().getRightService().hasAccessLevel("view", context.getUser(), doc.getFullName(),
context)) {
continue;
}
}
DocumentReference documentReference = doc.getDocumentReference();
if (distinctbylanguage) {
XWikiDocument document = context.getWiki().getDocument(documentReference, context);
if (StringUtils.isEmpty(locale)) {
documents.add(document);
} else {
documents.add(document.getTranslatedDocument(locale, context));
}
} else {
documents.add(context.getWiki().getDocument(documentReference, context));
}
}
return documents;
}
/**
* @param queryPrefix the start of the SQL query (for example "select distinct doc.space, doc.name")
* @param whereSQL the where clause to append
* @return the full formed SQL query, to which the order by columns have been added as returned columns (this is
* required for example for HSQLDB).
*/
protected String createSQLQuery(String queryPrefix, String whereSQL)
{
StringBuilder sql = new StringBuilder(queryPrefix);
String normalizedWhereSQL;
if (StringUtils.isBlank(whereSQL)) {
normalizedWhereSQL = "";
} else {
normalizedWhereSQL = whereSQL.trim();
}
sql.append(getColumnsForSelectStatement(normalizedWhereSQL));
sql.append(" from XWikiDocument as doc");
if (!normalizedWhereSQL.equals("")) {
if ((!normalizedWhereSQL.startsWith("where")) && (!normalizedWhereSQL.startsWith(","))) {
sql.append(" where ");
} else {
sql.append(" ");
}
sql.append(normalizedWhereSQL);
}
return sql.toString();
}
/**
* @param whereSQL the SQL where clause
* @return the list of columns to return in the select clause as a string starting with ", " if there are columns or
* an empty string otherwise. The returned columns are extracted from the where clause. One reason for doing
* so is because HSQLDB only support SELECT DISTINCT SQL statements where the columns operated on are
* returned from the query.
*/
protected String getColumnsForSelectStatement(String whereSQL)
{
StringBuilder columns = new StringBuilder();
int orderByPos = whereSQL.toLowerCase().indexOf("order by");
if (orderByPos >= 0) {
String orderByStatement = whereSQL.substring(orderByPos + "order by".length() + 1);
StringTokenizer tokenizer = new StringTokenizer(orderByStatement, ",");
while (tokenizer.hasMoreTokens()) {
String column = tokenizer.nextToken().trim();
// Remove "desc" or "asc" from the column found
column = StringUtils.removeEndIgnoreCase(column, " desc");
column = StringUtils.removeEndIgnoreCase(column, " asc");
columns.append(", ").append(column.trim());
}
}
return columns.toString();
}
@Override
public boolean isCustomMappingValid(BaseClass bclass, String custommapping1, XWikiContext context)
{
try {
Configuration hibconfig = getMapping(bclass.getName(), custommapping1);
return isValidCustomMapping(bclass, hibconfig);
} catch (Exception e) {
return false;
}
}
private SessionFactory injectCustomMappingsInSessionFactory(XWikiDocument doc, XWikiContext context)
throws XWikiException
{
// If we haven't turned of dynamic custom mappings we should not inject them
if (!context.getWiki().hasDynamicCustomMappings()) {
return getSessionFactory();
}
boolean result = injectCustomMappings(doc, context);
if (!result) {
return getSessionFactory();
}
Configuration config = getConfiguration();
SessionFactoryImpl sfactory = (SessionFactoryImpl) config.buildSessionFactory();
Settings settings = sfactory.getSettings();
ConnectionProvider provider = ((SessionFactoryImpl) getSessionFactory()).getSettings().getConnectionProvider();
Field field = null;
try {
field = settings.getClass().getDeclaredField("connectionProvider");
field.setAccessible(true);
field.set(settings, provider);
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_MAPPING_INJECTION_FAILED, "Mapping injection failed", e);
}
return sfactory;
}
@Override
public void injectCustomMappings(XWikiContext context) throws XWikiException
{
SessionFactory sfactory = injectCustomMappingsInSessionFactory(context);
setSessionFactory(sfactory);
}
@Override
public void injectUpdatedCustomMappings(XWikiContext context) throws XWikiException
{
Configuration config = getConfiguration();
setSessionFactory(injectInSessionFactory(config));
}
public SessionFactory injectCustomMappingsInSessionFactory(BaseClass bclass, XWikiContext context)
throws XWikiException
{
boolean result = injectCustomMapping(bclass, context);
if (result == false) {
return getSessionFactory();
}
Configuration config = getConfiguration();
return injectInSessionFactory(config);
}
private SessionFactory injectInSessionFactory(Configuration config) throws XWikiException
{
SessionFactoryImpl sfactory = (SessionFactoryImpl) config.buildSessionFactory();
Settings settings = sfactory.getSettings();
ConnectionProvider provider = ((SessionFactoryImpl) getSessionFactory()).getSettings().getConnectionProvider();
Field field = null;
try {
field = settings.getClass().getDeclaredField("connectionProvider");
field.setAccessible(true);
field.set(settings, provider);
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_MAPPING_INJECTION_FAILED, "Mapping injection failed", e);
}
return sfactory;
}
public SessionFactory injectCustomMappingsInSessionFactory(XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
// If we haven't turned of dynamic custom mappings we should not inject them
if (context.getWiki().hasDynamicCustomMappings() == false) {
return getSessionFactory();
}
List<XWikiDocument> list;
list = searchDocuments(" where (doc.xWikiClassXML is not null and doc.xWikiClassXML like '<%')", true,
false, false, 0, 0, context);
boolean result = false;
for (XWikiDocument doc : list) {
if (!doc.getXClass().getFieldList().isEmpty()) {
result |= injectCustomMapping(doc.getXClass(), context);
}
}
if (!result) {
return getSessionFactory();
}
Configuration config = getConfiguration();
return injectInSessionFactory(config);
} finally {
restoreExecutionXContext();
}
}
@Override
public boolean injectCustomMappings(XWikiDocument doc, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
// If we haven't turned of dynamic custom mappings we should not inject them
if (context.getWiki().hasDynamicCustomMappings() == false) {
return false;
}
boolean result = false;
for (List<BaseObject> objectsOfType : doc.getXObjects().values()) {
for (BaseObject object : objectsOfType) {
if (object != null) {
result |= injectCustomMapping(object.getXClass(context), context);
// Each class must be mapped only once
break;
}
}
}
return result;
} finally {
restoreExecutionXContext();
}
}
/**
* @param className the name of the class to map
* @param custommapping the custom mapping to inject for this class
* @param inputxcontext the current XWikiContext
* @return a boolean indicating if the mapping has been added to the current hibernate configuration, and a reload
* of the factory is required.
* @throws XWikiException if an error occurs
* @since 4.0M1
*/
public boolean injectCustomMapping(String className, String custommapping, XWikiContext inputxcontext)
throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
// If we haven't turned of dynamic custom mappings we should not inject them
if (!context.getWiki().hasDynamicCustomMappings()) {
return false;
}
Configuration config = getConfiguration();
// don't add a mapping that's already there
if (config.getClassMapping(className) != null) {
return false;
}
config.addXML(makeMapping(className, custommapping));
config.buildMappings();
return true;
} finally {
restoreExecutionXContext();
}
}
@Override
public boolean injectCustomMapping(BaseClass doc1class, XWikiContext inputxcontext) throws XWikiException
{
XWikiContext context = getExecutionXContext(inputxcontext, true);
try {
if (!doc1class.hasExternalCustomMapping()) {
return false;
}
if (injectCustomMapping(doc1class.getName(), doc1class.getCustomMapping(), context)) {
if (!isValidCustomMapping(doc1class, getConfiguration())) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_INVALID_MAPPING, "Invalid Custom Mapping");
}
return true;
}
return false;
} finally {
restoreExecutionXContext();
}
}
private boolean isValidCustomMapping(BaseClass bclass, Configuration config)
{
PersistentClass mapping = config.getClassMapping(bclass.getName());
if (mapping == null) {
return true;
}
Iterator it = mapping.getPropertyIterator();
while (it.hasNext()) {
Property hibprop = (Property) it.next();
String propname = hibprop.getName();
PropertyClass propclass = (PropertyClass) bclass.getField(propname);
if (propclass == null) {
this.logger.warn("Mapping contains invalid field name [{}]", propname);
return false;
}
boolean result = isValidColumnType(hibprop.getValue().getType().getName(), propclass.getClassName());
if (result == false) {
this.logger.warn("Mapping contains invalid type in field [{}]", propname);
return false;
}
}
return true;
}
@Override
public List<String> getCustomMappingPropertyList(BaseClass bclass)
{
List<String> list = new ArrayList<>();
Configuration hibconfig;
if (bclass.hasExternalCustomMapping()) {
hibconfig = getMapping(bclass.getName(), bclass.getCustomMapping());
} else {
hibconfig = getConfiguration();
}
PersistentClass mapping = hibconfig.getClassMapping(bclass.getName());
if (mapping == null) {
return null;
}
Iterator it = mapping.getPropertyIterator();
while (it.hasNext()) {
Property hibprop = (Property) it.next();
String propname = hibprop.getName();
list.add(propname);
}
return list;
}
private boolean isValidColumnType(String name, String className)
{
String[] validtypes = this.validTypesMap.get(className);
if (validtypes == null) {
return true;
} else {
return ArrayUtils.contains(validtypes, name);
}
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, XWikiContext context) throws XWikiException
{
return searchDocuments(wheresql, null, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, List<?> parameterValues, XWikiContext context)
throws XWikiException
{
return searchDocuments(wheresql, 0, 0, parameterValues, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, XWikiContext context)
throws XWikiException
{
return searchDocuments(wheresql, distinctbylanguage, 0, 0, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, boolean customMapping,
XWikiContext context) throws XWikiException
{
return searchDocuments(wheresql, distinctbylanguage, customMapping, 0, 0, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, int nb, int start, XWikiContext context)
throws XWikiException
{
return searchDocuments(wheresql, nb, start, null, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, int nb, int start, List<?> parameterValues,
XWikiContext context) throws XWikiException
{
return searchDocuments(wheresql, true, nb, start, parameterValues, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, int nb, int start,
List<?> parameterValues, XWikiContext context) throws XWikiException
{
return searchDocuments(wheresql, distinctbylanguage, false, nb, start, parameterValues, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, int nb, int start,
XWikiContext context) throws XWikiException
{
return searchDocuments(wheresql, distinctbylanguage, nb, start, null, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, boolean customMapping,
int nb, int start, XWikiContext context) throws XWikiException
{
return searchDocuments(wheresql, distinctbylanguage, customMapping, nb, start, null, context);
}
@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, boolean customMapping,
int nb, int start, List<?> parameterValues, XWikiContext context) throws XWikiException
{
return searchDocuments(wheresql, distinctbylanguage, customMapping, true, nb, start, parameterValues, context);
}
@Override
public List<String> getTranslationList(XWikiDocument doc, XWikiContext context) throws XWikiException
{
try {
return getTranslationList(doc.getDocumentReference());
} catch (QueryException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCH,
"Failed to retrieve the list of translations for [{0}]", e,
new Object[] { doc.getDocumentReference() });
}
}
private List<String> getTranslationList(DocumentReference documentReference) throws QueryException
{
// Note that the query is made to work with Oracle which treats empty strings as null.
String hql = "select doc.language from XWikiDocument as doc where doc.space = :space and doc.name = :name "
+ "and (doc.language <> '' or (doc.language is not null and '' is null))";
org.xwiki.query.Query query = getQueryManager().createQuery(hql, org.xwiki.query.Query.HQL);
query.setWiki(documentReference.getWikiReference().getName());
query.bindValue("space", this.localEntityReferenceSerializer.serialize(documentReference.getParent()));
query.bindValue("name", documentReference.getName());
return query.execute();
}
@Override
public QueryManager getQueryManager()
{
return this.queryManager;
}
/**
* This is in response to the fact that Hibernate interprets backslashes differently from the database. Our solution
* is to simply replace all instances of \ with \\ which makes the first backslash escape the second.
*
* @param sql the uncleaned sql.
* @return same as sql except it is guarenteed not to contain groups of odd numbers of backslashes.
* @since 2.4M1
*/
private String filterSQL(String sql)
{
return StringUtils.replace(sql, "\\", "\\\\");
}
private String getDefaultAttachmentContentStore(XWikiContext xcontext)
{
XWikiAttachmentStoreInterface store = xcontext.getWiki().getDefaultAttachmentContentStore();
if (store != null && store != this.attachmentContentStore) {
return store.getHint();
}
return null;
}
private String getDefaultAttachmentArchiveStore(XWikiContext xcontext)
{
AttachmentVersioningStore store = xcontext.getWiki().getDefaultAttachmentArchiveStore();
if (store != null && store != this.attachmentArchiveStore) {
return store.getHint();
}
return null;
}
private XWikiAttachmentStoreInterface getXWikiAttachmentStoreInterface(XWikiAttachment attachment)
throws ComponentLookupException
{
String storeHint = attachment.getContentStore();
if (storeHint != null && !storeHint.equals(HINT)) {
return this.componentManager.getInstance(XWikiAttachmentStoreInterface.class, storeHint);
}
return this.attachmentContentStore;
}
}
|
XWIKI-15161: XWikiHibernateStore ConcurrentModificationException
* fix ConcurrentModificationException
* add missing log entry for exception
|
xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateStore.java
|
XWIKI-15161: XWikiHibernateStore ConcurrentModificationException
|
|
Java
|
apache-2.0
|
312a9347cec1542a96fa2e9eae925106be40509c
| 0
|
RADAR-CNS/RADAR-AndroidApplication,RADAR-CNS/RADAR-AndroidApplication,RADAR-CNS/RADAR-AndroidApplication
|
package org.radarcns.empaticaE4;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Process;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.radarcns.R;
import org.radarcns.android.DeviceServiceConnection;
import org.radarcns.android.DeviceState;
import org.radarcns.android.DeviceStatusListener;
import org.radarcns.kafka.rest.ServerStatusListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.Set;
import static org.radarcns.empaticaE4.E4Service.DEVICE_CONNECT_FAILED;
import static org.radarcns.empaticaE4.E4Service.DEVICE_STATUS_NAME;
import static org.radarcns.empaticaE4.E4Service.SERVER_STATUS_CHANGED;
public class MainActivity extends AppCompatActivity {
private final static Logger logger = LoggerFactory.getLogger(MainActivity.class);
private static final int REQUEST_ENABLE_PERMISSIONS = 2;
private long uiRefreshRate;
private HandlerThread mHandlerThread;
private Handler mHandler;
private Runnable mUIScheduler;
private DeviceUIUpdater mUIUpdater;
private boolean isForcedDisconnected;
private final boolean[] mConnectionIsBound;
/** Defines callbacks for service binding, passed to bindService() */
private final DeviceServiceConnection<E4DeviceStatus> mE4Connection;
private final BroadcastReceiver serverStatusListener;
private final BroadcastReceiver bluetoothReceiver;
private final BroadcastReceiver deviceFailedReceiver;
/** Connections. 0 = Empatica, 1 = Angel sensor **/
private DeviceServiceConnection[] mConnections;
/** Overview UI **/
private TextView[] mDeviceNameLabels;
private View[] mStatusIcons;
private View mServerStatusIcon;
private TextView[] mTemperatureLabels;
private ImageView[] mBatteryLabels;
private Button[] mDeviceInputButtons;
private String[] mInputDeviceKeys = new String[4];
private final Runnable bindServicesRunner = new Runnable() {
@Override
public void run() {
if (!mConnectionIsBound[0]) {
Intent e4serviceIntent = new Intent(MainActivity.this, E4Service.class);
e4serviceIntent.putExtra("kafka_rest_proxy_url", getString(R.string.kafka_rest_proxy_url));
e4serviceIntent.putExtra("schema_registry_url", getString(R.string.schema_registry_url));
e4serviceIntent.putExtra("group_id", getString(R.string.group_id));
e4serviceIntent.putExtra("empatica_api_key", getString(R.string.apikey));
mE4Connection.bind(e4serviceIntent);
mConnectionIsBound[0] = true;
}
}
};
public MainActivity() {
super();
isForcedDisconnected = false;
mE4Connection = new DeviceServiceConnection<>(this, E4DeviceStatus.CREATOR);
mConnections = new DeviceServiceConnection[] {mE4Connection, null, null, null};
mConnectionIsBound = new boolean[] {false, false, false, false};
serverStatusListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SERVER_STATUS_CHANGED)) {
final ServerStatusListener.Status status = ServerStatusListener.Status.values()[intent.getIntExtra(SERVER_STATUS_CHANGED, 0)];
updateServerStatus(status);
}
}
};
bluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
logger.info("Bluetooth state {}", state);
if (state == BluetoothAdapter.STATE_ON) {
logger.info("Bluetooth has turned on");
startScanning();
} else if (state == BluetoothAdapter.STATE_OFF) {
logger.warn("Bluetooth is off");
startScanning();
}
}
}
};
deviceFailedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, final Intent intent) {
if (intent.getAction().equals(DEVICE_CONNECT_FAILED)) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "Cannot connect to device " + intent.getStringExtra(DEVICE_STATUS_NAME), Toast.LENGTH_SHORT).show();
}
});
}
}
};
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overview);
// Create arrays of labels. Fixed to four rows
mDeviceNameLabels = new TextView[] {
(TextView) findViewById(R.id.deviceNameRow1),
(TextView) findViewById(R.id.deviceNameRow2),
(TextView) findViewById(R.id.deviceNameRow3),
(TextView) findViewById(R.id.deviceNameRow4)
};
mStatusIcons = new View[] {
findViewById(R.id.statusRow1),
findViewById(R.id.statusRow2),
findViewById(R.id.statusRow3),
findViewById(R.id.statusRow4)
};
mServerStatusIcon = findViewById(R.id.statusServer);
mTemperatureLabels = new TextView[] {
(TextView) findViewById(R.id.temperatureRow1),
(TextView) findViewById(R.id.temperatureRow2),
(TextView) findViewById(R.id.temperatureRow3),
(TextView) findViewById(R.id.temperatureRow4)
};
mBatteryLabels = new ImageView[] {
(ImageView) findViewById(R.id.batteryRow1),
(ImageView) findViewById(R.id.batteryRow2),
(ImageView) findViewById(R.id.batteryRow3),
(ImageView) findViewById(R.id.batteryRow4)
};
mDeviceInputButtons = new Button[] {
(Button) findViewById(R.id.inputDeviceNameButtonRow1),
(Button) findViewById(R.id.inputDeviceNameButtonRow2),
(Button) findViewById(R.id.inputDeviceNameButtonRow3),
(Button) findViewById(R.id.inputDeviceNameButtonRow4)
};
uiRefreshRate = getResources().getInteger(R.integer.ui_refresh_rate);
mUIUpdater = new DeviceUIUpdater();
mUIScheduler = new Runnable() {
@Override
public void run() {
try {
// Update all rows in the UI with the data from the connections
mUIUpdater.update();
} catch (RemoteException e) {
logger.warn("Failed to update device data", e);
} finally {
getHandler().postDelayed(mUIScheduler, uiRefreshRate);
}
}
};
checkBluetoothPermissions();
}
@Override
protected void onResume() {
logger.info("mainActivity onResume");
super.onResume();
mHandler.postDelayed(bindServicesRunner, 300L);
}
@Override
protected void onPause() {
logger.info("mainActivity onPause");
super.onPause();
mHandler.removeCallbacks(mUIScheduler);
}
@Override
protected void onStart() {
logger.info("mainActivity onStart");
super.onStart();
registerReceiver(bluetoothReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
registerReceiver(serverStatusListener, new IntentFilter(E4Service.SERVER_STATUS_CHANGED));
registerReceiver(deviceFailedReceiver, new IntentFilter(E4Service.DEVICE_CONNECT_FAILED));
mHandlerThread = new HandlerThread("E4Service connection", Process.THREAD_PRIORITY_BACKGROUND);
mHandlerThread.start();
synchronized (this) {
mHandler = new Handler(mHandlerThread.getLooper());
}
mHandler.post(mUIScheduler);
mHandler.post(new Runnable() {
@Override
public void run() {
for (int i = 0; i < mConnections.length; i++) {
mConnectionIsBound[i] = false;
}
}
});
}
@Override
protected void onStop() {
logger.info("mainActivity onStop");
super.onStop();
unregisterReceiver(serverStatusListener);
unregisterReceiver(deviceFailedReceiver);
unregisterReceiver(bluetoothReceiver);
mHandler.post(new Runnable() {
@Override
public void run() {
for (int i = 0; i < mConnections.length; i++) {
if (mConnectionIsBound[i]) {
mConnectionIsBound[i] = false;
mConnections[i].unbind();
}
}
}
});
mHandlerThread.quitSafely();
}
private synchronized Handler getHandler() {
return mHandler;
}
private void disconnect() {
for (int i = 0; i < mConnections.length; i++) {
disconnect(i);
}
}
private void disconnect(int row) {
DeviceServiceConnection connection = mConnections[row];
if (connection != null && connection.isRecording()) {
try {
connection.stopRecording();
} catch (RemoteException e) {
// it cannot be reached so it already stopped recording
}
}
}
/**
* If no E4Service is scanning, and ask one to start scanning.
*/
private void startScanning() {
if (isForcedDisconnected) {
return;
} else if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
enableBt();
return;
}
for (int i = 0; i < mConnections.length; i++) {
DeviceServiceConnection connection = mConnections[i];
if (connection == null || !connection.hasService() || connection.isRecording()) {
return;
}
Set<String> acceptableIds;
if (mInputDeviceKeys[i] != null && !mInputDeviceKeys[i].isEmpty()) {
acceptableIds = Collections.singleton(mInputDeviceKeys[i]);
} else {
acceptableIds = Collections.emptySet();
}
try {
connection.startRecording(acceptableIds);
} catch (RemoteException e) {
logger.error("Failed to start recording for device {}", i, e);
}
}
}
public void serviceConnected(final DeviceServiceConnection connection) {
try {
ServerStatusListener.Status status = connection.getServerStatus();
logger.info("Initial server status: {}", status);
updateServerStatus(status);
} catch (RemoteException e) {
logger.warn("Failed to update UI server status");
}
startScanning();
}
public synchronized void serviceDisconnected(final DeviceServiceConnection connection) {
mHandler.post(bindServicesRunner);
}
public void deviceStatusUpdated(final DeviceServiceConnection connection, final DeviceStatusListener.Status status) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, status.toString(), Toast.LENGTH_SHORT).show();
switch (status) {
case CONNECTED:
break;
case CONNECTING:
// statusLabel.setText("CONNECTING");
logger.info( "Device name is {} while connecting.", connection.getDeviceName() );
// Reject if device name inputted does not equal device nameA
if ( mInputDeviceKeys[0] != null && ! connection.isAllowedDevice( mInputDeviceKeys[0] ) ) {
logger.info( "Device name '{}' is not equal to '{}'", connection.getDeviceName(), mInputDeviceKeys[0]);
Toast.makeText(MainActivity.this, String.format("Device '%s' rejected", connection.getDeviceName() ), Toast.LENGTH_LONG).show();
// TODO: Clear device name [updateDeviceName( String.format("Device '%s' rejected", connection.getDeviceName() ), 0);]
disconnect();
}
break;
case DISCONNECTED:
startScanning();
break;
case READY:
break;
}
}
});
}
void enableBt() {
BluetoothAdapter btAdaptor = BluetoothAdapter.getDefaultAdapter();
if (!btAdaptor.isEnabled() && btAdaptor.getState() != BluetoothAdapter.STATE_TURNING_ON) {
Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
btIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(btIntent);
}
}
private void checkBluetoothPermissions() {
String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN};
boolean waitingForPermission = false;
for (String permission : permissions) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
waitingForPermission = true;
break;
}
}
if (waitingForPermission) {
ActivityCompat.requestPermissions(this, permissions, REQUEST_ENABLE_PERMISSIONS);
}
}
@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_ENABLE_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
startScanning();
} else {
// User refused to grant permission.
Toast.makeText(this, "Cannot connect to Empatica E4DeviceManager without location permissions", Toast.LENGTH_LONG).show();
}
}
}
public class DeviceUIUpdater implements Runnable {
/** Data formats **/
final DecimalFormat singleDecimal = new DecimalFormat("0.0");
final DecimalFormat noDecimals = new DecimalFormat("0");
final DeviceState[] deviceData;
final String[] deviceNames;
DeviceUIUpdater() {
deviceData = new DeviceState[mConnections.length];
deviceNames = new String[mConnections.length];
}
public void update() throws RemoteException {
for (int i = 0; i < mConnections.length; i++) {
if (mConnections[i] != null && mConnections[i].hasService()) {
deviceData[i] = mConnections[i].getDeviceData();
switch (deviceData[i].getStatus()) {
case CONNECTED: case CONNECTING:
deviceNames[i] = mConnections[i].getDeviceName();
break;
default:
deviceNames[i] = null;
break;
}
} else {
deviceData[i] = null;
deviceNames[i] = null;
}
}
runOnUiThread(this);
}
@Override
public void run() {
for (int i = 0; i < mConnections.length; i++) {
updateRow(deviceData[i], i);
updateDeviceName(deviceNames[i], i);
}
}
/**
* Updates a row with the deviceData
* @param deviceData data to update with
* @param row Row number
*/
public void updateRow(DeviceState deviceData, int row ) {
updateDeviceStatus(deviceData, row);
updateTemperature(deviceData, row);
updateBattery(deviceData, row);
}
public void updateDeviceStatus(DeviceState deviceData, int row ) {
// Connection status. Change icon used.
switch (deviceData == null ? DeviceStatusListener.Status.DISCONNECTED : deviceData.getStatus()) {
case CONNECTED:
mStatusIcons[row].setBackgroundResource( R.drawable.status_connected );
break;
case DISCONNECTED:
mStatusIcons[row].setBackgroundResource( R.drawable.status_disconnected );
break;
case READY:
case CONNECTING:
mStatusIcons[row].setBackgroundResource( R.drawable.status_searching );
break;
default:
mStatusIcons[row].setBackgroundResource( R.drawable.status_searching );
}
}
public void updateTemperature(DeviceState deviceData, int row ) {
// \u2103 == ℃
setText(mTemperatureLabels[row], deviceData == null ? Float.NaN : deviceData.getTemperature(), "\u2103", singleDecimal);
}
public void updateBattery(DeviceState deviceData, int row ) {
// Battery levels observed for E4 are 0.01, 0.1, 0.45 or 1
Float batteryLevel = deviceData == null ? Float.NaN : deviceData.getBatteryLevel();
// if ( row == 0 ) {logger.info("Battery: {}", batteryLevel);}
if ( batteryLevel.isNaN() ) {
mBatteryLabels[row].setImageResource( R.drawable.ic_battery_unknown );
// up to 100%
} else if ( batteryLevel > 0.5 ) {
mBatteryLabels[row].setImageResource( R.drawable.ic_battery_full );
// up to 45%
} else if ( batteryLevel > 0.2 ) {
mBatteryLabels[row].setImageResource( R.drawable.ic_battery_50 );
// up to 10%
} else if ( batteryLevel > 0.1 ) {
mBatteryLabels[row].setImageResource( R.drawable.ic_battery_low );
// up to 5% [what are possible values below 10%?]
} else {
mBatteryLabels[row].setImageResource( R.drawable.ic_battery_empty );
}
}
public void updateDeviceName(String deviceName, int row) {
// TODO: restrict n_characters of deviceName
if (deviceName == null) {
// \u2014 == —
mDeviceNameLabels[row].setText("\u2014");
} else {
mDeviceNameLabels[row].setText(deviceName);
}
}
private void setText(TextView label, float value, String suffix, DecimalFormat formatter) {
if (Float.isNaN(value)) {
// em dash
label.setText("\u2014");
} else {
label.setText(formatter.format(value) + " " + suffix);
}
}
}
public void connectDevice(View v) {
int rowIndex = getRowIndexFromView(v);
// will restart scanning after disconnect
disconnect(rowIndex);
}
public void showDetails(final View v) {
final int row = getRowIndexFromView(v);
mHandler.post(new Runnable() {
@Override
public void run() {
try {
mUIUpdater.update();
DeviceServiceConnection connection = mConnections[row];
if (connection == mE4Connection) {
new E4HeartbeatToast(MainActivity.this).execute(connection);
}
} catch (RemoteException e) {
logger.warn("Failed to update view with device data");
}
}
});
}
private int getRowIndexFromView(View v) {
// Assume all elements are direct descendants from the TableRow
View parent = (View) v.getParent();
switch ( parent.getId() ) {
case R.id.row1:
return 0;
case R.id.row2:
return 1;
case R.id.row3:
return 2;
case R.id.row4:
return 3;
default:
return -1; // TODO: throw exception
}
}
public void updateServerStatus( final ServerStatusListener.Status status ) {
// Update server status
runOnUiThread(new Runnable() {
@Override
public void run() {
switch (status) {
case CONNECTED:
mServerStatusIcon.setBackgroundResource( R.drawable.status_connected );
break;
case DISCONNECTED:
case DISABLED:
mServerStatusIcon.setBackgroundResource( R.drawable.status_disconnected );
break;
case READY:
case CONNECTING:
mServerStatusIcon.setBackgroundResource( R.drawable.status_searching );
break;
case UPLOADING:
mServerStatusIcon.setBackgroundResource( R.drawable.status_searching );
break;
default:
mServerStatusIcon.setBackgroundResource( R.drawable.status_searching );
}
}
});
}
public void dialogInputDeviceName(final View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Device Serial Number:");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final int row = getRowIndexFromView( v );
String oldValue = mInputDeviceKeys[row];
mInputDeviceKeys[row] = input.getText().toString();
mDeviceInputButtons[row].setText( mInputDeviceKeys[row] );
if (!mInputDeviceKeys[row].equals(oldValue) && !mInputDeviceKeys[row].isEmpty()) {
mHandler.post(new Runnable() {
@Override
public void run() {
try {
if (mConnections[row].isRecording()) {
mConnections[row].stopRecording();
// will restart recording once the status is set to disconnected.
}
} catch (RemoteException e) {
logger.error("Cannot restart scanning");
}
}
});
}
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
}
|
app/src/main/java/org/radarcns/empaticaE4/MainActivity.java
|
package org.radarcns.empaticaE4;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Process;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.radarcns.R;
import org.radarcns.android.DeviceServiceConnection;
import org.radarcns.android.DeviceState;
import org.radarcns.android.DeviceStatusListener;
import org.radarcns.kafka.rest.ServerStatusListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.Set;
import static org.radarcns.empaticaE4.E4Service.DEVICE_CONNECT_FAILED;
import static org.radarcns.empaticaE4.E4Service.DEVICE_STATUS_NAME;
import static org.radarcns.empaticaE4.E4Service.SERVER_STATUS_CHANGED;
public class MainActivity extends AppCompatActivity {
private final static Logger logger = LoggerFactory.getLogger(MainActivity.class);
private static final int REQUEST_ENABLE_PERMISSIONS = 2;
private long uiRefreshRate;
private HandlerThread mHandlerThread;
private Handler mHandler;
private Runnable mUIScheduler;
private DeviceUIUpdater mUIUpdater;
private boolean isForcedDisconnected;
private final boolean[] mConnectionIsBound;
/** Defines callbacks for service binding, passed to bindService() */
private final DeviceServiceConnection<E4DeviceStatus> mE4Connection;
private final BroadcastReceiver serverStatusListener;
private final BroadcastReceiver bluetoothReceiver;
private final BroadcastReceiver deviceFailedReceiver;
/** Connections. 0 = Empatica, 1 = Angel sensor **/
private DeviceServiceConnection[] mConnections;
/** Overview UI **/
private TextView[] mDeviceNameLabels;
private View[] mStatusIcons;
private View mServerStatusIcon;
private TextView[] mTemperatureLabels;
private ImageView[] mBatteryLabels;
private Button[] mDeviceInputButtons;
private String[] mInputDeviceKeys = new String[4];
private final Runnable bindServicesRunner = new Runnable() {
@Override
public void run() {
if (!mConnectionIsBound[0]) {
Intent e4serviceIntent = new Intent(MainActivity.this, E4Service.class);
e4serviceIntent.putExtra("kafka_rest_proxy_url", getString(R.string.kafka_rest_proxy_url));
e4serviceIntent.putExtra("schema_registry_url", getString(R.string.schema_registry_url));
e4serviceIntent.putExtra("group_id", getString(R.string.group_id));
e4serviceIntent.putExtra("empatica_api_key", getString(R.string.apikey));
mE4Connection.bind(e4serviceIntent);
mConnectionIsBound[0] = true;
}
}
};
public MainActivity() {
super();
isForcedDisconnected = false;
mE4Connection = new DeviceServiceConnection<>(this, E4DeviceStatus.CREATOR);
mConnections = new DeviceServiceConnection[] {mE4Connection, null, null, null};
mConnectionIsBound = new boolean[] {false, false, false, false};
serverStatusListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SERVER_STATUS_CHANGED)) {
final ServerStatusListener.Status status = ServerStatusListener.Status.values()[intent.getIntExtra(SERVER_STATUS_CHANGED, 0)];
updateServerStatus(status);
}
}
};
bluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
logger.info("Bluetooth state {}", state);
if (state == BluetoothAdapter.STATE_ON) {
logger.info("Bluetooth has turned on");
startScanning();
} else if (state == BluetoothAdapter.STATE_OFF) {
logger.warn("Bluetooth is off");
startScanning();
}
}
}
};
deviceFailedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, final Intent intent) {
if (intent.getAction().equals(DEVICE_CONNECT_FAILED)) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "Cannot connect to device " + intent.getStringExtra(DEVICE_STATUS_NAME), Toast.LENGTH_SHORT).show();
}
});
}
}
};
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overview);
// Create arrays of labels. Fixed to four rows
mDeviceNameLabels = new TextView[] {
(TextView) findViewById(R.id.deviceNameRow1),
(TextView) findViewById(R.id.deviceNameRow2),
(TextView) findViewById(R.id.deviceNameRow3),
(TextView) findViewById(R.id.deviceNameRow4)
};
mStatusIcons = new View[] {
findViewById(R.id.statusRow1),
findViewById(R.id.statusRow2),
findViewById(R.id.statusRow3),
findViewById(R.id.statusRow4)
};
mServerStatusIcon = findViewById(R.id.statusServer);
mTemperatureLabels = new TextView[] {
(TextView) findViewById(R.id.temperatureRow1),
(TextView) findViewById(R.id.temperatureRow2),
(TextView) findViewById(R.id.temperatureRow3),
(TextView) findViewById(R.id.temperatureRow4)
};
mBatteryLabels = new ImageView[] {
(ImageView) findViewById(R.id.batteryRow1),
(ImageView) findViewById(R.id.batteryRow2),
(ImageView) findViewById(R.id.batteryRow3),
(ImageView) findViewById(R.id.batteryRow4)
};
mDeviceInputButtons = new Button[] {
(Button) findViewById(R.id.inputDeviceNameButtonRow1),
(Button) findViewById(R.id.inputDeviceNameButtonRow2),
(Button) findViewById(R.id.inputDeviceNameButtonRow3),
(Button) findViewById(R.id.inputDeviceNameButtonRow4)
};
uiRefreshRate = getResources().getInteger(R.integer.ui_refresh_rate);
mUIUpdater = new DeviceUIUpdater();
mUIScheduler = new Runnable() {
@Override
public void run() {
try {
// Update all rows in the UI with the data from the connections
mUIUpdater.update();
} catch (RemoteException e) {
logger.warn("Failed to update device data", e);
} finally {
getHandler().postDelayed(mUIScheduler, uiRefreshRate);
}
}
};
checkBluetoothPermissions();
}
@Override
protected void onResume() {
logger.info("mainActivity onResume");
super.onResume();
mHandler.postDelayed(bindServicesRunner, 300L);
}
@Override
protected void onPause() {
logger.info("mainActivity onPause");
super.onPause();
mHandler.removeCallbacks(mUIScheduler);
}
@Override
protected void onStart() {
logger.info("mainActivity onStart");
super.onStart();
registerReceiver(bluetoothReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
registerReceiver(serverStatusListener, new IntentFilter(E4Service.SERVER_STATUS_CHANGED));
registerReceiver(deviceFailedReceiver, new IntentFilter(E4Service.DEVICE_CONNECT_FAILED));
mHandlerThread = new HandlerThread("E4Service connection", Process.THREAD_PRIORITY_BACKGROUND);
mHandlerThread.start();
synchronized (this) {
mHandler = new Handler(mHandlerThread.getLooper());
}
mHandler.post(mUIScheduler);
mHandler.post(new Runnable() {
@Override
public void run() {
for (int i = 0; i < mConnections.length; i++) {
mConnectionIsBound[i] = false;
}
}
});
}
@Override
protected void onStop() {
logger.info("mainActivity onStop");
super.onStop();
unregisterReceiver(serverStatusListener);
unregisterReceiver(deviceFailedReceiver);
unregisterReceiver(bluetoothReceiver);
mHandler.post(new Runnable() {
@Override
public void run() {
for (int i = 0; i < mConnections.length; i++) {
if (mConnectionIsBound[i]) {
mConnectionIsBound[i] = false;
mConnections[i].unbind();
}
}
}
});
mHandlerThread.quitSafely();
}
private synchronized Handler getHandler() {
return mHandler;
}
private void disconnect() {
for (int i = 0; i < mConnections.length; i++) {
disconnect(i);
}
}
private void disconnect(int row) {
DeviceServiceConnection connection = mConnections[row];
if (connection != null && connection.isRecording()) {
try {
connection.stopRecording();
} catch (RemoteException e) {
// it cannot be reached so it already stopped recording
}
}
}
/**
* If no E4Service is scanning, and ask one to start scanning.
*/
private void startScanning() {
if (isForcedDisconnected) {
return;
} else if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
enableBt();
return;
}
for (int i = 0; i < mConnections.length; i++) {
DeviceServiceConnection connection = mConnections[i];
if (connection == null || !connection.hasService() || connection.isRecording()) {
return;
}
Set<String> acceptableIds;
if (mInputDeviceKeys[i] != null && !mInputDeviceKeys[i].isEmpty()) {
acceptableIds = Collections.singleton(mInputDeviceKeys[i]);
} else {
acceptableIds = Collections.emptySet();
}
try {
connection.startRecording(acceptableIds);
} catch (RemoteException e) {
logger.error("Failed to start recording for device {}", i, e);
}
}
}
public void serviceConnected(final DeviceServiceConnection connection) {
try {
ServerStatusListener.Status status = connection.getServerStatus();
logger.info("Initial server status: {}", status);
updateServerStatus(status);
} catch (RemoteException e) {
logger.warn("Failed to update UI server status");
}
startScanning();
}
public synchronized void serviceDisconnected(final DeviceServiceConnection connection) {
mHandler.post(bindServicesRunner);
}
public void deviceStatusUpdated(final DeviceServiceConnection connection, final DeviceStatusListener.Status status) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, status.toString(), Toast.LENGTH_SHORT).show();
switch (status) {
case CONNECTED:
break;
case CONNECTING:
// statusLabel.setText("CONNECTING");
logger.info( "Device name is {} while connecting.", connection.getDeviceName() );
// Reject if device name inputted does not equal device nameA
if ( mInputDeviceKeys[0] != null && ! connection.isAllowedDevice( mInputDeviceKeys[0] ) ) {
logger.info( "Device name '{}' is not equal to '{}'", connection.getDeviceName(), mInputDeviceKeys[0]);
Toast.makeText(MainActivity.this, String.format("Device '%s' rejected", connection.getDeviceName() ), Toast.LENGTH_LONG).show();
// TODO: Clear device name [updateDeviceName( String.format("Device '%s' rejected", connection.getDeviceName() ), 0);]
disconnect();
}
break;
case DISCONNECTED:
startScanning();
break;
case READY:
break;
}
}
});
}
void enableBt() {
BluetoothAdapter btAdaptor = BluetoothAdapter.getDefaultAdapter();
if (!btAdaptor.isEnabled() && btAdaptor.getState() != BluetoothAdapter.STATE_TURNING_ON) {
Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
btIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(btIntent);
}
}
private void checkBluetoothPermissions() {
String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN};
boolean waitingForPermission = false;
for (String permission : permissions) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
waitingForPermission = true;
break;
}
}
if (waitingForPermission) {
ActivityCompat.requestPermissions(this, permissions, REQUEST_ENABLE_PERMISSIONS);
}
}
@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_ENABLE_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
startScanning();
} else {
// User refused to grant permission.
Toast.makeText(this, "Cannot connect to Empatica E4DeviceManager without location permissions", Toast.LENGTH_LONG).show();
}
}
}
public class DeviceUIUpdater implements Runnable {
/** Data formats **/
final DecimalFormat singleDecimal = new DecimalFormat("0.0");
final DecimalFormat noDecimals = new DecimalFormat("0");
final DeviceState[] deviceData;
final String[] deviceNames;
DeviceUIUpdater() {
deviceData = new DeviceState[mConnections.length];
deviceNames = new String[mConnections.length];
}
public void update() throws RemoteException {
for (int i = 0; i < mConnections.length; i++) {
if (mConnections[i] != null && mConnections[i].hasService()) {
deviceData[i] = mConnections[i].getDeviceData();
switch (deviceData[i].getStatus()) {
case CONNECTED: case CONNECTING:
deviceNames[i] = mConnections[i].getDeviceName();
break;
default:
deviceNames[i] = null;
break;
}
} else {
deviceData[i] = null;
deviceNames[i] = null;
}
}
runOnUiThread(this);
}
@Override
public void run() {
for (int i = 0; i < mConnections.length; i++) {
updateRow(deviceData[i], i);
updateDeviceName(deviceNames[i], i);
}
}
/**
* Updates a row with the deviceData
* @param deviceData data to update with
* @param row Row number
*/
public void updateRow(DeviceState deviceData, int row ) {
updateDeviceStatus(deviceData, row);
updateTemperature(deviceData, row);
updateBattery(deviceData, row);
}
public void updateDeviceStatus(DeviceState deviceData, int row ) {
// Connection status. Change icon used.
switch (deviceData == null ? DeviceStatusListener.Status.DISCONNECTED : deviceData.getStatus()) {
case CONNECTED:
mStatusIcons[row].setBackgroundResource( R.drawable.status_connected );
break;
case DISCONNECTED:
mStatusIcons[row].setBackgroundResource( R.drawable.status_disconnected );
break;
case READY:
case CONNECTING:
mStatusIcons[row].setBackgroundResource( R.drawable.status_searching );
break;
default:
mStatusIcons[row].setBackgroundResource( R.drawable.status_searching );
}
}
public void updateTemperature(DeviceState deviceData, int row ) {
// \u2103 == ℃
setText(mTemperatureLabels[row], deviceData == null ? Float.NaN : deviceData.getTemperature(), "\u2103", singleDecimal);
}
public void updateBattery(DeviceState deviceData, int row ) {
// Battery levels observed for E4 are 10, 45 or 100%
Float batteryLevel = deviceData == null ? Float.NaN : deviceData.getBatteryLevel();
if ( batteryLevel.isNaN() ) {
mBatteryLabels[row].setImageResource( R.drawable.ic_battery_unknown );
// up to 100%
} else if ( batteryLevel > 0.45 ) {
mBatteryLabels[row].setImageResource( R.drawable.ic_battery_full );
// up to 45%
} else if ( batteryLevel > 0.10 ) {
mBatteryLabels[row].setImageResource( R.drawable.ic_battery_50 );
// up to 10%
} else if ( batteryLevel > 0.05 ) {
mBatteryLabels[row].setImageResource( R.drawable.ic_battery_low );
// up to 5% [what are possible values below 10%?]
} else {
mBatteryLabels[row].setImageResource( R.drawable.ic_battery_empty );
}
}
public void updateDeviceName(String deviceName, int row) {
// TODO: restrict n_characters of deviceName
if (deviceName == null) {
// \u2014 == —
mDeviceNameLabels[row].setText("\u2014");
} else {
mDeviceNameLabels[row].setText(deviceName);
}
}
private void setText(TextView label, float value, String suffix, DecimalFormat formatter) {
if (Float.isNaN(value)) {
// em dash
label.setText("\u2014");
} else {
label.setText(formatter.format(value) + " " + suffix);
}
}
}
public void connectDevice(View v) {
int rowIndex = getRowIndexFromView(v);
// will restart scanning after disconnect
disconnect(rowIndex);
}
public void showDetails(final View v) {
final int row = getRowIndexFromView(v);
mHandler.post(new Runnable() {
@Override
public void run() {
try {
mUIUpdater.update();
DeviceServiceConnection connection = mConnections[row];
if (connection == mE4Connection) {
new E4HeartbeatToast(MainActivity.this).execute(connection);
}
} catch (RemoteException e) {
logger.warn("Failed to update view with device data");
}
}
});
}
private int getRowIndexFromView(View v) {
// Assume all elements are direct descendants from the TableRow
View parent = (View) v.getParent();
switch ( parent.getId() ) {
case R.id.row1:
return 0;
case R.id.row2:
return 1;
case R.id.row3:
return 2;
case R.id.row4:
return 3;
default:
return -1; // TODO: throw exception
}
}
public void updateServerStatus( final ServerStatusListener.Status status ) {
// Update server status
runOnUiThread(new Runnable() {
@Override
public void run() {
switch (status) {
case CONNECTED:
mServerStatusIcon.setBackgroundResource( R.drawable.status_connected );
break;
case DISCONNECTED:
case DISABLED:
mServerStatusIcon.setBackgroundResource( R.drawable.status_disconnected );
break;
case READY:
case CONNECTING:
mServerStatusIcon.setBackgroundResource( R.drawable.status_searching );
break;
case UPLOADING:
mServerStatusIcon.setBackgroundResource( R.drawable.status_searching );
break;
default:
mServerStatusIcon.setBackgroundResource( R.drawable.status_searching );
}
}
});
}
public void dialogInputDeviceName(final View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Device Serial Number:");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final int row = getRowIndexFromView( v );
String oldValue = mInputDeviceKeys[row];
mInputDeviceKeys[row] = input.getText().toString();
mDeviceInputButtons[row].setText( mInputDeviceKeys[row] );
if (!mInputDeviceKeys[row].equals(oldValue) && !mInputDeviceKeys[row].isEmpty()) {
mHandler.post(new Runnable() {
@Override
public void run() {
try {
if (mConnections[row].isRecording()) {
mConnections[row].stopRecording();
// will restart recording once the status is set to disconnected.
}
} catch (RemoteException e) {
logger.error("Cannot restart scanning");
}
}
});
}
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
}
|
Generalized the battery level breaks
|
app/src/main/java/org/radarcns/empaticaE4/MainActivity.java
|
Generalized the battery level breaks
|
|
Java
|
apache-2.0
|
44b87ce4fb8cab3ee83bccbaf23bde890a22f180
| 0
|
ouit0408/sakai,puramshetty/sakai,tl-its-umich-edu/sakai,pushyamig/sakai,rodriguezdevera/sakai,zqian/sakai,rodriguezdevera/sakai,kwedoff1/sakai,buckett/sakai-gitflow,puramshetty/sakai,lorenamgUMU/sakai,lorenamgUMU/sakai,liubo404/sakai,joserabal/sakai,pushyamig/sakai,frasese/sakai,lorenamgUMU/sakai,lorenamgUMU/sakai,ouit0408/sakai,wfuedu/sakai,kingmook/sakai,conder/sakai,pushyamig/sakai,bkirschn/sakai,surya-janani/sakai,zqian/sakai,noondaysun/sakai,buckett/sakai-gitflow,liubo404/sakai,bkirschn/sakai,hackbuteer59/sakai,liubo404/sakai,liubo404/sakai,Fudan-University/sakai,noondaysun/sakai,colczr/sakai,liubo404/sakai,surya-janani/sakai,Fudan-University/sakai,ouit0408/sakai,bzhouduke123/sakai,bzhouduke123/sakai,ouit0408/sakai,duke-compsci290-spring2016/sakai,colczr/sakai,joserabal/sakai,wfuedu/sakai,conder/sakai,kingmook/sakai,bzhouduke123/sakai,kwedoff1/sakai,frasese/sakai,clhedrick/sakai,rodriguezdevera/sakai,ktakacs/sakai,hackbuteer59/sakai,colczr/sakai,frasese/sakai,hackbuteer59/sakai,noondaysun/sakai,puramshetty/sakai,OpenCollabZA/sakai,clhedrick/sakai,introp-software/sakai,OpenCollabZA/sakai,bkirschn/sakai,bkirschn/sakai,surya-janani/sakai,bzhouduke123/sakai,clhedrick/sakai,bzhouduke123/sakai,whumph/sakai,joserabal/sakai,hackbuteer59/sakai,noondaysun/sakai,kingmook/sakai,ktakacs/sakai,wfuedu/sakai,introp-software/sakai,whumph/sakai,whumph/sakai,tl-its-umich-edu/sakai,clhedrick/sakai,udayg/sakai,buckett/sakai-gitflow,pushyamig/sakai,OpenCollabZA/sakai,udayg/sakai,buckett/sakai-gitflow,ktakacs/sakai,joserabal/sakai,surya-janani/sakai,liubo404/sakai,colczr/sakai,bzhouduke123/sakai,bkirschn/sakai,OpenCollabZA/sakai,duke-compsci290-spring2016/sakai,rodriguezdevera/sakai,pushyamig/sakai,wfuedu/sakai,lorenamgUMU/sakai,pushyamig/sakai,zqian/sakai,tl-its-umich-edu/sakai,hackbuteer59/sakai,zqian/sakai,noondaysun/sakai,Fudan-University/sakai,buckett/sakai-gitflow,udayg/sakai,frasese/sakai,kingmook/sakai,ktakacs/sakai,puramshetty/sakai,rodriguezdevera/sakai,duke-compsci290-spring2016/sakai,introp-software/sakai,willkara/sakai,colczr/sakai,liubo404/sakai,wfuedu/sakai,surya-janani/sakai,tl-its-umich-edu/sakai,bkirschn/sakai,frasese/sakai,wfuedu/sakai,hackbuteer59/sakai,kwedoff1/sakai,Fudan-University/sakai,joserabal/sakai,surya-janani/sakai,ouit0408/sakai,whumph/sakai,noondaysun/sakai,surya-janani/sakai,duke-compsci290-spring2016/sakai,joserabal/sakai,kingmook/sakai,bzhouduke123/sakai,buckett/sakai-gitflow,introp-software/sakai,udayg/sakai,bkirschn/sakai,pushyamig/sakai,puramshetty/sakai,conder/sakai,noondaysun/sakai,ktakacs/sakai,bkirschn/sakai,conder/sakai,zqian/sakai,frasese/sakai,hackbuteer59/sakai,whumph/sakai,ktakacs/sakai,pushyamig/sakai,udayg/sakai,tl-its-umich-edu/sakai,whumph/sakai,lorenamgUMU/sakai,tl-its-umich-edu/sakai,introp-software/sakai,udayg/sakai,colczr/sakai,kwedoff1/sakai,kwedoff1/sakai,clhedrick/sakai,rodriguezdevera/sakai,rodriguezdevera/sakai,zqian/sakai,whumph/sakai,willkara/sakai,willkara/sakai,Fudan-University/sakai,ouit0408/sakai,lorenamgUMU/sakai,zqian/sakai,introp-software/sakai,clhedrick/sakai,wfuedu/sakai,clhedrick/sakai,clhedrick/sakai,ouit0408/sakai,zqian/sakai,Fudan-University/sakai,liubo404/sakai,tl-its-umich-edu/sakai,rodriguezdevera/sakai,willkara/sakai,kwedoff1/sakai,kingmook/sakai,Fudan-University/sakai,willkara/sakai,tl-its-umich-edu/sakai,ktakacs/sakai,colczr/sakai,hackbuteer59/sakai,introp-software/sakai,frasese/sakai,buckett/sakai-gitflow,introp-software/sakai,puramshetty/sakai,kwedoff1/sakai,colczr/sakai,OpenCollabZA/sakai,kingmook/sakai,lorenamgUMU/sakai,buckett/sakai-gitflow,udayg/sakai,duke-compsci290-spring2016/sakai,willkara/sakai,ktakacs/sakai,willkara/sakai,duke-compsci290-spring2016/sakai,OpenCollabZA/sakai,surya-janani/sakai,conder/sakai,conder/sakai,OpenCollabZA/sakai,bzhouduke123/sakai,ouit0408/sakai,frasese/sakai,udayg/sakai,conder/sakai,wfuedu/sakai,whumph/sakai,kingmook/sakai,willkara/sakai,puramshetty/sakai,joserabal/sakai,OpenCollabZA/sakai,Fudan-University/sakai,joserabal/sakai,kwedoff1/sakai,duke-compsci290-spring2016/sakai,noondaysun/sakai,puramshetty/sakai,conder/sakai,duke-compsci290-spring2016/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.assignment.impl;
import au.com.bytecode.opencsv.CSVWriter;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.WorkbookUtil;
import org.sakaiproject.announcement.api.AnnouncementChannel;
import org.sakaiproject.announcement.api.AnnouncementService;
import org.sakaiproject.assignment.api.*;
import org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer;
import org.sakaiproject.authz.api.*;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.authz.cover.FunctionManager;
import org.sakaiproject.calendar.api.Calendar;
import org.sakaiproject.calendar.api.CalendarEvent;
import org.sakaiproject.calendar.api.CalendarService;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.content.util.ZipContentUtil;
import org.sakaiproject.contentreview.exception.QueueException;
import org.sakaiproject.contentreview.exception.ReportException;
import org.sakaiproject.contentreview.exception.SubmissionException;
import org.sakaiproject.contentreview.model.ContentReviewItem;
import org.sakaiproject.contentreview.service.ContentReviewService;
import org.sakaiproject.email.cover.DigestService;
import org.sakaiproject.email.cover.EmailService;
import org.sakaiproject.entity.api.*;
import org.sakaiproject.event.api.Event;
import org.sakaiproject.event.api.LearningResourceStoreService;
import org.sakaiproject.event.api.LearningResourceStoreService.*;
import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Verb.SAKAI_VERB;
import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.event.cover.NotificationService;
import org.sakaiproject.exception.*;
import org.sakaiproject.id.cover.IdManager;
import org.sakaiproject.memory.api.MemoryService;
import org.sakaiproject.service.gradebook.shared.GradebookExternalAssessmentService;
import org.sakaiproject.service.gradebook.shared.GradebookService;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.taggable.api.TaggingManager;
import org.sakaiproject.taggable.api.TaggingProvider;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.SessionBindingEvent;
import org.sakaiproject.tool.api.SessionBindingListener;
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.util.*;
import org.sakaiproject.util.cover.LinkMigrationHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.Normalizer;
import java.text.NumberFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* <p>
* BaseAssignmentService is the abstract service class for Assignments.
* </p>
* <p>
* The Concrete Service classes extending this are the XmlFile and DbCached storage classes.
* </p>
*/
public abstract class BaseAssignmentService implements AssignmentService, EntityTransferrer, EntityTransferrerRefMigrator
{
/** Our logger. */
private static Log M_log = LogFactory.getLog(BaseAssignmentService.class);
/** the resource bundle */
private static ResourceLoader rb = new ResourceLoader("assignment");
/** A Storage object for persistent storage of Assignments. */
protected AssignmentStorage m_assignmentStorage = null;
/** A Storage object for persistent storage of Assignments. */
protected AssignmentContentStorage m_contentStorage = null;
/** A Storage object for persistent storage of Assignments. */
protected AssignmentSubmissionStorage m_submissionStorage = null;
/** The access point URL. */
protected static String m_relativeAccessPoint = null;
private static final String NEW_ASSIGNMENT_DUE_DATE_SCHEDULED = "new_assignment_due_date_scheduled";
protected static final String GROUP_LIST = "group";
protected static final String GROUP_NAME = "authzGroup";
protected static final String GROUP_SECTION_PROPERTY = "sections_category";
// the file types for zip download
protected static final String ZIP_COMMENT_FILE_TYPE = ".txt";
protected static final String ZIP_SUBMITTED_TEXT_FILE_TYPE = ".html";
// spring service injection
protected ContentReviewService contentReviewService;
public void setContentReviewService(ContentReviewService contentReviewService) {
this.contentReviewService = contentReviewService;
}
private AssignmentPeerAssessmentService assignmentPeerAssessmentService = null;
public void setAssignmentPeerAssessmentService(AssignmentPeerAssessmentService assignmentPeerAssessmentService){
this.assignmentPeerAssessmentService = assignmentPeerAssessmentService;
}
private SecurityService securityService = null;
public void setSecurityService(SecurityService securityService){
this.securityService = securityService;
}
String newline = "<br />\n";
/**********************************************************************************************************************************************************************************************************************************************************
* Abstractions, etc.
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Construct a Storage object for Assignments.
*
* @return The new storage object.
*/
protected abstract AssignmentStorage newAssignmentStorage();
/**
* Construct a Storage object for AssignmentContents.
*
* @return The new storage object.
*/
protected abstract AssignmentContentStorage newContentStorage();
/**
* Construct a Storage object for AssignmentSubmissions.
*
* @return The new storage object.
*/
protected abstract AssignmentSubmissionStorage newSubmissionStorage();
/**
* Access the partial URL that forms the root of resource URLs.
*
* @param relative -
* if true, form within the access path only (i.e. starting with /msg)
* @return the partial URL that forms the root of resource URLs.
*/
static protected String getAccessPoint(boolean relative)
{
return (relative ? "" : m_serverConfigurationService.getAccessUrl()) + m_relativeAccessPoint;
} // getAccessPoint
/**
* Access the internal reference which can be used to assess security clearance.
*
* @param id
* The assignment id string.
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String assignmentReference(String context, String id)
{
String retVal = null;
if (context == null)
retVal = getAccessPoint(true) + Entity.SEPARATOR + "a" + Entity.SEPARATOR + id;
else
retVal = getAccessPoint(true) + Entity.SEPARATOR + "a" + Entity.SEPARATOR + context + Entity.SEPARATOR + id;
return retVal;
} // assignmentReference
/**
* I feel silly having to look up the entire assignment object just to get the reference,
* but if there's no context, that seems to be the only way to do it.
* @param id
* @return
*/
public String assignmentReference(String id) {
String ref = null;
Assignment assignment = findAssignment(id);
if (assignment != null)
ref = assignment.getReference();
return ref;
} // assignmentReference
public List getSortedGroupUsers(Group _g) {
List retVal = new ArrayList();
Iterator<Member> _members = _g.getMembers().iterator();
while (_members.hasNext()) {
Member _member = _members.next();
try
{
retVal.add(UserDirectoryService.getUser(_member.getUserId()));
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission Group getSubmitters" + e.getMessage() + _member.getUserId());
}
}
java.util.Collections.sort(retVal, new UserComparator());
return retVal;
}
/**
* Access the internal reference which can be used to access the resource from within the system.
*
* @param id
* The content id string.
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String contentReference(String context, String id)
{
String retVal = null;
if (context == null)
retVal = getAccessPoint(true) + Entity.SEPARATOR + "c" + Entity.SEPARATOR + id;
else
retVal = getAccessPoint(true) + Entity.SEPARATOR + "c" + Entity.SEPARATOR + context + Entity.SEPARATOR + id;
return retVal;
} // contentReference
/**
* Access the internal reference which can be used to access the resource from within the system.
*
* @param id
* The submission id string.
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String submissionReference(String context, String id, String assignmentId)
{
String retVal = null;
if (context == null)
retVal = getAccessPoint(true) + Entity.SEPARATOR + "s" + Entity.SEPARATOR + id;
else
retVal = getAccessPoint(true) + Entity.SEPARATOR + "s" + Entity.SEPARATOR + context + Entity.SEPARATOR + assignmentId
+ Entity.SEPARATOR + id;
return retVal;
} // submissionReference
/**
* Access the assignment id extracted from an assignment reference.
*
* @param ref
* The assignment reference string.
* @return The the assignment id extracted from an assignment reference.
*/
protected String assignmentId(String ref)
{
if (ref == null) return ref;
int i = ref.lastIndexOf(Entity.SEPARATOR);
if (i == -1) return ref;
String id = ref.substring(i + 1);
return id;
} // assignmentId
/**
* Access the content id extracted from a content reference.
*
* @param ref
* The content reference string.
* @return The the content id extracted from a content reference.
*/
protected String contentId(String ref)
{
int i = ref.lastIndexOf(Entity.SEPARATOR);
if (i == -1) return ref;
String id = ref.substring(i + 1);
return id;
} // contentId
/**
* Access the submission id extracted from a submission reference.
*
* @param ref
* The submission reference string.
* @return The the submission id extracted from a submission reference.
*/
protected String submissionId(String ref)
{
int i = ref.lastIndexOf(Entity.SEPARATOR);
if (i == -1) return ref;
String id = ref.substring(i + 1);
return id;
} // submissionId
/**
* Check security permission.
*
* @param lock -
* The lock id string.
* @param resource -
* The resource reference string, or null if no resource is involved.
* @return true if allowed, false if not
*/
protected boolean unlockCheck(String lock, String resource)
{
if (!securityService.unlock(lock, resource))
{
return false;
}
return true;
}// unlockCheck
/**
* SAK-21525 Groups need to be queried, not just the site.
*
* @param lock The security function to be checked, 'asn.submit' for example.
* @param resource The resource to be accessed
* @param assignment An Assignment object. We use this for the group checks.
* @return
*/
protected boolean unlockCheckWithGroups(String lock, String resource, Assignment assignment)
{
// SAK-23755 addons:
// super user should be allowed
if (securityService.isSuperUser())
return true;
// all.groups permission should apply down to group level
String context = assignment.getContext();
String userId = SessionManager.getCurrentSessionUserId();
if (allowAllGroups(context) && securityService.unlock(lock, SiteService.siteReference(context)))
{
return true;
}
// group level users
Collection groupIds = null;
//SAK-23235 this method can be passed a null assignment -DH
if (assignment != null)
{
groupIds = assignment.getGroups();
}
if(groupIds != null && groupIds.size() > 0)
{
Iterator i = groupIds.iterator();
while(i.hasNext())
{
String groupId = (String) i.next();
boolean isAllowed
= securityService.unlock(lock,groupId);
if(isAllowed) return true;
}
if (SECURE_ADD_ASSIGNMENT_SUBMISSION.equals(lock) && assignment.isGroup())
return securityService.unlock(lock, resource);
else
return false;
}
else
{
return securityService.unlock(lock, SiteService.siteReference(context));
}
}// unlockCheckWithGroups
/**
* Check security permission.
*
* @param lock1
* The lock id string.
* @param lock2
* The lock id string.
* @param resource
* The resource reference string, or null if no resource is involved.
* @return true if either allowed, false if not
*/
protected boolean unlockCheck2(String lock1, String lock2, String resource)
{
// check the first lock
if (securityService.unlock(lock1, resource)) return true;
// if the second is different, check that
if ((!lock1.equals(lock2)) && (securityService.unlock(lock2, resource))) return true;
return false;
} // unlockCheck2
/**
* Check security permission.
*
* @param lock -
* The lock id string.
* @param resource -
* The resource reference string, or null if no resource is involved.
* @exception PermissionException
* Thrown if the user does not have access
*/
protected void unlock(String lock, String resource) throws PermissionException
{
if (!unlockCheck(lock, resource))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), lock, resource);
}
} // unlock
/**
* Check security permission.
*
* @param lock1
* The lock id string.
* @param lock2
* The lock id string.
* @param resource
* The resource reference string, or null if no resource is involved.
* @exception PermissionException
* Thrown if the user does not have access to either.
*/
protected void unlock2(String lock1, String lock2, String resource) throws PermissionException
{
if (!unlockCheck2(lock1, lock2, resource))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), lock1 + "/" + lock2, resource);
}
} // unlock2
/**********************************************************************************************************************************************************************************************************************************************************
* Dependencies and their setter methods
*********************************************************************************************************************************************************************************************************************************************************/
/** Dependency: MemoryService. */
protected MemoryService m_memoryService = null;
/**
* Dependency: MemoryService.
*
* @param service
* The MemoryService.
*/
public void setMemoryService(MemoryService service)
{
m_memoryService = service;
}
/** Dependency: ContentHostingService. */
protected ContentHostingService m_contentHostingService = null;
/**
* Dependency:ContentHostingService.
*
* @param service
* The ContentHostingService.
*/
public void setContentHostingService(ContentHostingService service)
{
m_contentHostingService = service;
}
/**
* Configuration: set the locks-in-db
*
* @param value true or false
* @deprecated 7 April 2014 - this has no effect anymore and should be removed in 11 release
*/
public void setCaching(String value) {} // intentionally blank
/** Dependency: EntityManager. */
protected EntityManager m_entityManager = null;
/**
* Dependency: EntityManager.
*
* @param service
* The EntityManager.
*/
public void setEntityManager(EntityManager service)
{
m_entityManager = service;
}
/** Dependency: ServerConfigurationService. */
static protected ServerConfigurationService m_serverConfigurationService = null;
/**
* Dependency: ServerConfigurationService.
*
* @param service
* The ServerConfigurationService.
*/
public void setServerConfigurationService(ServerConfigurationService service)
{
m_serverConfigurationService = service;
}
/** Dependency: TaggingManager. */
protected TaggingManager m_taggingManager = null;
/**
* Dependency: TaggingManager.
*
* @param manager
* The TaggingManager.
*/
public void setTaggingManager(TaggingManager manager)
{
m_taggingManager = manager;
}
/** Dependency: AssignmentActivityProducer. */
protected AssignmentActivityProducer m_assignmentActivityProducer = null;
/**
* Dependency: AssignmentActivityProducer.
*
* @param assignmentActivityProducer
* The AssignmentActivityProducer.
*/
public void setAssignmentActivityProducer(AssignmentActivityProducer assignmentActivityProducer)
{
m_assignmentActivityProducer = assignmentActivityProducer;
}
/** Dependency: GradebookService. */
protected GradebookService m_gradebookService = null;
/**
* Dependency: GradebookService
*
* @param gradebookService
* The GradebookService
*/
public void setGradebookService(GradebookService gradebookService)
{
m_gradebookService= gradebookService;
}
/** Dependency: GradebookExternalAssessmentService. */
protected GradebookExternalAssessmentService m_gradebookExternalAssessmentService = null;
/**
* Dependency: GradebookExternalAssessmentService
*
* @param gradebookExternalAssessmentService
* The GradebookExternalAssessmentService
*/
public void setGradebookExternalAssessmentService(GradebookExternalAssessmentService gradebookExternalAssessmentService)
{
m_gradebookExternalAssessmentService= gradebookExternalAssessmentService;
}
/** Dependency: CalendarService. */
protected CalendarService m_calendarService = null;
/**
* Dependency: CalendarService
*
* @param calendarService
* The CalendarService
*/
public void setCalendarService(CalendarService calendarService)
{
m_calendarService= calendarService;
}
/** Dependency: AnnouncementService. */
protected AnnouncementService m_announcementService = null;
/**
* Dependency: AnnouncementService
*
* @param announcementService
* The AnnouncementService
*/
public void setAnnouncementService(AnnouncementService announcementService)
{
m_announcementService= announcementService;
}
/** Dependency: allowGroupAssignments setting */
protected boolean m_allowGroupAssignments = true;
/**
* Dependency: allowGroupAssignments
*
* @param allowGroupAssignments
* the setting
*/
public void setAllowGroupAssignments(boolean allowGroupAssignments)
{
m_allowGroupAssignments = allowGroupAssignments;
}
/**
* Get
*
* @return allowGroupAssignments
*/
public boolean getAllowGroupAssignments()
{
return m_allowGroupAssignments;
}
/** Dependency: allowSubmitByInstructor setting */
protected boolean m_allowSubmitByInstructor = true;
/**
* Dependency: allowSubmitByInstructor
*
* @param allowSubmitByInstructor
* the setting
*/
public void setAllowSubmitByInstructor(boolean allowSubmitByInstructor)
{
m_allowSubmitByInstructor = allowSubmitByInstructor;
}
/**
* Get
*
* @return allowSubmitByInstructor
*/
public boolean getAllowSubmitByInstructor()
{
return m_allowSubmitByInstructor;
}
/** Dependency: allowGroupAssignmentsInGradebook setting */
protected boolean m_allowGroupAssignmentsInGradebook = true;
/**
* Dependency: allowGroupAssignmentsInGradebook
*
* @param allowGroupAssignmentsInGradebook
*/
public void setAllowGroupAssignmentsInGradebook(boolean allowGroupAssignmentsInGradebook)
{
m_allowGroupAssignmentsInGradebook = allowGroupAssignmentsInGradebook;
}
/**
* Get
*
* @return allowGroupAssignmentsGradebook
*/
public boolean getAllowGroupAssignmentsInGradebook()
{
return m_allowGroupAssignmentsInGradebook;
}
/**********************************************************************************************************************************************************************************************************************************************************
* Init and Destroy
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Final initialization, once all dependencies are set.
*/
public void init()
{
m_relativeAccessPoint = REFERENCE_ROOT;
M_log.info(this + " init()");
// construct storage helpers and read
m_assignmentStorage = newAssignmentStorage();
m_assignmentStorage.open();
m_contentStorage = newContentStorage();
m_contentStorage.open();
m_submissionStorage = newSubmissionStorage();
m_submissionStorage.open();
m_allowSubmitByInstructor = m_serverConfigurationService.getBoolean("assignments.instructor.submit.for.student", true);
if (!m_allowSubmitByInstructor) {
M_log.info("Instructor submission of assignments is disabled - add assignments.instructor.submit.for.student=true to sakai config to enable");
} else {
M_log.info("Instructor submission of assignments is enabled");
}
// register as an entity producer
m_entityManager.registerEntityProducer(this, REFERENCE_ROOT);
// register functions
FunctionManager.registerFunction(SECURE_ALL_GROUPS);
FunctionManager.registerFunction(SECURE_ADD_ASSIGNMENT);
FunctionManager.registerFunction(SECURE_ADD_ASSIGNMENT_SUBMISSION);
FunctionManager.registerFunction(SECURE_REMOVE_ASSIGNMENT);
FunctionManager.registerFunction(SECURE_ACCESS_ASSIGNMENT);
FunctionManager.registerFunction(SECURE_UPDATE_ASSIGNMENT);
FunctionManager.registerFunction(SECURE_GRADE_ASSIGNMENT_SUBMISSION);
FunctionManager.registerFunction(SECURE_ASSIGNMENT_RECEIVE_NOTIFICATIONS);
FunctionManager.registerFunction(SECURE_SHARE_DRAFTS);
//if no contentReviewService was set try discovering it
if (contentReviewService == null)
{
contentReviewService = (ContentReviewService) ComponentManager.get(ContentReviewService.class.getName());
}
} // init
/**
* Returns to uninitialized state.
*/
public void destroy()
{
m_assignmentStorage.close();
m_assignmentStorage = null;
m_contentStorage.close();
m_contentStorage = null;
m_submissionStorage.close();
m_submissionStorage = null;
M_log.info(this + " destroy()");
}
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentService implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Creates and adds a new Assignment to the service.
*
* @param context -
* Describes the portlet context - generated with DefaultId.getChannel().
* @return The new Assignment object.
* @throws IdInvalidException
* if the id contains prohibited characers.
* @throws IdUsedException
* if the id is already used in the service.
* @throws PermissionException
* if current User does not have permission to do this.
*/
public AssignmentEdit addAssignment(String context) throws PermissionException
{
M_log.debug(this + " ENTERING ADD ASSIGNMENT : CONTEXT : " + context);
String assignmentId = null;
boolean badId = false;
do
{
badId = !Validator.checkResourceId(assignmentId);
assignmentId = IdManager.createUuid();
if (m_assignmentStorage.check(assignmentId)) badId = true;
}
while (badId);
String key = assignmentReference(context, assignmentId);
// security check
if (!allowAddAssignment(context))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), SECURE_ADD_ASSIGNMENT, key);
}
// storage
AssignmentEdit assignment = m_assignmentStorage.put(assignmentId, context);
// event for tracking
((BaseAssignmentEdit) assignment).setEvent(AssignmentConstants.EVENT_ADD_ASSIGNMENT);
M_log.debug(this + " LEAVING ADD ASSIGNMENT WITH : ID : " + assignment.getId());
return assignment;
} // addAssignment
/**
* Add a new assignment to the directory, from a definition in XML. Must commitEdit() to make official, or cancelEdit() when done!
*
* @param el
* The XML DOM Element defining the assignment.
* @return A locked AssignmentEdit object (reserving the id).
* @exception IdInvalidException
* if the assignment id is invalid.
* @exception IdUsedException
* if the assignment id is already used.
* @exception PermissionException
* if the current user does not have permission to add an assignnment.
*/
public AssignmentEdit mergeAssignment(Element el) throws IdInvalidException, IdUsedException, PermissionException
{
// construct from the XML
Assignment assignmentFromXml = new BaseAssignment(el);
// check for a valid assignment name
if (!Validator.checkResourceId(assignmentFromXml.getId())) throw new IdInvalidException(assignmentFromXml.getId());
// check security (throws if not permitted)
unlock(SECURE_ADD_ASSIGNMENT, assignmentFromXml.getReference());
// reserve a assignment with this id from the info store - if it's in use, this will return null
AssignmentEdit assignment = m_assignmentStorage.put(assignmentFromXml.getId(), assignmentFromXml.getContext());
if (assignment == null)
{
throw new IdUsedException(assignmentFromXml.getId());
}
// transfer from the XML read assignment object to the AssignmentEdit
((BaseAssignmentEdit) assignment).set(assignmentFromXml);
((BaseAssignmentEdit) assignment).setEvent(AssignmentConstants.EVENT_ADD_ASSIGNMENT);
ResourcePropertiesEdit propertyEdit = (BaseResourcePropertiesEdit)assignment.getProperties();
try
{
propertyEdit.getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
}
catch(EntityPropertyNotDefinedException epnde)
{
String now = TimeService.newTime().toString();
propertyEdit.addProperty(ResourceProperties.PROP_CREATION_DATE, now);
}
catch(EntityPropertyTypeException epte)
{
M_log.error(this + " mergeAssignment error when trying to get creation time property " + epte);
}
return assignment;
}
/**
* Creates and adds a new Assignment to the service which is a copy of an existing Assignment.
*
* @param assignmentId -
* The Assignment to be duplicated.
* @return The new Assignment object, or null if the original Assignment does not exist.
* @throws PermissionException
* if current User does not have permission to do this.
*/
public AssignmentEdit addDuplicateAssignment(String context, String assignmentReference) throws PermissionException,
IdInvalidException, IdUsedException, IdUnusedException
{
M_log.debug(this + " ENTERING ADD DUPLICATE ASSIGNMENT WITH ID : " + assignmentReference);
AssignmentEdit retVal = null;
AssignmentContentEdit newContent = null;
if (assignmentReference != null)
{
String assignmentId = assignmentId(assignmentReference);
if (!m_assignmentStorage.check(assignmentId))
throw new IdUnusedException(assignmentId);
else
{
M_log.debug(this + " addDuplicateAssignment : assignment exists - will copy");
Assignment existingAssignment = getAssignment(assignmentReference);
newContent = addDuplicateAssignmentContent(context, existingAssignment.getContentReference());
commitEdit(newContent);
retVal = addAssignment(context);
retVal.setContentReference(newContent.getReference());
retVal.setTitle(existingAssignment.getTitle() + " - " + rb.getString("assignment.copy"));
retVal.setSection(existingAssignment.getSection());
retVal.setOpenTime(existingAssignment.getOpenTime());
retVal.setDueTime(existingAssignment.getDueTime());
retVal.setDropDeadTime(existingAssignment.getDropDeadTime());
retVal.setCloseTime(existingAssignment.getCloseTime());
retVal.setDraft(true);
retVal.setGroup(existingAssignment.isGroup());
ResourcePropertiesEdit pEdit = (BaseResourcePropertiesEdit) retVal.getProperties();
pEdit.addAll(existingAssignment.getProperties());
addLiveProperties(pEdit);
}
}
M_log.debug(this + " ADD DUPLICATE ASSIGNMENT : LEAVING ADD DUPLICATE ASSIGNMENT WITH ID : "
+ retVal != null ? retVal.getId() : "");
return retVal;
}
/**
* Access the Assignment with the specified reference.
*
* @param assignmentReference -
* The reference of the Assignment.
* @return The Assignment corresponding to the reference, or null if it does not exist.
* @throws IdUnusedException
* if there is no object with this reference.
* @throws PermissionException
* if the current user is not allowed to access this.
*/
public Assignment getAssignment(String assignmentReference) throws IdUnusedException, PermissionException
{
M_log.debug(this + " GET ASSIGNMENT : REF : " + assignmentReference);
// check security on the assignment
unlockCheck(SECURE_ACCESS_ASSIGNMENT, assignmentReference);
Assignment assignment = findAssignment(assignmentReference);
String currentUserId = SessionManager.getCurrentSessionUserId();
if (assignment == null) throw new IdUnusedException(assignmentReference);
return checkAssignmentAccessibleForUser(assignment, currentUserId);
}// getAssignment
/**
* Retrieves the current status of an assignment.
* @param assignmentReference
* @return
* @throws IdUnusedException
* @throws PermissionException
*/
public String getAssignmentStatus(String assignmentReference) throws IdUnusedException, PermissionException
{
M_log.debug(this + " GET ASSIGNMENT : REF : " + assignmentReference);
// check security on the assignment
unlockCheck(SECURE_ACCESS_ASSIGNMENT, assignmentReference);
Assignment assignment = findAssignment(assignmentReference);
if (assignment == null) throw new IdUnusedException(assignmentReference);
return assignment.getStatus();
} // getAssignmentStatus
/**
* Check visibility of an assignment for a given user. We consider an
* an assignment to be visible to the user if it has been opened and is
* not deleted. However, we allow access to deleted assignments if the
* user has already made a submission for the assignment.
*
* Note that this method does not check permissions at all. It should
* already be established that the user is permitted to access this
* assignment.
*
* @param assignment the assignment to check
* @param userId the user for whom to check
* @return true if the assignment is available (open, not deleted) or
* submitted by the specified user; false otherwise
*/
private boolean isAvailableOrSubmitted(Assignment assignment, String userId)
{
boolean accessible = false;
String deleted = assignment.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED);
if (deleted == null || "".equals(deleted))
{
// show not deleted, not draft, opened assignments
Time openTime = assignment.getOpenTime();
if (openTime != null && TimeService.newTime().after(openTime) && !assignment.getDraft())
{
accessible = true;
}
}
else if (deleted.equalsIgnoreCase(Boolean.TRUE.toString()) && (assignment.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
&& getSubmission(assignment.getReference(), userId) != null)
{
// and those deleted but not non-electronic assignments but the user has made submissions to them
accessible = true;
}
return accessible;
}
private Assignment checkAssignmentAccessibleForUser(Assignment assignment, String currentUserId) throws PermissionException {
if (assignment.getAccess() == Assignment.AssignmentAccess.GROUPED)
{
String context = assignment.getContext();
Collection<Group> asgGroups = assignment.getGroups();
Collection<Group> allowedGroups = getGroupsAllowGetAssignment(context, currentUserId);
// reject and throw PermissionException if there is no intersection
if (!allowAllGroups(context) && !isIntersectionGroupRefsToGroups(asgGroups, allowedGroups)) {
throw new PermissionException(currentUserId, SECURE_ACCESS_ASSIGNMENT, assignment.getReference());
}
}
if (assignment.getAccess() == Assignment.AssignmentAccess.GROUPED)
{
Collection<Group> asgGroups = assignment.getGroups();
Collection<Group> allowedGroups = getGroupsAllowGetAssignment(assignment.getContext(), currentUserId);
// reject and throw PermissionException if there is no intersection
if (!isIntersectionGroupRefsToGroups(asgGroups, allowedGroups)) {
throw new PermissionException(currentUserId, SECURE_ACCESS_ASSIGNMENT, assignment.getReference());
}
}
if (allowAddAssignment(assignment.getContext()))
{
// always return for users can add assignent in the context
return assignment;
}
else if (isAvailableOrSubmitted(assignment, currentUserId))
{
return assignment;
}
throw new PermissionException(currentUserId, SECURE_ACCESS_ASSIGNMENT, assignment.getReference());
}
protected Assignment findAssignment(String assignmentReference)
{
Assignment assignment = null;
String assignmentId = assignmentId(assignmentReference);
assignment = m_assignmentStorage.get(assignmentId);
return assignment;
}
/**
* Access all assignment objects - known to us (not from external providers).
*
* @return A list of assignment objects.
*/
protected List getAssignments(String context)
{
return assignments(context, null);
} // getAssignments
/**
* Access all assignment objects - known to us (not from external providers) and accessible by the user
*
* @return A list of assignment objects.
*/
protected List getAssignments(String context, String userId)
{
return assignments(context, userId);
} // getAssignments
//
private List assignments(String context, String userId)
{
List rv = new ArrayList();
if (!allowGetAssignment(context))
{
// no permission to read assignment in context
return rv;
}
else
{
List assignments = getUnfilteredAssignments(context);
if (userId == null)
{
userId = SessionManager.getCurrentSessionUserId();
}
// check for the site and group permissions of these assignments as well as visibility (release time, etc.)
rv = getAccessibleAssignments(assignments, context, userId);
}
return rv;
}
/**
* Access all assignment objects for a site without considering user permissions.
* This should be used with care; almost all scenarios should use {@link getAssignments(String)}
* or {@link getAssignments(String, String)}, which do enforce permissions and visibility.
*
* @return A list of Assignment objects.
*/
protected List getUnfilteredAssignments(String context)
{
List assignments = m_assignmentStorage.getAll(context);
return assignments;
}
/**
* Filter a list of assignments to those that the supplied user can access.
*
* This method is primarily provided to be called from assignments() for
* set-based efficiency over iteration in building a list of assignments
* for a given user.
*
* There are a few ways that we consider an assignment to be accessible:
* 1. The user can add assignments to the site, or
* 2. The assignment is grouped and the user can view assignments in at
* least one of those groups, or
* 3. The assignment is ungrouped and the user can view assignments in
* the site
* An additional state check applies, which is that the assignment is
* not visible if it is deleted, except when the user has made a
* submission for it already or can add (manage) assignments.
*
* These rules were extracted from assignments() and we are enforcing
* them here for a set, rather than a single assignment.
*
* This is a somewhat awkward signature; it should really either have just the
* assignments list or just the siteId, but the other methods are not refactored
* now. Namely, getAssignments calls assignments, which has some cache specifics
* and other items that would need to be refactored very carefully. Rather than
* potentially changing the behavior subtly, this only replaces the iterative
* permissions checks with set-based ones.
*
* @param assignments a list of assignments to filter; must all be from the same site
* @param siteId the Site ID for all assignments
* @param userId the user whose access should be checked for the assignments
* @return a list of the assignments that are accessible; will never be null but may be empty
*/
protected List<Assignment> getAccessibleAssignments(List<Assignment> assignments, String siteId, String userId)
{
// Make sure that everything is from the specified site
List<Assignment> siteAssignments = filterAssignmentsBySite(assignments, siteId);
// Check whether the user can add assignments for the site.
// If so, return the full list.
String siteRef = SiteService.siteReference(siteId);
boolean allowAdd = securityService.unlock(userId, SECURE_ALL_GROUPS, siteRef);
if (allowAdd)
{
return siteAssignments;
}
// Partition the assignments into grouped and ungrouped for access checks
List<List<Assignment>> partitioned = partitionAssignments(siteAssignments);
List<Assignment> grouped = partitioned.get(0);
List<Assignment> ungrouped = partitioned.get(1);
List<Assignment> permitted = new ArrayList<Assignment>();
// Check the user's site permissions and collect all of the ungrouped
// assignments if the user has permission
boolean allowSiteGet = securityService.unlock(userId, SECURE_ACCESS_ASSIGNMENT, siteRef);
if (allowSiteGet)
{
permitted.addAll(ungrouped);
}
// Collect grouped assignments that the user can access
permitted.addAll(filterGroupedAssignmentsForAccess(grouped, siteId, userId));
// Filter for visibility/submission state
List<Assignment> visible = (securityService.unlock(userId, SECURE_ADD_ASSIGNMENT, siteRef))? permitted : filterAssignmentsByVisibility(permitted, userId);
// We are left with the original list filtered by site/group permissions and visibility/submission state
return visible;
}
/**
* Filter a list of assignments to those in a given site.
*
* @param assignments the list of assignments to filter; none may be null
* @param siteId the site ID to use to filter
* @return a new list with only the assignments that belong to the site;
* never null, but empty if the site doesn't exist, the assignments
* list is empty, or none of the assignments belong to the site
*/
protected List<Assignment> filterAssignmentsBySite(List<Assignment> assignments, String siteId)
{
List<Assignment> filtered = new ArrayList<Assignment>();
if (siteId == null)
{
return filtered;
}
try
{
SiteService.getSite(siteId);
}
catch (IdUnusedException e)
{
return filtered;
}
for (Assignment assignment : assignments)
{
if (assignment != null && siteId.equals(assignment.getContext()))
{
filtered.add(assignment);
}
}
return filtered;
}
/**
* Partition a list of assignments into those that are grouped and ungrouped.
*
* @param assignments the list of assignments to inspect and partition
* @return a two-element list containing List<Assignment> in both indexes;
* the first is the grouped assignments, the second is ungrouped;
* never null, always two elements, neither list is null;
* any null assignments will be omitted in the final lists
*/
protected List<List<Assignment>> partitionAssignments(List<Assignment> assignments)
{
List<Assignment> grouped = new ArrayList<Assignment>();
List<Assignment> ungrouped = new ArrayList<Assignment>();
for (Assignment assignment : assignments)
{
if (assignment != null && assignment.getAccess() == Assignment.AssignmentAccess.GROUPED)
{
grouped.add(assignment);
}
else
{
ungrouped.add(assignment);
}
}
List<List<Assignment>> partitioned = new ArrayList<List<Assignment>>();
partitioned.add(grouped);
partitioned.add(ungrouped);
return partitioned;
}
/**
* Filter a list of grouped assignments by permissions based on a given site. Note that
* this does not consider the assignment or submission state, only permissions.
*
* @param assignments the list of assignments to filter; should all be grouped and from the same site
* @param siteId the site to which all of the assignments belong
* @param userId the user for which group permissions should be checked
* @return a new list of assignments, containing those supplied that the user
* can access, based on permission to view the assignment in one or more of its
* groups, permission to add assignments in the site, or permission to
* view assignments in all of the site's groups; never null but may be empty
*
*/
protected List<Assignment> filterGroupedAssignmentsForAccess(List<Assignment> assignments, String siteId, String userId)
{
List<Assignment> filtered = new ArrayList<Assignment>();
// Short-circuit to save the group query if we can't make a reasonable check
if (assignments == null || assignments.isEmpty() || siteId == null || userId == null)
{
return filtered;
}
// Collect the groups where the user is permitted to view assignments
// and the groups covered by the assignments, then check the
// intersection to keep only visible assignments.
Collection<Group> allowedGroups = (Collection<Group>) getGroupsAllowGetAssignment(siteId, userId);
Set<String> allowedGroupRefs = new HashSet<String>();
for (Group group : allowedGroups)
{
allowedGroupRefs.add(group.getReference());
}
for (Assignment assignment : assignments)
{
for (String groupRef : (Collection<String>) assignment.getGroups())
{
if (allowedGroupRefs.contains(groupRef))
{
filtered.add(assignment);
break;
}
}
}
return filtered;
}
/**
* Filter a list of assignments based on visibility (open time, deletion, submission, etc.)
* for a specified user. Note that this only considers assignment and submission state and
* does not consider permissions so the assignments should have already been checked for
* permissions for the given user.
*
* @param assignments the list of assignments to filter
* @param userId the user for whom to check visibility; should be permitted to
* access all of the assignments
* @return a new list containing those supplied that the user may access, based
* on visibility; never null but may be empty
*/
protected List<Assignment> filterAssignmentsByVisibility(List<Assignment> assignments, String userId)
{
List<Assignment> visible = new ArrayList<Assignment>();
for (Assignment assignment : assignments)
{
if (assignment != null && isAvailableOrSubmitted(assignment, userId))
{
visible.add(assignment);
}
}
return visible;
}
/**
* See if the collection of group reference strings has at least one group that is in the collection of Group objects.
*
* @param groupRefs
* The collection (String) of group references.
* @param groups
* The collection (Group) of group objects.
* @return true if there is interesection, false if not.
*/
protected boolean isIntersectionGroupRefsToGroups(Collection groupRefs, Collection groups)
{
for (Iterator iRefs = groupRefs.iterator(); iRefs.hasNext();)
{
String findThisGroupRef = (String) iRefs.next();
for (Iterator iGroups = groups.iterator(); iGroups.hasNext();)
{
String thisGroupRef = ((Group) iGroups.next()).getReference();
if (thisGroupRef.equals(findThisGroupRef))
{
return true;
}
}
}
return false;
}
/**
* Get a locked assignment object for editing. Must commitEdit() to make official, or cancelEdit() when done!
*
* @param id
* The assignment id string.
* @return An AssignmentEdit object for editing.
* @exception IdUnusedException
* if not found, or if not an AssignmentEdit object
* @exception PermissionException
* if the current user does not have permission to edit this assignment.
* @exception InUseException
* if the assignment is being edited by another user.
*/
public AssignmentEdit editAssignment(String assignmentReference) throws IdUnusedException, PermissionException, InUseException
{
// check security (throws if not permitted)
unlock(SECURE_UPDATE_ASSIGNMENT, assignmentReference);
String assignmentId = assignmentId(assignmentReference);
// check for existance
if (!m_assignmentStorage.check(assignmentId))
{
throw new IdUnusedException(assignmentId);
}
// ignore the cache - get the assignment with a lock from the info store
AssignmentEdit assignmentEdit = m_assignmentStorage.edit(assignmentId);
if (assignmentEdit == null) throw new InUseException(assignmentId);
((BaseAssignmentEdit) assignmentEdit).setEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT);
return assignmentEdit;
} // editAssignment
/**
* Commit the changes made to an AssignmentEdit object, and release the lock.
*
* @param assignment
* The AssignmentEdit object to commit.
*/
public void commitEdit(AssignmentEdit assignment)
{
// check for closed edit
if (!assignment.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" commitEdit(): closed AssignmentEdit " + e.getMessage() + " assignment id=" + assignment.getId());
}
return;
}
// update the properties
addLiveUpdateProperties(assignment.getPropertiesEdit());
// complete the edit
m_assignmentStorage.commit(assignment);
//update peer assessment information:
if(!assignment.getDraft() && assignment.getAllowPeerAssessment()){
assignmentPeerAssessmentService.schedulePeerReview(assignment.getId());
}else{
assignmentPeerAssessmentService.removeScheduledPeerReview(assignment.getId());
}
// track it
EventTrackingService.post(EventTrackingService.newEvent(((BaseAssignmentEdit) assignment).getEvent(), assignment
.getReference(), true));
// close the edit object
((BaseAssignmentEdit) assignment).closeEdit();
} // commitEdit
/**
* Cancel the changes made to a AssignmentEdit object, and release the lock.
*
* @param assignment
* The AssignmentEdit object to commit.
*/
public void cancelEdit(AssignmentEdit assignment)
{
// check for closed edit
if (!assignment.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" cancelEdit(): closed AssignmentEdit " + e.getMessage() + " assignment id=" + assignment.getId());
}
return;
}
// release the edit lock
m_assignmentStorage.cancel(assignment);
// close the edit object
((BaseAssignmentEdit) assignment).closeEdit();
} // cancelEdit(Assignment)
/**
* {@inheritDoc}
*/
public void removeAssignment(AssignmentEdit assignment) throws PermissionException
{
if (assignment != null)
{
M_log.debug(this + " removeAssignment with id : " + assignment.getId());
if (!assignment.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" removeAssignment(): closed AssignmentEdit" + e.getMessage() + " assignment id=" + assignment.getId());
}
return;
}
// CHECK PERMISSION
unlock(SECURE_REMOVE_ASSIGNMENT, assignment.getReference());
// complete the edit
m_assignmentStorage.remove(assignment);
// track event
EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_REMOVE_ASSIGNMENT, assignment.getReference(), true));
// close the edit object
((BaseAssignmentEdit) assignment).closeEdit();
// remove any realm defined for this resource
try
{
AuthzGroupService.removeAuthzGroup(assignment.getReference());
}
catch (AuthzPermissionException e)
{
M_log.warn(" removeAssignment: removing realm for assignment reference=" + assignment.getReference() + " : " + e.getMessage());
}
}
}// removeAssignment
/**
* {@inheritDoc}
*/
public void removeAssignmentAndAllReferences(AssignmentEdit assignment) throws PermissionException
{
if (assignment != null)
{
M_log.debug(this + " removeAssignmentAndAllReferences with id : " + assignment.getId());
if (!assignment.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" removeAssignmentAndAllReferences(): closed AssignmentEdit" + e.getMessage() + " assignment id=" + assignment.getId());
}
return;
}
// CHECK PERMISSION
unlock(SECURE_REMOVE_ASSIGNMENT, assignment.getReference());
// we may need to remove associated calendar events and annc, so get the basic info here
ResourcePropertiesEdit pEdit = assignment.getPropertiesEdit();
String context = assignment.getContext();
// 1. remove associated calendar events, if exists
removeAssociatedCalendarItem(getCalendar(context), assignment, pEdit);
// 2. remove associated announcement, if exists
removeAssociatedAnnouncementItem(getAnnouncementChannel(context), assignment, pEdit);
// 3. remove Gradebook items, if linked
removeAssociatedGradebookItem(pEdit, context);
// 4. remove tags as necessary
removeAssociatedTaggingItem(assignment);
// 5. remove assignment submissions
List submissions = getSubmissions(assignment);
if (submissions != null)
{
for (Iterator sIterator=submissions.iterator(); sIterator.hasNext();)
{
AssignmentSubmission s = (AssignmentSubmission)sIterator.next();
String sReference = s.getReference();
try
{
removeSubmission(editSubmission(sReference));
}
catch (PermissionException e)
{
M_log.warn("removeAssignmentAndAllReference: User does not have permission to remove submission " + sReference + " for assignment: " + assignment.getId() + e.getMessage());
}
catch (InUseException e)
{
M_log.warn("removeAssignmentAndAllReference: submission " + sReference + " for assignment: " + assignment.getId() + " is in use. " + e.getMessage());
}catch (IdUnusedException e)
{
M_log.warn("removeAssignmentAndAllReference: submission " + sReference + " for assignment: " + assignment.getId() + " does not exist. " + e.getMessage());
}
}
}
// 6. remove associated content object
try
{
removeAssignmentContent(editAssignmentContent(assignment.getContent().getReference()));
}
catch (AssignmentContentNotEmptyException e)
{
M_log.warn(" removeAssignmentAndAllReferences(): cannot remove non-empty AssignmentContent object for assignment = " + assignment.getId() + ". " + e.getMessage());
}
catch (PermissionException e)
{
M_log.warn(" removeAssignmentAndAllReferences(): not allowed to remove AssignmentContent object for assignment = " + assignment.getId() + ". " + e.getMessage());
}
catch (InUseException e)
{
M_log.warn(" removeAssignmentAndAllReferences(): AssignmentContent object for assignment = " + assignment.getId() + " is in used. " + e.getMessage());
}
catch (IdUnusedException e)
{
M_log.warn(" removeAssignmentAndAllReferences(): cannot find AssignmentContent object for assignment = " + assignment.getId() + ". " + e.getMessage());
}
// 7. remove assignment
m_assignmentStorage.remove(assignment);
// close the edit object
((BaseAssignmentEdit) assignment).closeEdit();
// 8. remove any realm defined for this resource
try
{
AuthzGroupService.removeAuthzGroup(assignment.getReference());
}
catch (AuthzPermissionException e)
{
M_log.warn(" removeAssignment: removing realm for assignment reference=" + assignment.getReference() + " : " + e.getMessage());
}
// track event
EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_REMOVE_ASSIGNMENT, assignment.getReference(), true));
}
}// removeAssignment
/**
* remove the associated tagging items
* @param assignment
*/
private void removeAssociatedTaggingItem(AssignmentEdit assignment) {
try
{
if (m_taggingManager.isTaggable()) {
for (TaggingProvider provider : m_taggingManager.getProviders()) {
provider.removeTags(m_assignmentActivityProducer.getActivity(assignment));
}
}
}
catch (PermissionException pe)
{
M_log.warn("removeAssociatedTaggingItem: User does not have permission to remove tags for assignment: " + assignment.getId() + " via transferCopyEntities");
}
}
/**
* remove the linked Gradebook item related with the assignment
* @param pEdit
* @param context
*/
private void removeAssociatedGradebookItem(ResourcePropertiesEdit pEdit, String context) {
String associatedGradebookAssignment = pEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
if (associatedGradebookAssignment != null) {
boolean isExternalAssignmentDefined = m_gradebookExternalAssessmentService.isExternalAssignmentDefined(context, associatedGradebookAssignment);
if (isExternalAssignmentDefined)
{
m_gradebookExternalAssessmentService.removeExternalAssessment(context, associatedGradebookAssignment);
}
}
}
private Calendar getCalendar(String contextId)
{
Calendar calendar = null;
String calendarId = m_serverConfigurationService.getString("calendar", null);
if (calendarId == null)
{
calendarId = m_calendarService.calendarReference(contextId, SiteService.MAIN_CONTAINER);
try
{
calendar = m_calendarService.getCalendar(calendarId);
}
catch (IdUnusedException e)
{
M_log.warn("getCalendar: No calendar found for site: " + contextId);
calendar = null;
}
catch (PermissionException e)
{
M_log.warn("getCalendar: The current user does not have permission to access " +
"the calendar for context: " + contextId, e);
}
catch (Exception ex)
{
M_log.warn("getCalendar: Unknown exception occurred retrieving calendar for site: " + contextId, ex);
calendar = null;
}
}
return calendar;
}
/**
* Will determine if there is a calendar event associated with this assignment and
* remove it, if found.
* @param calendar Calendar
* @param aEdit AssignmentEdit
* @param pEdit ResourcePropertiesEdit
*/
private void removeAssociatedCalendarItem(Calendar calendar, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit)
{
String isThereEvent = pEdit.getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
if (isThereEvent != null && isThereEvent.equals(Boolean.TRUE.toString()))
{
// remove the associated calendar event
if (calendar != null)
{
// already has calendar object
// get the old event
CalendarEvent event = null;
String oldEventId = pEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
if (oldEventId != null)
{
try
{
event = calendar.getEvent(oldEventId);
}
catch (IdUnusedException ee)
{
// no action needed for this condition
M_log.warn(":removeCalendarEvent " + ee.getMessage());
}
catch (PermissionException ee)
{
M_log.warn(":removeCalendarEvent " + ee.getMessage());
}
}
// remove the event if it exists
if (event != null)
{
try
{
calendar.removeEvent(calendar.getEditEvent(event.getId(), CalendarService.EVENT_REMOVE_CALENDAR));
pEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
pEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
}
catch (PermissionException ee)
{
M_log.warn(":removeCalendarEvent not allowed to remove calendar event for assignment = " + aEdit.getTitle() + ". ");
}
catch (InUseException ee)
{
M_log.warn(":removeCalendarEvent someone else is editing calendar event for assignment = " + aEdit.getTitle() + ". ");
}
catch (IdUnusedException ee)
{
M_log.warn(":removeCalendarEvent calendar event are in use for assignment = " + aEdit.getTitle() + " and event =" + event.getId());
}
}
}
}
}
private AnnouncementChannel getAnnouncementChannel(String contextId)
{
AnnouncementService aService = org.sakaiproject.announcement.cover.AnnouncementService.getInstance();
AnnouncementChannel channel = null;
String channelId = m_serverConfigurationService.getString(m_announcementService.ANNOUNCEMENT_CHANNEL_PROPERTY, null);
if (channelId == null)
{
channelId = m_announcementService.channelReference(contextId, SiteService.MAIN_CONTAINER);
try
{
channel = aService.getAnnouncementChannel(channelId);
}
catch (IdUnusedException e)
{
M_log.warn("getAnnouncement:No announcement channel found");
channel = null;
}
catch (PermissionException e)
{
M_log.warn("getAnnouncement:Current user not authorized to deleted annc associated " +
"with assignment. " + e.getMessage());
channel = null;
}
}
return channel;
}
/**
* Will determine if there is an announcement associated
* with this assignment and removes it, if found.
* @param channel AnnouncementChannel
* @param aEdit AssignmentEdit
* @param pEdit ResourcePropertiesEdit
*/
private void removeAssociatedAnnouncementItem(AnnouncementChannel channel, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit)
{
if (channel != null)
{
String openDateAnnounced = StringUtils.trimToNull(pEdit.getProperty("new_assignment_open_date_announced"));
String openDateAnnouncementId = StringUtils.trimToNull(pEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID));
if (openDateAnnounced != null && openDateAnnouncementId != null)
{
try
{
channel.removeMessage(openDateAnnouncementId);
}
catch (PermissionException e)
{
M_log.warn(":removeAnnouncement " + e.getMessage());
}
}
}
}
/**
* Creates and adds a new AssignmentContent to the service.
*
* @param context -
* Describes the portlet context - generated with DefaultId.getChannel().
* @return AssignmentContent The new AssignmentContent object.
* @throws PermissionException
* if current User does not have permission to do this.
*/
public AssignmentContentEdit addAssignmentContent(String context) throws PermissionException
{
M_log.debug(this + " ENTERING ADD ASSIGNMENT CONTENT");
String contentId = null;
boolean badId = false;
do
{
badId = !Validator.checkResourceId(contentId);
contentId = IdManager.createUuid();
if (m_contentStorage.check(contentId)) badId = true;
}
while (badId);
// security check
if (!allowAddAssignmentContent(context))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), SECURE_ADD_ASSIGNMENT_CONTENT, contentId);
}
AssignmentContentEdit content = m_contentStorage.put(contentId, context);
M_log.debug(this + " LEAVING ADD ASSIGNMENT CONTENT : ID : " + content.getId());
// event for tracking
((BaseAssignmentContentEdit) content).setEvent(AssignmentConstants.EVENT_ADD_ASSIGNMENT_CONTENT);
return content;
}// addAssignmentContent
/**
* Add a new AssignmentContent to the directory, from a definition in XML. Must commitEdit() to make official, or cancelEdit() when done!
*
* @param el
* The XML DOM Element defining the AssignmentContent.
* @return A locked AssignmentContentEdit object (reserving the id).
* @exception IdInvalidException
* if the AssignmentContent id is invalid.
* @exception IdUsedException
* if the AssignmentContent id is already used.
* @exception PermissionException
* if the current user does not have permission to add an AssignnmentContent.
*/
public AssignmentContentEdit mergeAssignmentContent(Element el) throws IdInvalidException, IdUsedException, PermissionException
{
// construct from the XML
AssignmentContent contentFromXml = new BaseAssignmentContent(el);
// check for a valid assignment name
if (!Validator.checkResourceId(contentFromXml.getId())) throw new IdInvalidException(contentFromXml.getId());
// check security (throws if not permitted)
unlock(SECURE_ADD_ASSIGNMENT_CONTENT, contentFromXml.getReference());
// reserve a content with this id from the info store - if it's in use, this will return null
AssignmentContentEdit content = m_contentStorage.put(contentFromXml.getId(), contentFromXml.getContext());
if (content == null)
{
throw new IdUsedException(contentFromXml.getId());
}
// transfer from the XML read content object to the AssignmentContentEdit
((BaseAssignmentContentEdit) content).set(contentFromXml);
((BaseAssignmentContentEdit) content).setEvent(AssignmentConstants.EVENT_ADD_ASSIGNMENT_CONTENT);
return content;
}
/**
* Creates and adds a new AssignmentContent to the service which is a copy of an existing AssignmentContent.
*
* @param context -
* From DefaultId.getChannel(RunData)
* @param contentReference -
* The id of the AssignmentContent to be duplicated.
* @return AssignmentContentEdit The new AssignmentContentEdit object, or null if the original does not exist.
* @throws PermissionException
* if current User does not have permission to do this.
*/
public AssignmentContentEdit addDuplicateAssignmentContent(String context, String contentReference) throws PermissionException,
IdInvalidException, IdUnusedException
{
M_log.debug(this + " ENTERING ADD DUPLICATE ASSIGNMENT CONTENT : " + contentReference);
AssignmentContentEdit retVal = null;
AssignmentContent existingContent = null;
List tempVector = null;
Reference tempRef = null;
Reference newRef = null;
if (contentReference != null)
{
String contentId = contentId(contentReference);
if (!m_contentStorage.check(contentId))
throw new IdUnusedException(contentId);
else
{
M_log.debug(this + " ADD DUPL. CONTENT : found match - will copy");
existingContent = getAssignmentContent(contentReference);
retVal = addAssignmentContent(context);
retVal.setTitle(existingContent.getTitle() + " - " + rb.getString("assignment.copy"));
retVal.setInstructions(existingContent.getInstructions());
retVal.setHonorPledge(existingContent.getHonorPledge());
retVal.setHideDueDate(existingContent.getHideDueDate());
retVal.setTypeOfSubmission(existingContent.getTypeOfSubmission());
retVal.setTypeOfGrade(existingContent.getTypeOfGrade());
retVal.setMaxGradePoint(existingContent.getMaxGradePoint());
retVal.setGroupProject(existingContent.getGroupProject());
retVal.setIndividuallyGraded(existingContent.individuallyGraded());
retVal.setReleaseGrades(existingContent.releaseGrades());
retVal.setAllowAttachments(existingContent.getAllowAttachments());
// for ContentReview service
retVal.setAllowReviewService(existingContent.getAllowReviewService());
tempVector = existingContent.getAttachments();
if (tempVector != null)
{
for (int z = 0; z < tempVector.size(); z++)
{
tempRef = (Reference) tempVector.get(z);
if (tempRef != null)
{
String tempRefId = tempRef.getId();
String tempRefCollectionId = m_contentHostingService.getContainingCollectionId(tempRefId);
try
{
// get the original attachment display name
ResourceProperties p = m_contentHostingService.getProperties(tempRefId);
String displayName = p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
// add another attachment instance
String newItemId = m_contentHostingService.copyIntoFolder(tempRefId, tempRefCollectionId);
ContentResourceEdit copy = m_contentHostingService.editResource(newItemId);
// with the same display name
ResourcePropertiesEdit pedit = copy.getPropertiesEdit();
pedit.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName);
m_contentHostingService.commitResource(copy, NotificationService.NOTI_NONE);
newRef = m_entityManager.newReference(copy.getReference());
retVal.addAttachment(newRef);
}
catch (Exception e)
{
M_log.warn(" LEAVING ADD DUPLICATE CONTENT : " + e.toString());
}
}
}
}
ResourcePropertiesEdit pEdit = (BaseResourcePropertiesEdit) retVal.getPropertiesEdit();
pEdit.addAll(existingContent.getProperties());
addLiveProperties(pEdit);
}
}
M_log.debug(this + " LEAVING ADD DUPLICATE CONTENT WITH ID : " + retVal != null ? retVal.getId() : "");
return retVal;
}
/**
* Access the AssignmentContent with the specified reference.
*
* @param contentReference -
* The reference of the AssignmentContent.
* @return The AssignmentContent corresponding to the reference, or null if it does not exist.
* @throws IdUnusedException
* if there is no object with this reference.
* @throws PermissionException
* if the current user is not allowed to access this.
*/
public AssignmentContent getAssignmentContent(String contentReference) throws IdUnusedException, PermissionException
{
M_log.debug(this + " GET CONTENT : ID : " + contentReference);
// check security on the assignment content
unlockCheck(SECURE_ACCESS_ASSIGNMENT_CONTENT, contentReference);
AssignmentContent content = null;
// if we have it in the cache, use it
String contentId = contentId(contentReference);
if (contentId != null) {
content = m_contentStorage.get(contentId);
}
if (content == null) throw new IdUnusedException(contentId);
M_log.debug(this + " GOT ASSIGNMENT CONTENT : ID : " + content.getId());
// track event
// EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT_CONTENT, content.getReference(), false));
return content;
}// getAssignmentContent
/**
* Access all AssignmentContent objects - known to us (not from external providers).
*
* @return A list of AssignmentContent objects.
*/
protected List getAssignmentContents(String context)
{
List contents = m_contentStorage.getAll(context);
return contents;
} // getAssignmentContents
/**
* Get a locked AssignmentContent object for editing. Must commitEdit() to make official, or cancelEdit() when done!
*
* @param id
* The content id string.
* @return An AssignmentContentEdit object for editing.
* @exception IdUnusedException
* if not found, or if not an AssignmentContentEdit object
* @exception PermissionException
* if the current user does not have permission to edit this content.
* @exception InUseException
* if the assignment is being edited by another user.
*/
public AssignmentContentEdit editAssignmentContent(String contentReference) throws IdUnusedException, PermissionException,
InUseException
{
// check security (throws if not permitted)
unlock(SECURE_UPDATE_ASSIGNMENT_CONTENT, contentReference);
String contentId = contentId(contentReference);
// check for existance
if (!m_contentStorage.check(contentId))
{
throw new IdUnusedException(contentId);
}
// ignore the cache - get the AssignmentContent with a lock from the info store
AssignmentContentEdit content = m_contentStorage.edit(contentId);
if (content == null) throw new InUseException(contentId);
((BaseAssignmentContentEdit) content).setEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_CONTENT);
return content;
} // editAssignmentContent
/**
* Commit the changes made to an AssignmentContentEdit object, and release the lock.
*
* @param content
* The AssignmentContentEdit object to commit.
*/
public void commitEdit(AssignmentContentEdit content)
{
// check for closed edit
if (!content.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" commitEdit(): closed AssignmentContentEdit " + e + " content id=" + content.getId());
}
return;
}
// update the properties
addLiveUpdateProperties(content.getPropertiesEdit());
// complete the edit
m_contentStorage.commit(content);
// track it
EventTrackingService.post(EventTrackingService.newEvent(((BaseAssignmentContentEdit) content).getEvent(), content
.getReference(), true));
// close the edit object
((BaseAssignmentContentEdit) content).closeEdit();
} // commitEdit(AssignmentContent)
/**
* Cancel the changes made to a AssignmentContentEdit object, and release the lock.
*
* @param content
* The AssignmentContentEdit object to commit.
*/
public void cancelEdit(AssignmentContentEdit content)
{
// check for closed edit
if (!content.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" cancelEdit(): closed AssignmentContentEdit " + e.getMessage() + " assignment content id=" + content.getId());
}
return;
}
// release the edit lock
m_contentStorage.cancel(content);
// close the edit object
((BaseAssignmentContentEdit) content).closeEdit();
} // cancelEdit(Content)
/**
* Removes an AssignmentContent
*
* @param content -
* the AssignmentContent to remove.
* @throws an
* AssignmentContentNotEmptyException if this content still has related Assignments.
* @throws PermissionException
* if current User does not have permission to do this.
*/
public void removeAssignmentContent(AssignmentContentEdit content) throws AssignmentContentNotEmptyException,
PermissionException
{
if (content != null)
{
if (!content.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" removeAssignmentContent(): closed AssignmentContentEdit " + e.getMessage() + " assignment content id=" + content.getId());
}
return;
}
// CHECK SECURITY
unlock(SECURE_REMOVE_ASSIGNMENT_CONTENT, content.getReference());
// complete the edit
m_contentStorage.remove(content);
// track event
EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_REMOVE_ASSIGNMENT_CONTENT, content.getReference(),
true));
// close the edit object
((BaseAssignmentContentEdit) content).closeEdit();
}
}
/**
* {@inheritDoc}
*/
public AssignmentSubmissionEdit addSubmission(String context, String assignmentId, String submitterId) throws PermissionException
{
M_log.debug(this + " ENTERING ADD SUBMISSION");
String submissionId = null;
boolean badId = false;
do
{
badId = !Validator.checkResourceId(submissionId);
submissionId = IdManager.createUuid();
if (m_submissionStorage.check(submissionId)) badId = true;
}
while (badId);
String key = submissionReference(context, submissionId, assignmentId);
M_log.debug(this + " ADD SUBMISSION : SUB REF : " + key);
Assignment assignment = null;
try
{
assignment = getAssignment(assignmentId);
}
catch(IdUnusedException iue)
{
// A bit terminal, this.
}
// SAK-21525
if(!unlockCheckWithGroups(SECURE_ADD_ASSIGNMENT_SUBMISSION, key,assignment))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), SECURE_ADD_ASSIGNMENT_SUBMISSION, key);
}
M_log.debug(this + " ADD SUBMISSION : UNLOCKED");
// storage
M_log.debug(this + " SUBMITTER ID " + submitterId);
AssignmentSubmissionEdit submission = m_submissionStorage.put(submissionId, assignmentId, submitterId, null, null, null);
if (submission != null)
{
submission.setContext(context);
// event for tracking
((BaseAssignmentSubmissionEdit) submission).setEvent(AssignmentConstants.EVENT_ADD_ASSIGNMENT_SUBMISSION);
M_log.debug(this + " LEAVING ADD SUBMISSION : REF : " + submission.getReference());
}
else
{
M_log.warn(this + " ADD SUBMISSION: cannot add submission object with submission id=" + submissionId + ", assignment id=" + assignmentId + ", and submitter id=" + submitterId);
}
return submission;
}
/**
* Add a new AssignmentSubmission to the directory, from a definition in XML. Must commitEdit() to make official, or cancelEdit() when done!
*
* @param el
* The XML DOM Element defining the submission.
* @return A locked AssignmentSubmissionEdit object (reserving the id).
* @exception IdInvalidException
* if the submission id is invalid.
* @exception IdUsedException
* if the submission id is already used.
* @exception PermissionException
* if the current user does not have permission to add a submission.
*/
public AssignmentSubmissionEdit mergeSubmission(Element el) throws IdInvalidException, IdUsedException, PermissionException
{
// construct from the XML
BaseAssignmentSubmission submissionFromXml = new BaseAssignmentSubmission(el);
// check for a valid submission name
if (!Validator.checkResourceId(submissionFromXml.getId())) throw new IdInvalidException(submissionFromXml.getId());
// check security (throws if not permitted)
unlock(SECURE_ADD_ASSIGNMENT_SUBMISSION, submissionFromXml.getReference());
// reserve a submission with this id from the info store - if it's in use, this will return null
AssignmentSubmissionEdit submission = m_submissionStorage.put( submissionFromXml.getId(),
submissionFromXml.getAssignmentId(),
submissionFromXml.getSubmitterIdString(),
(submissionFromXml.getTimeSubmitted() != null)?String.valueOf(submissionFromXml.getTimeSubmitted().getTime()):null,
Boolean.valueOf(submissionFromXml.getSubmitted()).toString(),
Boolean.valueOf(submissionFromXml.getGraded()).toString());
if (submission == null)
{
throw new IdUsedException(submissionFromXml.getId());
}
// transfer from the XML read submission object to the SubmissionEdit
((BaseAssignmentSubmissionEdit) submission).set(submissionFromXml);
((BaseAssignmentSubmissionEdit) submission).setEvent(AssignmentConstants.EVENT_ADD_ASSIGNMENT_SUBMISSION);
return submission;
}
/**
* Get a locked AssignmentSubmission object for editing. Must commitEdit() to make official, or cancelEdit() when done!
*
* @param submissionrReference -
* the reference for the submission.
* @return An AssignmentSubmissionEdit object for editing.
* @exception IdUnusedException
* if not found, or if not an AssignmentSubmissionEdit object
* @exception PermissionException
* if the current user does not have permission to edit this submission.
* @exception InUseException
* if the assignment is being edited by another user.
*/
public AssignmentSubmissionEdit editSubmission(String submissionReference) throws IdUnusedException, PermissionException,
InUseException
{
String submissionId = submissionId(submissionReference);
// ignore the cache - get the AssignmentSubmission with a lock from the info store
AssignmentSubmissionEdit submission = m_submissionStorage.edit(submissionId);
if (submission == null) throw new InUseException(submissionId);
// pass if with grade or update assignment right
if (!unlockCheck(SECURE_GRADE_ASSIGNMENT_SUBMISSION, submissionReference) && !unlockCheck(SECURE_UPDATE_ASSIGNMENT, submissionReference))
{
boolean notAllowed = true;
// normal user(not a grader) can only edit his/her own submission
User currentUser = UserDirectoryService.getCurrentUser();
if (unlockCheck(SECURE_UPDATE_ASSIGNMENT_SUBMISSION, submissionReference))
{
Assignment a = submission.getAssignment();
if (a.isGroup()) {
String context = a.getContext();
Site st = SiteService.getSite(context);
try {
notAllowed =
st.getGroup(submission.getSubmitterId()).getMember(currentUser.getId()) == null;
} catch (Throwable _sss) { }
} else {
if ( submission.getSubmitterId() != null && submission.getSubmitterId().equals(currentUser.getId()) ) {
// is editing one's own submission
// then test against extra criteria depend on the status of submission
try
{
if (canSubmit(a.getContext(), a))
{
notAllowed = false;
}
}
catch (Exception e)
{
M_log.warn(" editSubmission(): cannot get assignment for submission " + submissionReference + e.getMessage());
}
}
}
}
if (notAllowed)
{
// throw PermissionException
throw new PermissionException(currentUser.getId(), SECURE_UPDATE_ASSIGNMENT, submissionReference);
}
}
// check for existance
if (!m_submissionStorage.check(submissionId))
{
throw new IdUnusedException(submissionId);
}
((BaseAssignmentSubmissionEdit) submission).setEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_SUBMISSION);
return submission;
} // editSubmission
/**
* Commit the changes made to an AssignmentSubmissionEdit object, and release the lock.
*
* @param submission
* The AssignmentSubmissionEdit object to commit.
*/
public void commitEdit(AssignmentSubmissionEdit submission)
{
String submissionRef = submission.getReference();
// check for closed edit
if (!submission.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" commitEdit(): closed AssignmentSubmissionEdit assignment submission id=" + submission.getId() + e.getMessage());
}
return;
}
// update the properties
addLiveUpdateProperties(submission.getPropertiesEdit());
submission.setTimeLastModified(TimeService.newTime());
// complete the edit
m_submissionStorage.commit(submission);
// close the edit object
((BaseAssignmentSubmissionEdit) submission).closeEdit();
try
{
AssignmentSubmission s = getSubmission(submissionRef);
Assignment a = s.getAssignment();
Time returnedTime = s.getTimeReturned();
Time submittedTime = s.getTimeSubmitted();
String resubmitNumber = s.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
// track it
if (!s.getSubmitted())
{
// saving a submission
EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_SAVE_ASSIGNMENT_SUBMISSION, submissionRef, true));
}
else if (returnedTime == null && !s.getReturned() && (submittedTime == null /*grading non-submissions*/
|| (submittedTime != null && (s.getTimeLastModified().getTime() - submittedTime.getTime()) > 1000*60 /*make sure the last modified time is at least one minute after the submit time*/)))
{
if (StringUtils.trimToNull(s.getSubmittedText()) == null && s.getSubmittedAttachments().isEmpty()
&& StringUtils.trimToNull(s.getGrade()) == null && StringUtils.trimToNull(s.getFeedbackText()) == null && StringUtils.trimToNull(s.getFeedbackComment()) == null && s.getFeedbackAttachments().isEmpty() )
{
// auto add submission for those not submitted
//EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_ADD_ASSIGNMENT_SUBMISSION, submissionRef, true));
}
else
{
// graded and saved before releasing it
Event event = EventTrackingService.newEvent(AssignmentConstants.EVENT_GRADE_ASSIGNMENT_SUBMISSION, submissionRef, true);
EventTrackingService.post(event);
LearningResourceStoreService lrss = (LearningResourceStoreService) ComponentManager
.get("org.sakaiproject.event.api.LearningResourceStoreService");
if (null != lrss && StringUtils.isNotEmpty(s.getGrade())) {
for (User user : s.getSubmitters()) {
lrss.registerStatement(getStatementForAssignmentGraded(lrss.getEventActor(event), event, a, s, user), "assignment");
}
}
}
}
else if (returnedTime != null && s.getGraded() && (submittedTime == null/*returning non-submissions*/
|| (submittedTime != null && returnedTime.after(submittedTime))/*returning normal submissions*/
|| (submittedTime != null && submittedTime.after(returnedTime) && s.getTimeLastModified().after(submittedTime))/*grading the resubmitted assignment*/))
{
// releasing a submitted assignment or releasing grade to an unsubmitted assignment
Event event = EventTrackingService.newEvent(AssignmentConstants.EVENT_GRADE_ASSIGNMENT_SUBMISSION, submissionRef, true);
EventTrackingService.post(event);
LearningResourceStoreService lrss = (LearningResourceStoreService) ComponentManager
.get("org.sakaiproject.event.api.LearningResourceStoreService");
if (null != lrss && StringUtils.isNotEmpty(s.getGrade())) {
for (User user : s.getSubmitters()) {
lrss.registerStatement(getStatementForAssignmentGraded(lrss.getEventActor(event), event, a, s, user), "assignment");
}
}
// if this is releasing grade, depending on the release grade notification setting, send email notification to student
sendGradeReleaseNotification(s.getGradeReleased(), a.getProperties().getProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE), s.getSubmitters(), s);
if(resubmitNumber!=null)
sendGradeReleaseNotification(s.getGradeReleased(), a.getProperties().getProperty(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE), s.getSubmitters(), s);
}
else if (submittedTime == null) /*grading non-submission*/
{
// releasing a submitted assignment or releasing grade to an unsubmitted assignment
Event event = EventTrackingService.newEvent(AssignmentConstants.EVENT_GRADE_ASSIGNMENT_SUBMISSION, submissionRef, true);
EventTrackingService.post(event);
LearningResourceStoreService lrss = (LearningResourceStoreService) ComponentManager
.get("org.sakaiproject.event.api.LearningResourceStoreService");
if (null != lrss) {
for (User user : s.getSubmitters()) {
lrss.registerStatement(getStatementForUnsubmittedAssignmentGraded(lrss.getEventActor(event), event, a, s, user),
"sakai.assignment");
}
}
}
else
{
// submitting a submission
EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_SUBMIT_ASSIGNMENT_SUBMISSION, submissionRef, true));
// only doing the notification for real online submissions
if (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
// instructor notification
notificationToInstructors(s, a);
// student notification, whether the student gets email notification once he submits an assignment
notificationToStudent(s);
}
}
}
catch (IdUnusedException e)
{
M_log.warn(" commitEdit(), submissionId=" + submissionRef, e);
}
catch (PermissionException e)
{
M_log.warn(" commitEdit(), submissionId=" + submissionRef, e);
}
} // commitEdit(Submission)
protected void sendGradeReleaseNotification(boolean released, String notificationSetting, User[] allSubmitters, AssignmentSubmission s)
{
if (allSubmitters == null) return;
// SAK-19916 need to filter submitters against list of valid users still in site
Set<User> filteredSubmitters = new HashSet<User>();
try {
String siteId = s.getAssignment().getContext();
Set<String> siteUsers = SiteService.getSite(siteId).getUsers();
for (int x = 0; x < allSubmitters.length; x++)
{
User u = (User) allSubmitters[x];
String userId = u.getId();
if (siteUsers.contains(userId)) {
filteredSubmitters.add(u);
}
}
} catch (IdUnusedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
User[] submitters = new User[filteredSubmitters.size()];
filteredSubmitters.toArray(submitters);
if (released && notificationSetting != null && notificationSetting.equals(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_EACH))
{
// send email to every submitters
if (submitters != null)
{
// send the message immidiately
EmailService.sendToUsers(new ArrayList(Arrays.asList(submitters)), getHeaders(null, "releasegrade"), getNotificationMessage(s, "releasegrade"));
}
}
if (notificationSetting != null && notificationSetting.equals(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_EACH)){
// send email to every submitters
if (submitters != null){
// send the message immidiately
EmailService.sendToUsers(new ArrayList(Arrays.asList(submitters)), getHeaders(null, "releaseresumbission"), getNotificationMessage(s, "releaseresumbission"));
}
}
}
/**
* send notification to instructor type of users if necessary
* @param s
* @param a
*/
private void notificationToInstructors(AssignmentSubmission s, Assignment a)
{
String notiOption = a.getProperties().getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE);
if (notiOption != null && !notiOption.equals(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE))
{
// need to send notification email
String context = s.getContext();
// compare the list of users with the receive.notifications and list of users who can actually grade this assignment
List receivers = allowReceiveSubmissionNotificationUsers(context);
List allowGradeAssignmentUsers = allowGradeAssignmentUsers(a.getReference());
receivers.retainAll(allowGradeAssignmentUsers);
String messageBody = getNotificationMessage(s, "submission");
if (notiOption.equals(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_EACH))
{
// send the message immediately
EmailService.sendToUsers(receivers, getHeaders(null, "submission"), messageBody);
}
else if (notiOption.equals(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DIGEST))
{
// just send plain/text version for now
String digestMsgBody = getPlainTextNotificationMessage(s, "submission");
// digest the message to each user
for (Iterator iReceivers = receivers.iterator(); iReceivers.hasNext();)
{
User user = (User) iReceivers.next();
DigestService.digest(user.getId(), getSubject("submission"), digestMsgBody);
}
}
}
}
/**
* get only the plain text of notification message
* @param s
* @return
*/
protected String getPlainTextNotificationMessage(AssignmentSubmission s, String submissionOrReleaseGrade)
{
StringBuilder message = new StringBuilder();
message.append(plainTextContent(s, submissionOrReleaseGrade));
return message.toString();
}
/**
* send notification to student/students if necessary
* @param s
*/
private void notificationToStudent(AssignmentSubmission s)
{
if (m_serverConfigurationService.getBoolean("assignment.submission.confirmation.email", true))
{
//send notification
User[] users = s.getSubmitters();
List receivers = new ArrayList();
for (int i=0; users != null && i<users.length; i++){
if (StringUtils.trimToNull(users[i].getEmail()) != null){
receivers.add(users[i]);
}
}
EmailService.sendToUsers(receivers, getHeaders(null, "submission"), getNotificationMessage(s, "submission"));
}
}
protected List<String> getHeaders(String receiverEmail, String submissionOrReleaseGrade)
{
List<String> rv = new ArrayList<String>();
rv.add("MIME-Version: 1.0");
rv.add("Content-Type: multipart/alternative; boundary=\""+MULTIPART_BOUNDARY+"\"");
// set the subject
rv.add(getSubject(submissionOrReleaseGrade));
// from
rv.add(getFrom());
// to
if (StringUtils.trimToNull(receiverEmail) != null)
{
rv.add("To: " + receiverEmail);
}
return rv;
}
protected List<String> getReleaseGradeHeaders(String receiverEmail)
{
List<String> rv = new ArrayList<String>();
rv.add("MIME-Version: 1.0");
rv.add("Content-Type: multipart/alternative; boundary=\""+MULTIPART_BOUNDARY+"\"");
// set the subject
rv.add(getSubject("releasegrade"));
// from
rv.add(getFrom());
// to
if (StringUtils.trimToNull(receiverEmail) != null)
{
rv.add("To: " + receiverEmail);
}
return rv;
}
protected String getSubject(String submissionOrReleaseGrade)
{
String subject = "";
if("submission".equals(submissionOrReleaseGrade))
subject = rb.getString("noti.subject.content");
else if ("releasegrade".equals(submissionOrReleaseGrade))
subject = rb.getString("noti.releasegrade.subject.content");
else
subject = rb.getString("noti.releaseresubmission.subject.content");
return "Subject: " + subject ;
}
protected String getFrom()
{
return "From: " + "\"" + m_serverConfigurationService.getString("ui.service", "Sakai") + "\"<no-reply@"+ m_serverConfigurationService.getServerName() + ">";
}
private final String MULTIPART_BOUNDARY = "======sakai-multi-part-boundary======";
private final String BOUNDARY_LINE = "\n\n--"+MULTIPART_BOUNDARY+"\n";
private final String TERMINATION_LINE = "\n\n--"+MULTIPART_BOUNDARY+"--\n\n";
private final String MIME_ADVISORY = "This message is for MIME-compliant mail readers.";
/**
* Get the message for the email.
*
* @param event
* The event that matched criteria to cause the notification.
* @return the message for the email.
*/
protected String getNotificationMessage(AssignmentSubmission s, String submissionOrReleaseGrade)
{
StringBuilder message = new StringBuilder();
message.append(MIME_ADVISORY);
message.append(BOUNDARY_LINE);
message.append(plainTextHeaders());
message.append(plainTextContent(s, submissionOrReleaseGrade));
message.append(BOUNDARY_LINE);
message.append(htmlHeaders());
message.append(htmlPreamble(submissionOrReleaseGrade));
if("submission".equals(submissionOrReleaseGrade))
message.append(htmlContent(s));
else if ("releasegrade".equals(submissionOrReleaseGrade))
message.append(htmlContentReleaseGrade(s));
else
message.append(htmlContentReleaseResubmission(s));
message.append(htmlEnd());
message.append(TERMINATION_LINE);
return message.toString();
}
protected String plainTextHeaders() {
return "Content-Type: text/plain\n\n";
}
protected String plainTextContent(AssignmentSubmission s, String submissionOrReleaseGrade) {
if("submission".equals(submissionOrReleaseGrade))
return FormattedText.convertFormattedTextToPlaintext(htmlContent(s));
else if ("releasegrade".equals(submissionOrReleaseGrade))
return FormattedText.convertFormattedTextToPlaintext(htmlContentReleaseGrade(s));
else
return FormattedText.convertFormattedTextToPlaintext(htmlContentReleaseResubmission(s));
}
protected String htmlHeaders() {
return "Content-Type: text/html\n\n";
}
protected String htmlPreamble(String submissionOrReleaseGrade) {
StringBuilder buf = new StringBuilder();
buf.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n");
buf.append(" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
buf.append("<html>\n");
buf.append(" <head><title>");
buf.append(getSubject(submissionOrReleaseGrade));
buf.append("</title></head>\n");
buf.append(" <body>\n");
return buf.toString();
}
protected String htmlEnd() {
return "\n </body>\n</html>\n";
}
private String htmlContent(AssignmentSubmission s)
{
Assignment a = s.getAssignment();
String context = s.getContext();
String siteTitle = "";
String siteId = "";
try
{
Site site = SiteService.getSite(context);
siteTitle = site.getTitle();
siteId = site.getId();
}
catch (Exception ee)
{
M_log.warn(" htmlContent(), site id =" + context + " " + ee.getMessage());
}
StringBuilder buffer = new StringBuilder();
// site title and id
buffer.append(rb.getString("noti.site.title") + " " + siteTitle + newline);
buffer.append(rb.getString("noti.site.id") + " " + siteId +newline + newline);
// assignment title and due date
buffer.append(rb.getString("assignment.title") + " " + a.getTitle()+newline);
buffer.append(rb.getString("noti.assignment.duedate") + " " + a.getDueTime().toStringLocalFull()+newline + newline);
// submitter name and id
User[] submitters = s.getSubmitters();
String submitterNames = "";
String submitterIds = "";
for (int i = 0; i<submitters.length; i++)
{
User u = (User) submitters[i];
if (i>0)
{
submitterNames = submitterNames.concat("; ");
submitterIds = submitterIds.concat("; ");
}
submitterNames = submitterNames.concat(u.getDisplayName());
submitterIds = submitterIds.concat(u.getDisplayId());
}
buffer.append(rb.getString("noti.student") + " " + submitterNames);
if (submitterIds.length() != 0)
{
buffer.append("( " + submitterIds + " )");
}
buffer.append(newline + newline);
// submit time
buffer.append(rb.getString("submission.id") + " " + s.getId() + newline);
// submit time
buffer.append(rb.getString("noti.submit.time") + " " + s.getTimeSubmitted().toStringLocalFull() + newline + newline);
// submit text
String text = StringUtils.trimToNull(s.getSubmittedText());
if ( text != null)
{
buffer.append(rb.getString("gen.submittedtext") + newline + newline + Validator.escapeHtmlFormattedText(text) + newline + newline);
}
// attachment if any
List attachments = s.getSubmittedAttachments();
if (attachments != null && attachments.size() >0)
{
if (a.getContent().getTypeOfSubmission() == Assignment.SINGLE_ATTACHMENT_SUBMISSION)
{
buffer.append(rb.getString("gen.att.single"));
}
else
{
buffer.append(rb.getString("gen.att"));
}
buffer.append(newline).append(newline);
for (int j = 0; j<attachments.size(); j++)
{
Reference r = (Reference) attachments.get(j);
buffer.append(r.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME) + " (" + r.getProperties().getPropertyFormatted(ResourceProperties.PROP_CONTENT_LENGTH)+ ")\n");
//if this is a archive (zip etc) append the list of files in it
if (isArchiveFile(r)) {
buffer.append(getArchiveManifest(r));
}
}
}
return buffer.toString();
}
/**
* get a list of the files in the archive
* @param r
* @return
*/
private Object getArchiveManifest(Reference r) {
String extension = getFileExtension(r);
StringBuilder builder = new StringBuilder();
if (".zip".equals(extension)) {
ZipContentUtil zipUtil = new ZipContentUtil();
Map<String, Long> manifest = zipUtil.getZipManifest(r);
Set<Entry<String, Long>> set = manifest.entrySet();
Iterator<Entry<String, Long>> it = set.iterator();
while (it.hasNext()) {
Entry<String, Long> entry = it.next();
builder.append(entry.getKey() + " (" + formatFileSize(entry.getValue()) + ")" + newline);
}
}
return builder.toString();
}
private String formatFileSize(Long bytes) {
long len = bytes;
String[] byteString = { "KB", "KB", "MB", "GB" };
int count = 0;
long newLen = 0;
long lenBytesExtra = len;
while (len > 1024)
{
newLen = len / 1024;
lenBytesExtra = len - (newLen * 1024);
len = newLen;
count++;
}
if ((lenBytesExtra >= 512) || ((lenBytesExtra > 0) && (newLen == 0)))
{
newLen++;
}
return Long.toString(newLen) + " " + byteString[count];
}
/**
* is this an archive type for which we can get a manifest
* @param r
* @return
*/
private boolean isArchiveFile(Reference r) {
String extension = getFileExtension(r);
if (".zip".equals(extension)) {
return true;
}
return false;
}
private String getFileExtension(Reference r) {
ResourceProperties resourceProperties = r.getProperties();
String fileName = resourceProperties.getProperty(resourceProperties.getNamePropDisplayName());
if (fileName.indexOf(".")>0) {
String extension = fileName.substring(fileName.lastIndexOf("."));
return extension;
}
return null;
}
private String htmlContentReleaseGrade(AssignmentSubmission s)
{
String newline = "<br />\n";
Assignment a = s.getAssignment();
String context = s.getContext();
String siteTitle = "";
String siteId = "";
try
{
Site site = SiteService.getSite(context);
siteTitle = site.getTitle();
siteId = site.getId();
}
catch (Exception ee)
{
M_log.warn(" htmlContentReleaseGrade(), site id =" + context + " " + ee.getMessage());
}
StringBuilder buffer = new StringBuilder();
// site title and id
buffer.append(rb.getString("noti.site.title") + " " + siteTitle + newline);
buffer.append(rb.getString("noti.site.id") + " " + siteId +newline + newline);
// notification text
buffer.append(rb.getFormattedMessage("noti.releasegrade.text", new String[]{a.getTitle(), siteTitle}));
return buffer.toString();
}
private String htmlContentReleaseResubmission(AssignmentSubmission s){
String newline = "<br />\n";
Assignment a = s.getAssignment();
String context = s.getContext();
String siteTitle = "";
String siteId = "";
try {
Site site = SiteService.getSite(context);
siteTitle = site.getTitle();
siteId = site.getId();
}catch (Exception ee){
M_log.warn(this + " htmlContentReleaseResubmission(), site id =" + context + " " + ee.getMessage());
}
StringBuilder buffer = new StringBuilder();
// site title and id
buffer.append(rb.getString("noti.site.title") + " " + siteTitle + newline);
buffer.append(rb.getString("noti.site.id") + " " + siteId +newline + newline);
// notification text
buffer.append(rb.getFormattedMessage("noti.releaseresubmission.text", new String[]{a.getTitle(), siteTitle}));
return buffer.toString();
}
/**
* Cancel the changes made to a AssignmentSubmissionEdit object, and release the lock.
*
* @param submission
* The AssignmentSubmissionEdit object to commit.
*/
public void cancelEdit(AssignmentSubmissionEdit submission)
{
// check for closed edit
if (!submission.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" cancelEdit(): closed AssignmentSubmissionEdit assignment submission id=" + submission.getId() + " " + e.getMessage());
}
return;
}
// release the edit lock
m_submissionStorage.cancel(submission);
// close the edit object
((BaseAssignmentSubmissionEdit) submission).closeEdit();
} // cancelEdit(Submission)
/**
* Removes an AssignmentSubmission and all references to it
*
* @param submission -
* the AssignmentSubmission to remove.
* @throws PermissionException
* if current User does not have permission to do this.
*/
public void removeSubmission(AssignmentSubmissionEdit submission) throws PermissionException
{
if (submission != null)
{
if (!submission.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" removeSubmission(): closed AssignmentSubmissionEdit id=" + submission.getId() + " " + e.getMessage());
}
return;
}
// check security
unlock(SECURE_REMOVE_ASSIGNMENT_SUBMISSION, submission.getReference());
// complete the edit
m_submissionStorage.remove(submission);
// track event
EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_REMOVE_ASSIGNMENT_SUBMISSION, submission.getReference(),
true));
// close the edit object
((BaseAssignmentSubmissionEdit) submission).closeEdit();
// remove any realm defined for this resource
try
{
AuthzGroupService.removeAuthzGroup(AuthzGroupService.getAuthzGroup(submission.getReference()));
}
catch (AuthzPermissionException e)
{
M_log.warn(" removeSubmission: removing realm for : " + submission.getReference() + " : " + e.getMessage());
}
catch (GroupNotDefinedException e)
{
M_log.warn(" removeSubmission: cannot find group for submission " + submission.getReference() + " : " + e.getMessage());
}
}
}// removeSubmission
/**
*@inheritDoc
*/
public int getSubmissionsSize(String context)
{
int size = 0;
List submissions = getSubmissions(context);
if (submissions != null)
{
size = submissions.size();
}
return size;
}
/**
* Access all AssignmentSubmission objects - known to us (not from external providers).
*
* @return A list of AssignmentSubmission objects.
*/
protected List getSubmissions(String context)
{
List<AssignmentSubmission> submissions = m_submissionStorage.getAll(context);
//get all the review scores
if (contentReviewService != null) {
try {
List<ContentReviewItem> reports = contentReviewService.getReportList(null, context);
if (reports != null && reports.size() > 0) {
updateSubmissionList(submissions, reports);
}
} catch (QueueException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SubmissionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ReportException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return submissions;
} // getAssignmentSubmissions
private void updateSubmissionList(List<AssignmentSubmission> submissions, List<ContentReviewItem> reports) {
//lets build a map to avoid multiple searches through the list of reports
Map<String, ContentReviewItem> reportsMap = new HashMap<String, ContentReviewItem> ();
for (int i = 0; i < reports.size(); i++) {
ContentReviewItem item = reports.get(i);
reportsMap.put(item.getUserId(), item);
}
for (int i = 0; i < submissions.size(); i++) {
AssignmentSubmission sub = submissions.get(i);
String submitterid = sub.getSubmitterId();
if (reportsMap.containsKey(submitterid)) {
ContentReviewItem report = reportsMap.get(submitterid);
AssignmentSubmissionEdit edit;
try {
edit = this.editSubmission(sub.getReference());
edit.setReviewScore(report.getReviewScore());
edit.setReviewIconUrl(report.getIconUrl());
edit.setSubmitterId(sub.getSubmitterId());
edit.setReviewError(report.getLastError());
this.commitEdit(edit);
} catch (IdUnusedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (PermissionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InUseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* Access list of all AssignmentContents created by the User.
*
* @param owner -
* The User who's AssignmentContents are requested.
* @return Iterator over all AssignmentContents owned by this User.
*/
public Iterator getAssignmentContents(User owner)
{
List retVal = new ArrayList();
AssignmentContent aContent = null;
List allContents = getAssignmentContents(owner.getId());
for (int x = 0; x < allContents.size(); x++)
{
aContent = (AssignmentContent) allContents.get(x);
if (aContent.getCreator().equals(owner.getId()))
{
retVal.add(aContent);
}
}
if (retVal.isEmpty())
return new EmptyIterator();
else
return retVal.iterator();
}// getAssignmentContents(User)
/**
* Access all the Assignments which have the specified AssignmentContent.
*
* @param content -
* The particular AssignmentContent.
* @return Iterator over all the Assignments with the specified AssignmentContent.
*/
public Iterator getAssignments(AssignmentContent content)
{
List retVal = new ArrayList();
String contentReference = null;
String tempContentReference = null;
if (content != null)
{
contentReference = content.getReference();
List allAssignments = getAssignments(content.getContext());
Assignment tempAssignment = null;
for (int y = 0; y < allAssignments.size(); y++)
{
tempAssignment = (Assignment) allAssignments.get(y);
tempContentReference = tempAssignment.getContentReference();
if (tempContentReference != null)
{
if (tempContentReference.equals(contentReference))
{
retVal.add(tempAssignment);
}
}
}
}
if (retVal.isEmpty())
return new EmptyIterator();
else
return retVal.iterator();
}
/**
* Access all the Assignemnts associated with the context
*
* @param context -
* Describes the portlet context - generated with DefaultId.getChannel().
* @return Iterator over all the Assignments associated with the context and the user.
*/
public Iterator getAssignmentsForContext(String context)
{
M_log.debug(this + " GET ASSIGNMENTS FOR CONTEXT : CONTEXT : " + context);
return assignmentsForContextAndUser(context, null);
}
/**
* Access all the Assignemnts associated with the context and the user
*
* @param context -
* Describes the portlet context - generated with DefaultId.getChannel()
* @return Iterator over all the Assignments associated with the context and the user
*/
public Iterator getAssignmentsForContext(String context, String userId)
{
M_log.debug(this + " GET ASSIGNMENTS FOR CONTEXT : CONTEXT : " + context);
return assignmentsForContextAndUser(context, userId);
}
/**
* @inheritDoc
*/
public Map<Assignment, List<String>> getSubmittableAssignmentsForContext(String context)
{
Map<Assignment, List<String>> submittable = new HashMap<Assignment, List<String>>();
if (!allowGetAssignment(context))
{
// no permission to read assignment in context
return submittable;
}
Site site = null;
try {
site = SiteService.getSite(context);
} catch (IdUnusedException e) {
if (M_log.isDebugEnabled()) {
M_log.debug("Could not retrieve submittable assignments for nonexistent site: " + context);
}
}
if (site == null)
{
return submittable;
}
Set<String> siteSubmitterIds = AuthzGroupService.getUsersIsAllowed(
SECURE_ADD_ASSIGNMENT_SUBMISSION, Arrays.asList(site.getReference()));
Map<String, Set<String>> groupIdUserIds = new HashMap<String, Set<String>>();
for (Group group : site.getGroups()) {
String groupRef = group.getReference();
for (Member member : group.getMembers()) {
if (member.getRole().isAllowed(SECURE_ADD_ASSIGNMENT_SUBMISSION)) {
if (!groupIdUserIds.containsKey(groupRef)) {
groupIdUserIds.put(groupRef, new HashSet<String>());
}
groupIdUserIds.get(groupRef).add(member.getUserId());
}
}
}
List<Assignment> assignments = (List<Assignment>) getAssignments(context);
for (Assignment assignment : assignments) {
Set<String> userIds = new HashSet<String>();
if (assignment.getAccess() == Assignment.AssignmentAccess.GROUPED) {
for (String groupRef : (Collection<String>) assignment.getGroups()) {
if (groupIdUserIds.containsKey(groupRef)) {
userIds.addAll(groupIdUserIds.get(groupRef));
}
}
} else {
userIds.addAll(siteSubmitterIds);
}
submittable.put(assignment, new ArrayList(userIds));
}
return submittable;
}
/**
* get proper assignments for specified context and user
* @param context
* @param user
* @return
*/
private Iterator assignmentsForContextAndUser(String context, String userId)
{
Assignment tempAssignment = null;
List retVal = new ArrayList();
List allAssignments = null;
if (context != null)
{
allAssignments = getAssignments(context, userId);
for (int x = 0; x < allAssignments.size(); x++)
{
tempAssignment = (Assignment) allAssignments.get(x);
if ((context.equals(tempAssignment.getContext()))
|| (context.equals(getGroupNameFromContext(tempAssignment.getContext()))))
{
retVal.add(tempAssignment);
}
}
}
if (retVal.isEmpty())
return new EmptyIterator();
else
return retVal.iterator();
}
/**
* @inheritDoc
*/
public List getListAssignmentsForContext(String context)
{
M_log.debug(this + " getListAssignmetsForContext : CONTEXT : " + context);
Assignment tempAssignment = null;
List retVal = new ArrayList();
if (context != null)
{
List allAssignments = getAssignments(context);
for (int x = 0; x < allAssignments.size(); x++)
{
tempAssignment = (Assignment) allAssignments.get(x);
if ((context.equals(tempAssignment.getContext()))
|| (context.equals(getGroupNameFromContext(tempAssignment.getContext()))))
{
String deleted = tempAssignment.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED);
if (deleted == null || "".equals(deleted))
{
// not deleted, show it
if (tempAssignment.getDraft())
{
// who can see the draft assigment
if (isDraftAssignmentVisible(tempAssignment, context))
{
retVal.add(tempAssignment);
}
}
else
{
retVal.add(tempAssignment);
}
}
}
}
}
return retVal;
}
/**
* who can see the draft assignment
* @param assignment
* @param context
* @return
*/
private boolean isDraftAssignmentVisible(Assignment assignment, String context)
{
return securityService.isSuperUser() // super user can always see it
|| assignment.getCreator().equals(UserDirectoryService.getCurrentUser().getId()) // the creator can see it
|| (unlockCheck(SECURE_SHARE_DRAFTS, SiteService.siteReference(context))); // any role user with share draft permission
}
/**
* Access a User's AssignmentSubmission to a particular Assignment.
*
* @param assignmentReference
* The reference of the assignment.
* @param person -
* The User who's Submission you would like.
* @return AssignmentSubmission The user's submission for that Assignment.
* @throws IdUnusedException
* if there is no object with this id.
* @throws PermissionException
* if the current user is not allowed to access this.
*/
public AssignmentSubmission getSubmission(String assignmentReference, User person)
{
AssignmentSubmission submission = null;
String assignmentId = assignmentId(assignmentReference);
if ((assignmentReference != null) && (person != null))
{
try {
Assignment a = getAssignment(assignmentReference);
if (a.isGroup()) {
Site _site = SiteService.getSite( a.getContext() );
Collection groups = _site.getGroupsWithMember(person.getId());
if (groups != null) {
Iterator<Group> itgroup = groups.iterator();
while (submission == null && itgroup.hasNext()) {
Group _g = itgroup.next();
submission = getSubmission(assignmentReference, _g.getId());
}
}
} else {
M_log.debug(" BaseAssignmentContent : Getting submission ");
submission = m_submissionStorage.get(assignmentId, person.getId());
}
} catch (IdUnusedException iue) { } catch (PermissionException pme) { }
}
if (submission != null)
{
try
{
unlock2(SECURE_ACCESS_ASSIGNMENT_SUBMISSION, SECURE_ACCESS_ASSIGNMENT, submission.getReference());
}
catch (PermissionException e)
{
return null;
}
}
return submission;
}
/**
*
* Access a Group or User's AssignmentSubmission to a particular Assignment.
*
* @param assignmentReference
* The reference of the assignment.
* @param submitter -
* The User or Group who's Submission you would like.
* @return AssignmentSubmission The user's submission for that Assignment.
* @throws IdUnusedException
* if there is no object with this id.
* @throws PermissionException
* if the current user is not allowed to access this.
*/
public AssignmentSubmission getSubmission(String assignmentReference, String submitter)
{
AssignmentSubmission submission = null;
String assignmentId = assignmentId(assignmentReference);
if ((assignmentReference != null) && (submitter != null))
{
submission = m_submissionStorage.get(assignmentId, submitter);
}
if (submission != null)
{
try
{
unlock2(SECURE_ACCESS_ASSIGNMENT_SUBMISSION, SECURE_ACCESS_ASSIGNMENT, submission.getReference());
}
catch (PermissionException e)
{
return null;
}
}
return submission;
}
/**
* @inheritDoc
*/
public AssignmentSubmission getSubmission(List submissions, User person)
{
AssignmentSubmission retVal = null;
for (int z = 0; z < submissions.size(); z++)
{
AssignmentSubmission sub = (AssignmentSubmission) submissions.get(z);
if (sub != null)
{
List submitters = sub.getSubmitterIds();
for (int a = 0; a < submitters.size(); a++)
{
String aUserId = (String) submitters.get(a);
M_log.debug(this + " getSubmission(List, User) comparing aUser id : " + aUserId + " and chosen user id : "
+ person.getId());
if (aUserId.equals(person.getId()))
{
M_log.debug(this + " getSubmission(List, User) found a match : return value is " + sub.getId());
retVal = sub;
}
}
}
}
return retVal;
}
/**
* Get the submissions for an assignment.
*
* @param assignment -
* the Assignment who's submissions you would like.
* @return Iterator over all the submissions for an Assignment.
*/
public List getSubmissions(Assignment assignment)
{
List retVal = new ArrayList();
if (assignment != null)
{
retVal = getSubmissions(assignment.getId());
}
return retVal;
}
/**
* {@inheritDoc}
*/
public int getSubmittedSubmissionsCount(String assignmentRef)
{
return m_submissionStorage.getSubmittedSubmissionsCount(assignmentRef);
}
/**
* {@inheritDoc}
*/
public int getUngradedSubmissionsCount(String assignmentRef)
{
return m_submissionStorage.getUngradedSubmissionsCount(assignmentRef);
}
/**
* Access the AssignmentSubmission with the specified id.
*
* @param submissionReference -
* The reference of the AssignmentSubmission.
* @return The AssignmentSubmission corresponding to the id, or null if it does not exist.
* @throws IdUnusedException
* if there is no object with this id.
* @throws PermissionException
* if the current user is not allowed to access this.
*/
public AssignmentSubmission getSubmission(String submissionReference) throws IdUnusedException, PermissionException
{
M_log.debug(this + " GET SUBMISSION : REF : " + submissionReference);
// check permission
unlock2(SECURE_ACCESS_ASSIGNMENT_SUBMISSION, SECURE_ACCESS_ASSIGNMENT, submissionReference);
AssignmentSubmission submission = null;
String submissionId = submissionId(submissionReference);
submission = m_submissionStorage.get(submissionId);
if (submission == null) throw new IdUnusedException(submissionId);
// double check the submission submitter information:
// if current user is not the original submitter and if he doesn't have grading permission, he should not have access to other people's submission.
String assignmentRef = assignmentReference(submission.getContext(), submission.getAssignmentId());
if (!allowGradeSubmission(assignmentRef))
{
List submitterIds = submission.getSubmitterIds();
if (submitterIds != null && !submitterIds.contains(SessionManager.getCurrentSessionUserId()))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), SECURE_ACCESS_ASSIGNMENT_SUBMISSION, submissionId);
}
}
// track event
// EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT_SUBMISSION, submission.getReference(), false));
return submission;
}// getAssignmentSubmission
/**
* Return the reference root for use in resource references and urls.
*
* @return The reference root for use in resource references and urls.
*/
protected String getReferenceRoot()
{
return REFERENCE_ROOT;
}
/**
* Update the live properties for an object when modified.
*/
protected void addLiveUpdateProperties(ResourcePropertiesEdit props)
{
props.addProperty(ResourceProperties.PROP_MODIFIED_BY, SessionManager.getCurrentSessionUserId());
props.addProperty(ResourceProperties.PROP_MODIFIED_DATE, TimeService.newTime().toString());
} // addLiveUpdateProperties
/**
* Create the live properties for the object.
*/
protected void addLiveProperties(ResourcePropertiesEdit props)
{
String current = SessionManager.getCurrentSessionUserId();
props.addProperty(ResourceProperties.PROP_CREATOR, current);
props.addProperty(ResourceProperties.PROP_MODIFIED_BY, current);
String now = TimeService.newTime().toString();
props.addProperty(ResourceProperties.PROP_CREATION_DATE, now);
props.addProperty(ResourceProperties.PROP_MODIFIED_DATE, now);
} // addLiveProperties
/**
* check permissions for addAssignment().
*
* @param context -
* Describes the portlet context - generated with DefaultId.getChannel()
* @return true if the user is allowed to addAssignment(...), false if not.
*/
public boolean allowAddGroupAssignment(String context)
{
// base the check for SECURE_ADD on the site, any of the site's groups, and the channel
// if the user can SECURE_ADD anywhere in that mix, they can add an assignment
// this stack is not the normal azg set for channels, so use a special refernce to get this behavior
String resourceString = getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_ASSIGNMENT_GROUPS + Entity.SEPARATOR + "a"
+ Entity.SEPARATOR + context + Entity.SEPARATOR;
{
M_log.debug(this + " allowAddGroupAssignment with resource string : " + resourceString);
M_log.debug(" context string : " + context);
}
// check security on the channel (throws if not permitted)
return unlockCheck(SECURE_ADD_ASSIGNMENT, resourceString);
} // allowAddGroupAssignment
/**
* @inheritDoc
*/
public boolean allowReceiveSubmissionNotification(String context)
{
String resourceString = getContextReference(context);
{
M_log.debug(this + " allowReceiveSubmissionNotification with resource string : " + resourceString);
}
// checking allow at the site level
if (unlockCheck(SECURE_ASSIGNMENT_RECEIVE_NOTIFICATIONS, resourceString)) return true;
return false;
}
/**
* @inheritDoc
*/
public List allowReceiveSubmissionNotificationUsers(String context)
{
String resourceString = getContextReference(context);
{
M_log.debug(this + " allowReceiveSubmissionNotificationUsers with resource string : " + resourceString);
M_log.debug(" context string : " + context);
}
return securityService.unlockUsers(SECURE_ASSIGNMENT_RECEIVE_NOTIFICATIONS, resourceString);
} // allowAddAssignmentUsers
/**
* @inheritDoc
*/
public boolean allowAddAssignment(String context)
{
String resourceString = getContextReference(context);
// base the check for SECURE_ADD_ASSIGNMENT on the site and any of the site's groups
// if the user can SECURE_ADD_ASSIGNMENT anywhere in that mix, they can add an assignment
// this stack is not the normal azg set for site, so use a special refernce to get this behavior
{
M_log.debug(this + " allowAddAssignment with resource string : " + resourceString);
}
// checking allow at the site level
if (unlockCheck(SECURE_ADD_ASSIGNMENT, resourceString)) return true;
// if not, see if the user has any groups to which adds are allowed
return (!getGroupsAllowAddAssignment(context).isEmpty());
}
/**
* @inheritDoc
*/
public boolean allowAddSiteAssignment(String context)
{
// check for assignments that will be site-wide:
String resourceString = getContextReference(context);
{
M_log.debug(this + " allowAddSiteAssignment with resource string : " + resourceString);
}
// check security on the channel (throws if not permitted)
return unlockCheck(SECURE_ADD_ASSIGNMENT, resourceString);
}
/**
* @inheritDoc
*/
public boolean allowAllGroups(String context)
{
String resourceString = getContextReference(context);
{
M_log.debug(this + " allowAllGroups with resource string : " + resourceString);
}
// checking all.groups
if (unlockCheck(SECURE_ALL_GROUPS, resourceString)) return true;
// if not
return false;
}
/**
* @inheritDoc
*/
public Collection getGroupsAllowAddAssignment(String context)
{
return getGroupsAllowFunction(SECURE_ADD_ASSIGNMENT, context, null);
}
/**
* @inheritDoc
*/
public Collection getGroupsAllowGradeAssignment(String context, String assignmentReference)
{
Collection rv = new ArrayList();
if (allowGradeSubmission(assignmentReference))
{
// only if the user is allowed to group at all
Collection allAllowedGroups = getGroupsAllowFunction(SECURE_GRADE_ASSIGNMENT_SUBMISSION, context, null);
try
{
Assignment a = getAssignment(assignmentReference);
if (a.getAccess() == Assignment.AssignmentAccess.SITE)
{
// for site-scope assignment, return all groups
rv = allAllowedGroups;
}
else
{
Collection aGroups = a.getGroups();
// for grouped assignment, return only those also allowed for grading
for (Iterator i = allAllowedGroups.iterator(); i.hasNext();)
{
Group g = (Group) i.next();
if (aGroups.contains(g.getReference()))
{
rv.add(g);
}
}
}
}
catch (Exception e)
{
M_log.info(this + " getGroupsAllowGradeAssignment " + e.getMessage() + assignmentReference);
}
}
return rv;
}
/**
* @inherit
*/
public boolean allowGetAssignment(String context)
{
String resourceString = getContextReference(context);
{
M_log.debug(this + " allowGetAssignment with resource string : " + resourceString);
}
return unlockCheck(SECURE_ACCESS_ASSIGNMENT, resourceString);
}
/**
* @inheritDoc
*/
public Collection getGroupsAllowGetAssignment(String context)
{
return getGroupsAllowFunction(SECURE_ACCESS_ASSIGNMENT, context, null);
}
// for specified user
private Collection getGroupsAllowGetAssignment(String context, String userId)
{
return getGroupsAllowFunction(SECURE_ACCESS_ASSIGNMENT, context, userId);
}
/**
* Check permissions for updateing an Assignment.
*
* @param assignmentReference -
* The Assignment's reference.
* @return True if the current User is allowed to update the Assignment, false if not.
*/
public boolean allowUpdateAssignment(String assignmentReference)
{
M_log.debug(this + " allowUpdateAssignment with resource string : " + assignmentReference);
return unlockCheck(SECURE_UPDATE_ASSIGNMENT, assignmentReference);
}
/**
* Check permissions for removing an Assignment.
*
* @return True if the current User is allowed to remove the Assignment, false if not.
*/
public boolean allowRemoveAssignment(String assignmentReference)
{
M_log.debug(this + " allowRemoveAssignment " + assignmentReference);
// check security (throws if not permitted)
return unlockCheck(SECURE_REMOVE_ASSIGNMENT, assignmentReference);
}
/**
* @inheritDoc
*/
public Collection getGroupsAllowRemoveAssignment(String context)
{
return getGroupsAllowFunction(SECURE_REMOVE_ASSIGNMENT, context, null);
}
/**
* Get the groups of this channel's contex-site that the end user has permission to "function" in.
*
* @param function
* The function to check
*/
protected Collection getGroupsAllowFunction(String function, String context, String userId)
{
Collection rv = new ArrayList();
try
{
// get the site groups
Site site = SiteService.getSite(context);
Collection groups = site.getGroups();
if (securityService.isSuperUser())
{
// for super user, return all groups
return groups;
}
else if (userId == null)
{
// for current session user
userId = SessionManager.getCurrentSessionUserId();
}
// if the user has SECURE_ALL_GROUPS in the context (site), select all site groups
if (securityService.unlock(userId, SECURE_ALL_GROUPS, SiteService.siteReference(context)) && unlockCheck(function, SiteService.siteReference(context)))
{
return groups;
}
// otherwise, check the groups for function
// get a list of the group refs, which are authzGroup ids
Collection groupRefs = new ArrayList();
for (Iterator i = groups.iterator(); i.hasNext();)
{
Group group = (Group) i.next();
groupRefs.add(group.getReference());
}
// ask the authzGroup service to filter them down based on function
groupRefs = AuthzGroupService.getAuthzGroupsIsAllowed(userId,
function, groupRefs);
// pick the Group objects from the site's groups to return, those that are in the groupRefs list
for (Iterator i = groups.iterator(); i.hasNext();)
{
Group group = (Group) i.next();
if (groupRefs.contains(group.getReference()))
{
rv.add(group);
}
}
}
catch (IdUnusedException e)
{
M_log.debug(this + " getGroupsAllowFunction idunused :" + context + " : " + e.getMessage());
}
return rv;
}
/** ***********************************************check permissions for AssignmentContent object ******************************************* */
/**
* Check permissions for get AssignmentContent
*
* @param contentReference -
* The AssignmentContent reference.
* @return True if the current User is allowed to access the AssignmentContent, false if not.
*/
public boolean allowGetAssignmentContent(String context)
{
String resourceString = getAccessPoint(true) + Entity.SEPARATOR + "c" + Entity.SEPARATOR + context + Entity.SEPARATOR;
{
M_log.debug(this + " allowGetAssignmentContent with resource string : " + resourceString);
}
// check security (throws if not permitted)
return unlockCheck(SECURE_ACCESS_ASSIGNMENT_CONTENT, resourceString);
}
/**
* Check permissions for updating AssignmentContent
*
* @param contentReference -
* The AssignmentContent reference.
* @return True if the current User is allowed to update the AssignmentContent, false if not.
*/
public boolean allowUpdateAssignmentContent(String contentReference)
{
M_log.debug(this + " allowUpdateAssignmentContent with resource string : " + contentReference);
// check security (throws if not permitted)
return unlockCheck(SECURE_UPDATE_ASSIGNMENT_CONTENT, contentReference);
}
/**
* Check permissions for adding an AssignmentContent.
*
* @param context -
* Describes the portlet context - generated with DefaultId.getChannel().
* @return True if the current User is allowed to add an AssignmentContent, false if not.
*/
public boolean allowAddAssignmentContent(String context)
{
String resourceString = getAccessPoint(true) + Entity.SEPARATOR + "c" + Entity.SEPARATOR + context + Entity.SEPARATOR;
M_log.debug(this + "allowAddAssignmentContent with resource string : " + resourceString);
// check security (throws if not permitted)
if (unlockCheck(SECURE_ADD_ASSIGNMENT_CONTENT, resourceString)) return true;
// if not, see if the user has any groups to which adds are allowed
return (!getGroupsAllowAddAssignment(context).isEmpty());
}
/**
* Check permissions for remove the AssignmentContent
*
* @param contentReference -
* The AssignmentContent reference.
* @return True if the current User is allowed to remove the AssignmentContent, false if not.
*/
public boolean allowRemoveAssignmentContent(String contentReference)
{
M_log.debug(this + " allowRemoveAssignmentContent with referece string : " + contentReference);
// check security (throws if not permitted)
return unlockCheck(SECURE_REMOVE_ASSIGNMENT_CONTENT, contentReference);
}
/**
* Check permissions for add AssignmentSubmission
*
* @param context -
* Describes the portlet context - generated with DefaultId.getChannel().
* @return True if the current User is allowed to add an AssignmentSubmission, false if not.
*/
public boolean allowAddSubmission(String context)
{
// check security (throws if not permitted)
String resourceString = getAccessPoint(true) + Entity.SEPARATOR + "s" + Entity.SEPARATOR + context + Entity.SEPARATOR;
M_log.debug(this + " allowAddSubmission with resource string : " + resourceString);
return unlockCheck(SECURE_ADD_ASSIGNMENT_SUBMISSION, resourceString);
}
/**
* SAK-21525
*
* @param context
* @param assignment - An Assignment object. Needed for the groups to be checked.
* @return
*/
public boolean allowAddSubmissionCheckGroups(String context, Assignment assignment)
{
// check security (throws if not permitted)
String resourceString = getAccessPoint(true) + Entity.SEPARATOR + "s" + Entity.SEPARATOR + context + Entity.SEPARATOR;
M_log.debug(this + " allowAddSubmission with resource string : " + resourceString);
return unlockCheckWithGroups(SECURE_ADD_ASSIGNMENT_SUBMISSION, resourceString, assignment);
}
/**
* Get the List of Users who can addSubmission() for this assignment.
*
* @param assignmentReference -
* a reference to an assignment
* @return the List (User) of users who can addSubmission() for this assignment.
*/
public List allowAddSubmissionUsers(String assignmentReference)
{
return securityService.unlockUsers(SECURE_ADD_ASSIGNMENT_SUBMISSION, assignmentReference);
} // allowAddSubmissionUsers
/**
* Get the List of Users who can grade submission for this assignment.
*
* @param assignmentReference -
* a reference to an assignment
* @return the List (User) of users who can grade submission for this assignment.
*/
public List allowGradeAssignmentUsers(String assignmentReference)
{
List users = securityService.unlockUsers(SECURE_GRADE_ASSIGNMENT_SUBMISSION, assignmentReference);
if (users == null)
{
users = new ArrayList();
}
try
{
Assignment a = getAssignment(assignmentReference);
if (a.getAccess() == Assignment.AssignmentAccess.GROUPED)
{
// for grouped assignment, need to include those users that with "all.groups" and "grade assignment" permissions on the site level
AuthzGroup group = AuthzGroupService.getAuthzGroup(SiteService.siteReference(a.getContext()));
if (group != null)
{
// get the roles which are allowed for submission but not for all_site control
Set rolesAllowAllSite = group.getRolesIsAllowed(SECURE_ALL_GROUPS);
Set rolesAllowGradeAssignment = group.getRolesIsAllowed(SECURE_GRADE_ASSIGNMENT_SUBMISSION);
// save all the roles with both "all.groups" and "grade assignment" permissions
if (rolesAllowAllSite != null)
rolesAllowAllSite.retainAll(rolesAllowGradeAssignment);
if (rolesAllowAllSite != null && rolesAllowAllSite.size() > 0)
{
for (Iterator iRoles = rolesAllowAllSite.iterator(); iRoles.hasNext(); )
{
Set<String> userIds = group.getUsersHasRole((String) iRoles.next());
if (userIds != null)
{
for (Iterator<String> iUserIds = userIds.iterator(); iUserIds.hasNext(); )
{
String userId = iUserIds.next();
try
{
User u = UserDirectoryService.getUser(userId);
if (!users.contains(u))
{
users.add(u);
}
}
catch (Exception ee)
{
M_log.warn(" allowGradeAssignmentUsers " + ee.getMessage() + " problem with getting user =" + userId);
}
}
}
}
}
}
}
}
catch (Exception e)
{
M_log.warn(" allowGradeAssignmentUsers " + e.getMessage() + " assignmentReference=" + assignmentReference);
}
return users;
} // allowGradeAssignmentUsers
/**
* @inheritDoc
* @param context
* @return
*/
public List allowAddAnySubmissionUsers(String context)
{
List<String> rv = new Vector();
try
{
AuthzGroup group = AuthzGroupService.getAuthzGroup(SiteService.siteReference(context));
// get the roles which are allowed for submission but not for all_site control
Set rolesAllowSubmission = group.getRolesIsAllowed(SECURE_ADD_ASSIGNMENT_SUBMISSION);
Set rolesAllowAllSite = group.getRolesIsAllowed(SECURE_ALL_GROUPS);
rolesAllowSubmission.removeAll(rolesAllowAllSite);
for (Iterator iRoles = rolesAllowSubmission.iterator(); iRoles.hasNext(); )
{
rv.addAll(group.getUsersHasRole((String) iRoles.next()));
}
}
catch (Exception e)
{
M_log.warn(" allowAddAnySubmissionUsers " + e.getMessage() + " context=" + context);
}
return rv;
}
/**
* Get the List of Users who can add assignment
*
* @param assignmentReference -
* a reference to an assignment
* @return the List (User) of users who can addSubmission() for this assignment.
*/
public List allowAddAssignmentUsers(String context)
{
String resourceString = getContextReference(context);
{
M_log.debug(this + " allowAddAssignmentUsers with resource string : " + resourceString);
M_log.debug(" context string : " + context);
}
return securityService.unlockUsers(SECURE_ADD_ASSIGNMENT, resourceString);
} // allowAddAssignmentUsers
/**
* Check permissions for accessing a Submission.
*
* @param submissionReference -
* The Submission's reference.
* @return True if the current User is allowed to get the AssignmentSubmission, false if not.
*/
public boolean allowGetSubmission(String submissionReference)
{
M_log.debug(this + " allowGetSubmission with resource string : " + submissionReference);
return unlockCheck2(SECURE_ACCESS_ASSIGNMENT_SUBMISSION, SECURE_ACCESS_ASSIGNMENT, submissionReference);
}
/**
* Check permissions for updating Submission.
*
* @param submissionReference -
* The Submission's reference.
* @return True if the current User is allowed to update the AssignmentSubmission, false if not.
*/
public boolean allowUpdateSubmission(String submissionReference)
{
M_log.debug(this + " allowUpdateSubmission with resource string : " + submissionReference);
return unlockCheck2(SECURE_UPDATE_ASSIGNMENT_SUBMISSION, SECURE_UPDATE_ASSIGNMENT, submissionReference);
}
/**
* Check permissions for remove Submission
*
* @param submissionReference -
* The Submission's reference.
* @return True if the current User is allowed to remove the AssignmentSubmission, false if not.
*/
public boolean allowRemoveSubmission(String submissionReference)
{
M_log.debug(this + " allowRemoveSubmission with resource string : " + submissionReference);
// check security (throws if not permitted)
return unlockCheck(SECURE_REMOVE_ASSIGNMENT_SUBMISSION, submissionReference);
}
public boolean allowGradeSubmission(String assignmentReference)
{
{
M_log.debug(this + " allowGradeSubmission with resource string : " + assignmentReference);
}
return unlockCheck(SECURE_GRADE_ASSIGNMENT_SUBMISSION, assignmentReference);
}
/**
* Access the grades spreadsheet for the reference, either for an assignment or all assignments in a context.
*
* @param ref
* The reference, either to a specific assignment, or just to an assignment context.
* @return The grades spreadsheet bytes.
* @throws IdUnusedException
* if there is no object with this id.
* @throws PermissionException
* if the current user is not allowed to access this.
*/
public byte[] getGradesSpreadsheet(String ref) throws IdUnusedException, PermissionException
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (getGradesSpreadsheet(out, ref)) {
return out.toByteArray();
}
return null;
}
/**
* Access and output the grades spreadsheet for the reference, either for an assignment or all assignments in a context.
*
* @param out
* The outputStream to stream the grades spreadsheet into.
* @param ref
* The reference, either to a specific assignment, or just to an assignment context.
* @return Whether the grades spreadsheet is successfully output.
* @throws IdUnusedException
* if there is no object with this id.
* @throws PermissionException
* if the current user is not allowed to access this.
*/
public boolean getGradesSpreadsheet(final OutputStream out, final String ref)
throws IdUnusedException, PermissionException {
boolean retVal = false;
String typeGradesString = REF_TYPE_GRADES + Entity.SEPARATOR;
String context = ref.substring(ref.indexOf(typeGradesString) + typeGradesString.length());
// get site title for display purpose
String siteTitle = "";
try
{
Site s = SiteService.getSite(context);
siteTitle = s.getTitle();
}
catch (Exception e)
{
// ignore exception
M_log.debug(this + ":getGradesSpreadsheet cannot get site context=" + context + e.getMessage());
}
// does current user allowed to grade any assignment?
boolean allowGradeAny = false;
List assignmentsList = getListAssignmentsForContext(context);
for (int iAssignment = 0; !allowGradeAny && iAssignment<assignmentsList.size(); iAssignment++)
{
if (allowGradeSubmission(((Assignment) assignmentsList.get(iAssignment)).getReference()))
{
allowGradeAny = true;
}
}
if (!allowGradeAny)
{
// not permitted to download the spreadsheet
return false;
}
else
{
short rowNum = 0;
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(WorkbookUtil.createSafeSheetName(siteTitle));
// Create a row and put some cells in it. Rows are 0 based.
HSSFRow row = sheet.createRow(rowNum++);
row.createCell((short) 0).setCellValue(rb.getString("download.spreadsheet.title"));
// empty line
row = sheet.createRow(rowNum++);
row.createCell((short) 0).setCellValue("");
// site title
row = sheet.createRow(rowNum++);
row.createCell((short) 0).setCellValue(rb.getString("download.spreadsheet.site") + siteTitle);
// download time
row = sheet.createRow(rowNum++);
row.createCell((short) 0).setCellValue(
rb.getString("download.spreadsheet.date") + TimeService.newTime().toStringLocalFull());
// empty line
row = sheet.createRow(rowNum++);
row.createCell((short) 0).setCellValue("");
HSSFCellStyle style = wb.createCellStyle();
// this is the header row number
short headerRowNumber = rowNum;
// set up the header cells
row = sheet.createRow(rowNum++);
short cellNum = 0;
// user enterprise id column
HSSFCell cell = row.createCell(cellNum++);
cell.setCellStyle(style);
cell.setCellValue(rb.getString("download.spreadsheet.column.name"));
// user name column
cell = row.createCell(cellNum++);
cell.setCellStyle(style);
cell.setCellValue(rb.getString("download.spreadsheet.column.userid"));
// starting from this row, going to input user data
Iterator assignments = new SortedIterator(assignmentsList.iterator(), new AssignmentComparator("duedate", "true"));
// site members excluding those who can add assignments
List members = new ArrayList();
// hashmap which stores the Excel row number for particular user
HashMap user_row = new HashMap();
List allowAddAnySubmissionUsers = allowAddAnySubmissionUsers(context);
for (Iterator iUserIds = new SortedIterator(allowAddAnySubmissionUsers.iterator(), new AssignmentComparator("sortname", "true")); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
try
{
User u = UserDirectoryService.getUser(userId);
members.add(u);
// create the column for user first
row = sheet.createRow(rowNum);
// update user_row Hashtable
user_row.put(u.getId(), Integer.valueOf(rowNum));
// increase row
rowNum++;
// put user displayid and sortname in the first two cells
cellNum = 0;
row.createCell(cellNum++).setCellValue(u.getSortName());
row.createCell(cellNum).setCellValue(u.getDisplayId());
}
catch (Exception e)
{
M_log.warn(" getGradesSpreadSheet " + e.getMessage() + " userId = " + userId);
}
}
int index = 0;
// the grade data portion starts from the third column, since the first two are used for user's display id and sort name
while (assignments.hasNext())
{
Assignment a = (Assignment) assignments.next();
int assignmentType = a.getContent().getTypeOfGrade();
// for column header, check allow grade permission based on each assignment
if(!a.getDraft() && allowGradeSubmission(a.getReference()))
{
// put in assignment title as the column header
rowNum = headerRowNumber;
row = sheet.getRow(rowNum++);
cellNum = (short) (index + 2);
cell = row.createCell(cellNum); // since the first two column is taken by student id and name
cell.setCellStyle(style);
cell.setCellValue(a.getTitle());
for (int loopNum = 0; loopNum < members.size(); loopNum++)
{
// prepopulate the column with the "no submission" string
row = sheet.getRow(rowNum++);
cell = row.createCell(cellNum);
cell.setCellType(1);
cell.setCellValue(rb.getString("listsub.nosub"));
}
// begin to populate the column for this assignment, iterating through student list
for (Iterator sIterator=getSubmissions(a).iterator(); sIterator.hasNext();)
{
AssignmentSubmission submission = (AssignmentSubmission) sIterator.next();
String userId = submission.getSubmitterId();
if (a.isGroup()) {
User[] _users = submission.getSubmitters();
for (int i=0; _users != null && i < _users.length; i++) {
userId = _users[i].getId();
if (user_row.containsKey(userId))
{
// find right row
row = sheet.getRow(((Integer)user_row.get(userId)).intValue());
if (submission.getGraded() && submission.getGrade() != null)
{
// graded and released
if (assignmentType == 3)
{
try
{
// numeric cell type?
String grade = submission.getGradeForUser(userId) == null ? submission.getGradeDisplay():
submission.getGradeForUser(userId);
//We get float number no matter the locale it was managed with.
NumberFormat nbFormat = NumberFormat.getNumberInstance(rb.getLocale());
nbFormat.setMaximumFractionDigits(1);
nbFormat.setMinimumFractionDigits(1);
float f = nbFormat.parse(grade).floatValue();
// remove the String-based cell first
cell = row.getCell(cellNum);
row.removeCell(cell);
// add number based cell
cell=row.createCell(cellNum);
cell.setCellType(0);
cell.setCellValue(f);
style = wb.createCellStyle();
style.setDataFormat(wb.createDataFormat().getFormat("#,##0.0"));
cell.setCellStyle(style);
}
catch (Exception e)
{
// if the grade is not numeric, let's make it as String type
// No need to remove the cell and create a new one, as the existing one is String type.
cell = row.getCell(cellNum);
cell.setCellType(1);
cell.setCellValue(submission.getGradeForUser(userId) == null ? submission.getGradeDisplay():
submission.getGradeForUser(userId));
}
}
else
{
// String cell type
cell = row.getCell(cellNum);
cell.setCellValue(submission.getGradeForUser(userId) == null ? submission.getGradeDisplay():
submission.getGradeForUser(userId));
}
}
else if (submission.getSubmitted() && submission.getTimeSubmitted() != null)
{
// submitted, but no grade available yet
cell = row.getCell(cellNum);
cell.setCellValue(rb.getString("gen.nograd"));
}
} // if
}
}
else
{
if (user_row.containsKey(userId))
{
// find right row
row = sheet.getRow(((Integer)user_row.get(userId)).intValue());
if (submission.getGraded() && submission.getGrade() != null)
{
// graded and released
if (assignmentType == 3)
{
try
{
// numeric cell type?
String grade = submission.getGradeDisplay();
//We get float number no matter the locale it was managed with.
NumberFormat nbFormat = NumberFormat.getNumberInstance(rb.getLocale());
nbFormat.setMaximumFractionDigits(1);
nbFormat.setMinimumFractionDigits(1);
float f = nbFormat.parse(grade).floatValue();
// remove the String-based cell first
cell = row.getCell(cellNum);
row.removeCell(cell);
// add number based cell
cell=row.createCell(cellNum);
cell.setCellType(0);
cell.setCellValue(f);
style = wb.createCellStyle();
style.setDataFormat(wb.createDataFormat().getFormat("#,##0.0"));
cell.setCellStyle(style);
}
catch (Exception e)
{
// if the grade is not numeric, let's make it as String type
// No need to remove the cell and create a new one, as the existing one is String type.
cell = row.getCell(cellNum);
cell.setCellType(1);
// Setting grade display instead grade.
cell.setCellValue(submission.getGradeDisplay());
}
}
else
{
// String cell type
cell = row.getCell(cellNum);
cell.setCellValue(submission.getGradeDisplay());
}
}
else if (submission.getSubmitted() && submission.getTimeSubmitted() != null)
{
// submitted, but no grade available yet
cell = row.getCell(cellNum);
cell.setCellValue(rb.getString("gen.nograd"));
}
} // if
}
}
}
index++;
}
// output
try
{
wb.write(out);
retVal = true;
}
catch (IOException e)
{
M_log.warn(" getGradesSpreadsheet Can not output the grade spread sheet for reference= " + ref);
}
return retVal;
}
} // getGradesSpreadsheet
@SuppressWarnings("deprecation")
public Collection<Group> getSubmitterGroupList(String searchFilterOnly, String allOrOneGroup, String searchString, String aRef, String contextString) {
Collection<Group> rv = new ArrayList<Group>();
allOrOneGroup = StringUtil.trimToNull(allOrOneGroup);
searchString = StringUtil.trimToNull(searchString);
boolean bSearchFilterOnly = "true".equalsIgnoreCase(searchFilterOnly);
try
{
Assignment a = getAssignment(aRef);
if (a != null)
{
Site st = SiteService.getSite(contextString);
if (a.getAccess().equals(Assignment.AssignmentAccess.SITE))
{
Collection<Group> groupRefs = st.getGroups();
for (Iterator gIterator = groupRefs.iterator(); gIterator.hasNext();)
{
Group _gg = (Group)gIterator.next();
//if (_gg.getProperties().get(GROUP_SECTION_PROPERTY) == null) { // NO SECTIONS (this might not be valid test for manually created sections)
rv.add(_gg);
//}
}
}
else
{
Collection<String> groupRefs = a.getGroups();
for (Iterator gIterator = groupRefs.iterator(); gIterator.hasNext();)
{
Group _gg = st.getGroup((String)gIterator.next()); // NO SECTIONS (this might not be valid test for manually created sections)
if (_gg != null) {// && _gg.getProperties().get(GROUP_SECTION_PROPERTY) == null) {
rv.add(_gg);
}
}
}
for (Iterator uIterator = rv.iterator(); uIterator.hasNext();)
{
Group g = (Group) uIterator.next();
AssignmentSubmission uSubmission = getSubmission(aRef, g.getId());
if (uSubmission == null)
{
if (allowGradeSubmission(a.getReference()))
{
if (a.isGroup()) {
// temporarily allow the user to read and write from assignments (asn.revise permission)
SecurityAdvisor securityAdvisor = new MySecurityAdvisor(
SessionManager.getCurrentSessionUserId(),
new ArrayList<String>(Arrays.asList(SECURE_ADD_ASSIGNMENT_SUBMISSION, SECURE_UPDATE_ASSIGNMENT_SUBMISSION)),
""/* no submission id yet, pass the empty string to advisor*/);
try {
securityService.pushAdvisor(securityAdvisor);
M_log.debug(this + " getSubmitterGroupList context " + contextString + " for assignment " + a.getId() + " for group " + g.getId());
AssignmentSubmissionEdit s =
addSubmission(contextString, a.getId(), g.getId());
s.setSubmitted(false);
s.setAssignment(a);
// set the resubmission properties
// get the assignment setting for resubmitting
ResourceProperties assignmentProperties = a.getProperties();
String assignmentAllowResubmitNumber = assignmentProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
if (assignmentAllowResubmitNumber != null)
{
s.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, assignmentAllowResubmitNumber);
String assignmentAllowResubmitCloseDate = assignmentProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
// if assignment's setting of resubmit close time is null, use assignment close time as the close time for resubmit
s.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, assignmentAllowResubmitCloseDate != null?assignmentAllowResubmitCloseDate:String.valueOf(a.getCloseTime().getTime()));
}
commitEdit(s);
// clear the permission
} finally {
securityService.popAdvisor(securityAdvisor);
}
}
}
}
}
}
}
catch (IdUnusedException aIdException)
{
M_log.warn(":getSubmitterGroupList: Assignme id not used: " + aRef + " " + aIdException.getMessage());
}
catch (PermissionException aPerException)
{
M_log.warn(":getSubmitterGroupList: Not allowed to get assignment " + aRef + " " + aPerException.getMessage());
}
return rv;
}
/**
* {@inheritDoc}}
*/
public List<String> getSubmitterIdList(String searchFilterOnly, String allOrOneGroup, String searchString, String aRef, String contextString) {
List<String> rv = new ArrayList<String>();
List<User> rvUsers = new ArrayList<User>();
allOrOneGroup = StringUtils.trimToNull(allOrOneGroup);
searchString = StringUtils.trimToNull(searchString);
boolean bSearchFilterOnly = "true".equalsIgnoreCase(searchFilterOnly);
try
{
Assignment a = getAssignment(aRef);
if (a != null)
{
if (bSearchFilterOnly)
{
if (allOrOneGroup == null && searchString == null)
{
// if the option is set to "Only show user submissions according to Group Filter and Search result"
// if no group filter and no search string is specified, no user will be shown first by default;
return rv;
}
else
{
List allowAddSubmissionUsers = allowAddSubmissionUsers(aRef);
if (allOrOneGroup == null && searchString != null)
{
// search is done for all submitters
rvUsers = getSearchedUsers(searchString, allowAddSubmissionUsers, false);
}
else
{
// group filter first
rvUsers = getSelectedGroupUsers(allOrOneGroup, contextString, a, allowAddSubmissionUsers);
if (searchString != null)
{
// then search
rvUsers = getSearchedUsers(searchString, rvUsers, true);
}
}
}
}
else
{
List allowAddSubmissionUsers = allowAddSubmissionUsers(aRef);
List allowAddAssignmentUsers = allowAddAssignmentUsers(contextString);
// SAK-25555 need to take away those users who can add assignment
allowAddSubmissionUsers.removeAll(allowAddAssignmentUsers);
// Step 1: get group if any that is selected
rvUsers = getSelectedGroupUsers(allOrOneGroup, contextString, a, allowAddSubmissionUsers);
// Step 2: get all student that meets the search criteria based on previous group users. If search is null or empty string, return all users.
rvUsers = getSearchedUsers(searchString, rvUsers, true);
}
if (!rvUsers.isEmpty())
{
List<String> groupRefs = new ArrayList<String>();
for (Iterator uIterator = rvUsers.iterator(); uIterator.hasNext();)
{
User u = (User) uIterator.next();
AssignmentSubmission uSubmission = getSubmission(aRef, u);
if (uSubmission != null)
{
rv.add(u.getId());
}
// add those users who haven't made any submissions and with submission rights
else
{
//only initiate the group list once
if (groupRefs.isEmpty())
{
if (a.getAccess() == Assignment.AssignmentAccess.SITE)
{
// for site range assignment, add the site reference first
groupRefs.add(SiteService.siteReference(contextString));
}
// add all groups inside the site
Collection groups = getGroupsAllowGradeAssignment(contextString, a.getReference());
for(Object g : groups)
{
if (g instanceof Group)
{
groupRefs.add(((Group) g).getReference());
}
}
}
// construct fake submissions for grading purpose if the user has right for grading
if (allowGradeSubmission(a.getReference()))
{
SecurityAdvisor securityAdvisor = new MySecurityAdvisor(
SessionManager.getCurrentSessionUserId(),
new ArrayList<String>(Arrays.asList(SECURE_ADD_ASSIGNMENT_SUBMISSION, SECURE_UPDATE_ASSIGNMENT_SUBMISSION)),
groupRefs/* no submission id yet, pass the empty string to advisor*/);
try
{
// temporarily allow the user to read and write from assignments (asn.revise permission)
securityService.pushAdvisor(securityAdvisor);
AssignmentSubmissionEdit s = addSubmission(contextString, a.getId(), u.getId());
if (s != null)
{
s.setSubmitted(false);
s.setAssignment(a);
// set the resubmission properties
// get the assignment setting for resubmitting
ResourceProperties assignmentProperties = a.getProperties();
String assignmentAllowResubmitNumber = assignmentProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
if (assignmentAllowResubmitNumber != null)
{
s.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, assignmentAllowResubmitNumber);
String assignmentAllowResubmitCloseDate = assignmentProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
// if assignment's setting of resubmit close time is null, use assignment close time as the close time for resubmit
s.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, assignmentAllowResubmitCloseDate != null?assignmentAllowResubmitCloseDate:String.valueOf(a.getCloseTime().getTime()));
}
commitEdit(s);
rv.add(u.getId());
}
}
finally
{
// clear the permission
securityService.popAdvisor(securityAdvisor);
}
}
}
}
}
}
}
catch (IdUnusedException aIdException)
{
M_log.warn(":getSubmitterIdList: Assignme id not used: " + aRef + " " + aIdException.getMessage());
}
catch (PermissionException aPerException)
{
M_log.warn(":getSubmitterIdList: Not allowed to get assignment " + aRef + " " + aPerException.getMessage());
}
return rv;
}
private List<User> getSelectedGroupUsers(String allOrOneGroup, String contextString, Assignment a, List allowAddSubmissionUsers) {
Collection groups = new ArrayList();
List<User> selectedGroupUsers = new ArrayList<User>();
if (allOrOneGroup != null && allOrOneGroup.length() > 0)
{
// now are we view all sections/groups or just specific one?
if (allOrOneGroup.equals(AssignmentConstants.ALL))
{
if (allowAllGroups(contextString))
{
// site range
try {
groups.add(SiteService.getSite(contextString));
} catch (IdUnusedException e) {
M_log.warn(":getSelectedGroupUsers cannot find site " + " " + contextString + e.getMessage());
}
}
else
{
// get all those groups that user is allowed to grade
groups = getGroupsAllowGradeAssignment(contextString, a.getReference());
}
}
else
{
// filter out only those submissions from the selected-group members
try
{
Group group = SiteService.getSite(contextString).getGroup(allOrOneGroup);
groups.add(group);
}
catch (Exception e)
{
M_log.warn(":getSelectedGroupUsers " + e.getMessage() + " groupId=" + allOrOneGroup);
}
}
for (Iterator iGroup=groups.iterator(); iGroup.hasNext();)
{
Object nGroup = iGroup.next();
String authzGroupRef = (nGroup instanceof Group)? ((Group) nGroup).getReference():((nGroup instanceof Site))?((Site) nGroup).getReference():null;
if (authzGroupRef != null)
{
try
{
AuthzGroup group = AuthzGroupService.getAuthzGroup(authzGroupRef);
Set grants = group.getUsers();
for (Iterator iUserIds = grants.iterator(); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
// don't show user multiple times
try
{
User u = UserDirectoryService.getUser(userId);
if (u != null && allowAddSubmissionUsers.contains(u))
{
if (!selectedGroupUsers.contains(u))
{
selectedGroupUsers.add(u);
}
}
}
catch (UserNotDefinedException uException)
{
M_log.warn(":getSelectedGroupUsers " + uException.getMessage() + " userId =" + userId);
}
}
}
catch (GroupNotDefinedException gException)
{
M_log.warn(":getSelectedGroupUsers " + gException.getMessage() + " authGroupId=" + authzGroupRef);
}
}
}
}
return selectedGroupUsers;
}
/**
* keep the users that match search string in sortname, eid, email field
* @param searchString
* @param userList
* @param retain If true, the original list will be kept if there is no search string specified
* @return
*/
private List getSearchedUsers(String searchString, List userList, boolean retain) {
List rv = new ArrayList();
if (searchString != null && searchString.length() > 0)
{
searchString = searchString.toLowerCase();
for(Iterator iUserList = userList.iterator(); iUserList.hasNext();)
{
User u = (User) iUserList.next();
// search on user sortname, eid, email
String[] fields = {u.getSortName(), u.getEid(), u.getEmail()};
List<String> l = new ArrayList(Arrays.asList(fields));
for (String s : l)
{
s = s.toLowerCase();
if (s != null && s.indexOf(searchString) != -1)
{
rv.add(u);
break;
}
}
}
}
else if (retain)
{
// retain the original list
rv = userList;
}
return rv;
}
/**
* {@inheritDoc}
*/
public void getSubmissionsZip(OutputStream outputStream, String ref) throws IdUnusedException, PermissionException
{
M_log.debug(this + ": getSubmissionsZip reference=" + ref);
getSubmissionsZip(outputStream, ref, null);
}
/**
* depends on the query string from ui, determine what to include inside the submission zip
* @param outputStream
* @param ref
* @param queryString
* @throws IdUnusedException
* @throws PermissionException
*/
protected void getSubmissionsZip(OutputStream out, String ref, String queryString) throws IdUnusedException, PermissionException
{
M_log.debug(this + ": getSubmissionsZip 2 reference=" + ref);
boolean withStudentSubmissionText = false;
boolean withStudentSubmissionAttachment = false;
boolean withGradeFile = false;
boolean withFeedbackText = false;
boolean withFeedbackComment = false;
boolean withFeedbackAttachment = false;
boolean withoutFolders = false;
String viewString = "";
String contextString = "";
String searchString = "";
String searchFilterOnly = "";
if (queryString != null)
{
StringTokenizer queryTokens = new StringTokenizer(queryString, "&");
// Parsing the range list
while (queryTokens.hasMoreTokens()) {
String token = queryTokens.nextToken().trim();
// check against the content elements selection
if (token.contains("studentSubmissionText"))
{
// should contain student submission text information
withStudentSubmissionText = true;
}
else if (token.contains("studentSubmissionAttachment"))
{
// should contain student submission attachment information
withStudentSubmissionAttachment = true;
}
else if (token.contains("gradeFile"))
{
// should contain grade file
withGradeFile = true;
}
else if (token.contains("feedbackTexts"))
{
// inline text
withFeedbackText = true;
}
else if (token.contains("feedbackComments"))
{
// comments should be available
withFeedbackComment = true;
}
else if (token.contains("feedbackAttachments"))
{
// feedback attachment
withFeedbackAttachment = true;
}
else if (token.contains("withoutFolders"))
{
// feedback attachment
withoutFolders = true;
}
else if (token.contains("contextString"))
{
// context
contextString = token.indexOf("=") != -1 ? token.substring(token.indexOf("=") + 1) : "";
}
else if (token.contains("viewString"))
{
// view
viewString = token.indexOf("=") != -1 ? token.substring(token.indexOf("=") + 1) : "";
}
else if (token.contains("searchString"))
{
// search
searchString = token.indexOf("=") != -1 ? token.substring(token.indexOf("=") + 1) : "";
}
else if (token.contains("searchFilterOnly"))
{
// search and group filter only
searchFilterOnly = token.indexOf("=") != -1 ? token.substring(token.indexOf("=") + 1) : "";
}
}
}
byte[] rv = null;
try
{
String aRef = assignmentReferenceFromSubmissionsZipReference(ref);
Assignment a = getAssignment(aRef);
if (a.isGroup()) {
Collection<Group> submitterGroups = getSubmitterGroupList(searchFilterOnly, viewString.length() == 0 ? AssignmentConstants.ALL:viewString, searchString, aRef, contextString == null ? a.getContext(): contextString);
if (submitterGroups != null && !submitterGroups.isEmpty())
{
List<GroupSubmission> submissions = new ArrayList<GroupSubmission>();
for (Iterator<Group> iSubmitterGroupsIterator = submitterGroups.iterator(); iSubmitterGroupsIterator.hasNext();)
{
Group g = iSubmitterGroupsIterator.next();
M_log.debug(this + " ZIP GROUP " + g.getTitle() );
AssignmentSubmission sub = getSubmission(aRef, g.getId());
M_log.debug(this + " ZIP GROUP " + g.getTitle() + " SUB " + (sub == null ? "null": sub.getId() ));
if (g != null) {
GroupSubmission gs = new GroupSubmission(g, sub);
submissions.add(gs);
}
}
StringBuilder exceptionMessage = new StringBuilder();
if (allowGradeSubmission(aRef))
{
zipGroupSubmissions(aRef, a.getTitle(), a.getContent().getTypeOfGradeString(a.getContent().getTypeOfGrade()), a.getContent().getTypeOfSubmission(),
new SortedIterator(submissions.iterator(), new AssignmentComparator("submitterName", "true")), out, exceptionMessage, withStudentSubmissionText, withStudentSubmissionAttachment, withGradeFile, withFeedbackText, withFeedbackComment, withFeedbackAttachment);
if (exceptionMessage.length() > 0)
{
// log any error messages
M_log.warn(" getSubmissionsZip ref=" + ref + exceptionMessage.toString());
}
}
}
}
else
{
List<String> submitterIds = getSubmitterIdList(searchFilterOnly, viewString.length() == 0 ? AssignmentConstants.ALL:viewString, searchString, aRef, contextString == null? a.getContext():contextString);
if (submitterIds != null && !submitterIds.isEmpty())
{
List<AssignmentSubmission> submissions = new ArrayList<AssignmentSubmission>();
for (Iterator<String> iSubmitterIdsIterator = submitterIds.iterator(); iSubmitterIdsIterator.hasNext();)
{
String uId = iSubmitterIdsIterator.next();
try
{
User u = UserDirectoryService.getUser(uId);
AssignmentSubmission sub = getSubmission(aRef, u);
if (sub != null)
submissions.add(sub);
}
catch (UserNotDefinedException e)
{
M_log.warn(":getSubmissionsZip cannot find user id=" + uId + e.getMessage() + "");
}
}
StringBuilder exceptionMessage = new StringBuilder();
if (allowGradeSubmission(aRef))
{
zipSubmissions(aRef, a.getTitle(), a.getContent().getTypeOfGradeString(a.getContent().getTypeOfGrade()), a.getContent().getTypeOfSubmission(),
new SortedIterator(submissions.iterator(), new AssignmentComparator("submitterName", "true")), out, exceptionMessage, withStudentSubmissionText, withStudentSubmissionAttachment, withGradeFile, withFeedbackText, withFeedbackComment, withFeedbackAttachment, withoutFolders);
if (exceptionMessage.length() > 0)
{
// log any error messages
M_log.warn(" getSubmissionsZip ref=" + ref + exceptionMessage.toString());
}
}
}
}
}
catch (IdUnusedException e)
{
M_log.debug(this + "getSubmissionsZip -IdUnusedException Unable to get assignment " + ref);
throw new IdUnusedException(ref);
}
catch (PermissionException e)
{
M_log.warn(" getSubmissionsZip -PermissionException Not permitted to get assignment " + ref);
throw new PermissionException(SessionManager.getCurrentSessionUserId(), SECURE_ACCESS_ASSIGNMENT, ref);
}
} // getSubmissionsZip
public String escapeInvalidCharsEntry(String accentedString) {
String decomposed = Normalizer.normalize(accentedString, Normalizer.Form.NFD);
String cleanString = decomposed.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
return cleanString;
}
protected void zipGroupSubmissions(String assignmentReference, String assignmentTitle, String gradeTypeString, int typeOfSubmission, Iterator submissions, OutputStream outputStream, StringBuilder exceptionMessage, boolean withStudentSubmissionText, boolean withStudentSubmissionAttachment, boolean withGradeFile, boolean withFeedbackText, boolean withFeedbackComment, boolean withFeedbackAttachment)
{
ZipOutputStream out = null;
try {
out = new ZipOutputStream(outputStream);
// create the folder structure - named after the assignment's title
String root = Validator.escapeZipEntry(assignmentTitle) + Entity.SEPARATOR;
String submittedText = "";
if (!submissions.hasNext())
{
exceptionMessage.append("There is no submission yet. ");
}
// the buffer used to store grade information
StringBuilder gradesBuffer = new StringBuilder(assignmentTitle + "," + gradeTypeString + "\n\n");
gradesBuffer.append("Group" + "," + rb.getString("grades.eid") + "," + "Users" + "," + rb.getString("grades.grade") + "\n");
// allow add assignment members
List allowAddSubmissionUsers = allowAddSubmissionUsers(assignmentReference);
// Create the ZIP file
String submittersName = "";
int count = 1;
String caughtException = null;
while (submissions.hasNext())
{
GroupSubmission gs = (GroupSubmission) submissions.next();
AssignmentSubmission s = gs.getSubmission();
M_log.debug( this + " ZIPGROUP " + ( s == null ? "null": s.getId() ));
if (s.getSubmitted())
{
try
{
count = 1;
submittersName = root;
User[] submitters = s.getSubmitters();
String submitterString = gs.getGroup().getTitle() + " (" + gs.getGroup().getId() + ")";
String submittersString = "";
String submitters2String = "";
for (int i = 0; i < submitters.length; i++)
{
if (i > 0)
{
submittersString = submittersString.concat("; ");
submitters2String = submitters2String.concat("; ");
}
String fullName = submitters[i].getSortName();
// in case the user doesn't have first name or last name
if (fullName.indexOf(",") == -1)
{
fullName=fullName.concat(",");
}
submittersString = submittersString.concat(fullName);
submitters2String = submitters2String.concat(submitters[i].getDisplayName());
// add the eid to the end of it to guarantee folder name uniqness
submittersString = submittersString + "(" + submitters[i].getEid() + ")";
}
gradesBuffer.append( gs.getGroup().getTitle() + "," + gs.getGroup().getId() + "," + submitters2String + "," + s.getGradeDisplay() + "\n");
if (StringUtil.trimToNull(submitterString) != null)
{
submittersName = submittersName.concat(StringUtil.trimToNull(submitterString));
submittedText = s.getSubmittedText();
submittersName = submittersName.concat("/");
// record submission timestamp
if (s.getSubmitted() && s.getTimeSubmitted() != null)
{
ZipEntry textEntry = new ZipEntry(submittersName + "timestamp.txt");
out.putNextEntry(textEntry);
byte[] b = (s.getTimeSubmitted().toString()).getBytes();
out.write(b);
textEntry.setSize(b.length);
out.closeEntry();
}
// create the folder structure - named after the submitter's name
if (typeOfSubmission != Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION && typeOfSubmission != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
// include student submission text
if (withStudentSubmissionText)
{
// create the text file only when a text submission is allowed
ZipEntry textEntry = new ZipEntry(submittersName + submitterString + "_submissionText" + ZIP_SUBMITTED_TEXT_FILE_TYPE);
out.putNextEntry(textEntry);
byte[] text = submittedText.getBytes();
out.write(text);
textEntry.setSize(text.length);
out.closeEntry();
}
// include student submission feedback text
if (withFeedbackText)
{
// create a feedbackText file into zip
ZipEntry fTextEntry = new ZipEntry(submittersName + "feedbackText.html");
out.putNextEntry(fTextEntry);
byte[] fText = s.getFeedbackText().getBytes();
out.write(fText);
fTextEntry.setSize(fText.length);
out.closeEntry();
}
}
if (typeOfSubmission != Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION && typeOfSubmission != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
// include student submission attachment
if (withStudentSubmissionAttachment)
{
// create a attachment folder for the submission attachments
String sSubAttachmentFolder = submittersName + rb.getString("stuviewsubm.submissatt") + "/";
ZipEntry sSubAttachmentFolderEntry = new ZipEntry(sSubAttachmentFolder);
out.putNextEntry(sSubAttachmentFolderEntry);
// add all submission attachment into the submission attachment folder
zipAttachments(out, submittersName, sSubAttachmentFolder, s.getSubmittedAttachments());
out.closeEntry();
}
}
if (withFeedbackComment)
{
// the comments.txt file to show instructor's comments
ZipEntry textEntry = new ZipEntry(submittersName + "comments" + ZIP_COMMENT_FILE_TYPE);
out.putNextEntry(textEntry);
byte[] b = FormattedText.encodeUnicode(s.getFeedbackComment()).getBytes();
out.write(b);
textEntry.setSize(b.length);
out.closeEntry();
}
if (withFeedbackAttachment)
{
// create an attachment folder for the feedback attachments
String feedbackSubAttachmentFolder = submittersName + rb.getString("download.feedback.attachment") + "/";
ZipEntry feedbackSubAttachmentFolderEntry = new ZipEntry(feedbackSubAttachmentFolder);
out.putNextEntry(feedbackSubAttachmentFolderEntry);
// add all feedback attachment folder
zipAttachments(out, submittersName, feedbackSubAttachmentFolder, s.getFeedbackAttachments());
out.closeEntry();
}
if (submittersString.trim().length() > 0) {
// the comments.txt file to show instructor's comments
ZipEntry textEntry = new ZipEntry(submittersName + "members" + ZIP_COMMENT_FILE_TYPE);
out.putNextEntry(textEntry);
byte[] b = FormattedText.encodeUnicode(submittersString).getBytes();
out.write(b);
textEntry.setSize(b.length);
out.closeEntry();
}
} // if
}
catch (Exception e)
{
caughtException = e.toString();
break;
}
} // if the user is still in site
} // while -- there is submission
if (caughtException == null)
{
// continue
if (withGradeFile)
{
// create a grades.csv file into zip
ZipEntry gradesCSVEntry = new ZipEntry(root + "grades.csv");
out.putNextEntry(gradesCSVEntry);
byte[] grades = gradesBuffer.toString().getBytes();
out.write(grades);
gradesCSVEntry.setSize(grades.length);
out.closeEntry();
}
}
else
{
// log the error
exceptionMessage.append(" Exception " + caughtException + " for creating submission zip file for assignment " + "\"" + assignmentTitle + "\"\n");
}
}
catch (IOException e)
{
exceptionMessage.append("IOException for creating submission zip file for assignment " + "\"" + assignmentTitle + "\" exception: " + e + "\n");
} finally {
// Complete the ZIP file
if (out != null) {
try {
out.finish();
out.flush();
} catch (IOException e) {
// tried
}
try {
out.close();
} catch (IOException e) {
// tried
}
}
}
}
protected void zipSubmissions(String assignmentReference, String assignmentTitle, String gradeTypeString, int typeOfSubmission, Iterator submissions, OutputStream outputStream, StringBuilder exceptionMessage, boolean withStudentSubmissionText, boolean withStudentSubmissionAttachment, boolean withGradeFile, boolean withFeedbackText, boolean withFeedbackComment, boolean withFeedbackAttachment, boolean withoutFolders)
{
ZipOutputStream out = null;
try {
out = new ZipOutputStream(outputStream);
// create the folder structure - named after the assignment's title
String root = escapeInvalidCharsEntry(Validator.escapeZipEntry(assignmentTitle)) + Entity.SEPARATOR;
String submittedText = "";
if (!submissions.hasNext())
{
exceptionMessage.append("There is no submission yet. ");
}
// the buffer used to store grade information
ByteArrayOutputStream gradesBAOS = new ByteArrayOutputStream();
CSVWriter gradesBuffer = new CSVWriter(new OutputStreamWriter(gradesBAOS));
String [] values = {assignmentTitle,gradeTypeString};
gradesBuffer.writeNext(values);
//Blank line was in original gradefile
values = new String[] {""};
gradesBuffer.writeNext(values);
values = new String[] {rb.getString("grades.id"),rb.getString("grades.eid"),rb.getString("grades.lastname"),rb.getString("grades.firstname"),rb.getString("grades.grade")};
gradesBuffer.writeNext(values);
// allow add assignment members
List allowAddSubmissionUsers = allowAddSubmissionUsers(assignmentReference);
// Create the ZIP file
String submittersName = "";
int count = 1;
String caughtException = null;
while (submissions.hasNext())
{
AssignmentSubmission s = (AssignmentSubmission) submissions.next();
if (s.getSubmitted())
{
// get the submission user id and see if the user is still in site
String userId = s.getSubmitterId();
try
{
User u = UserDirectoryService.getUser(userId);
if (allowAddSubmissionUsers.contains(u))
{
count = 1;
submittersName = root;
User[] submitters = s.getSubmitters();
String submittersString = "";
for (int i = 0; i < submitters.length; i++)
{
if (i > 0)
{
submittersString = submittersString.concat("; ");
}
String fullName = submitters[i].getSortName();
// in case the user doesn't have first name or last name
if (fullName.indexOf(",") == -1)
{
fullName=fullName.concat(",");
}
submittersString = submittersString.concat(fullName);
// add the eid to the end of it to guarantee folder name uniqness
// if user Eid contains non ascii characters, the user internal id will be used
String userEid = submitters[i].getEid();
String candidateEid = escapeInvalidCharsEntry(userEid);
if (candidateEid.equals(userEid)){
submittersString = submittersString + "(" + candidateEid + ")";
} else{
submittersString = submittersString + "(" + submitters[i].getId() + ")";
}
submittersString = escapeInvalidCharsEntry(submittersString);
// in grades file, Eid is used
values = new String [] {submitters[i].getDisplayId(), submitters[i].getEid(), submitters[i].getLastName(), submitters[i].getFirstName(), s.getGradeDisplay()};
gradesBuffer.writeNext(values);
}
if (StringUtils.trimToNull(submittersString) != null)
{
submittersName = submittersName.concat(StringUtils.trimToNull(submittersString));
submittedText = s.getSubmittedText();
if (!withoutFolders)
{
submittersName = submittersName.concat("/");
}
else
{
submittersName = submittersName.concat("_");
}
// record submission timestamp
if (!withoutFolders)
{
if (s.getSubmitted() && s.getTimeSubmitted() != null)
{
ZipEntry textEntry = new ZipEntry(submittersName + "timestamp.txt");
out.putNextEntry(textEntry);
byte[] b = (s.getTimeSubmitted().toString()).getBytes();
out.write(b);
textEntry.setSize(b.length);
out.closeEntry();
}
}
// create the folder structure - named after the submitter's name
if (typeOfSubmission != Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION && typeOfSubmission != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
// include student submission text
if (withStudentSubmissionText)
{
// create the text file only when a text submission is allowed
String submittersNameString = submittersName + submittersString;
//remove folder name if Download All is without user folders
if (withoutFolders)
{
submittersNameString = submittersName;
}
ZipEntry textEntry = new ZipEntry(submittersNameString + "_submissionText" + ZIP_SUBMITTED_TEXT_FILE_TYPE);
out.putNextEntry(textEntry);
byte[] text = submittedText.getBytes();
out.write(text);
textEntry.setSize(text.length);
out.closeEntry();
}
// include student submission feedback text
if (withFeedbackText)
{
// create a feedbackText file into zip
ZipEntry fTextEntry = new ZipEntry(submittersName + "feedbackText.html");
out.putNextEntry(fTextEntry);
byte[] fText = s.getFeedbackText().getBytes();
out.write(fText);
fTextEntry.setSize(fText.length);
out.closeEntry();
}
}
if (typeOfSubmission != Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION && typeOfSubmission != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
// include student submission attachment
if (withStudentSubmissionAttachment)
{
//remove "/" that creates a folder if Download All is without user folders
String sSubAttachmentFolder = submittersName + rb.getString("stuviewsubm.submissatt");//jh + "/";
if (!withoutFolders)
{
// create a attachment folder for the submission attachments
sSubAttachmentFolder = submittersName + rb.getString("stuviewsubm.submissatt") + "/";
sSubAttachmentFolder = escapeInvalidCharsEntry(sSubAttachmentFolder);
ZipEntry sSubAttachmentFolderEntry = new ZipEntry(sSubAttachmentFolder);
out.putNextEntry(sSubAttachmentFolderEntry);
}
else
{
sSubAttachmentFolder = sSubAttachmentFolder + "_";
//submittersName = submittersName.concat("_");
}
// add all submission attachment into the submission attachment folder
zipAttachments(out, submittersName, sSubAttachmentFolder, s.getSubmittedAttachments());
out.closeEntry();
}
}
if (withFeedbackComment)
{
// the comments.txt file to show instructor's comments
ZipEntry textEntry = new ZipEntry(submittersName + "comments" + ZIP_COMMENT_FILE_TYPE);
out.putNextEntry(textEntry);
byte[] b = FormattedText.encodeUnicode(s.getFeedbackComment()).getBytes();
out.write(b);
textEntry.setSize(b.length);
out.closeEntry();
}
if (withFeedbackAttachment)
{
// create an attachment folder for the feedback attachments
String feedbackSubAttachmentFolder = submittersName + rb.getString("download.feedback.attachment");
if (!withoutFolders)
{
feedbackSubAttachmentFolder = feedbackSubAttachmentFolder + "/";
ZipEntry feedbackSubAttachmentFolderEntry = new ZipEntry(feedbackSubAttachmentFolder);
out.putNextEntry(feedbackSubAttachmentFolderEntry);
}
else
{
submittersName = submittersName.concat("_");
}
// add all feedback attachment folder
zipAttachments(out, submittersName, feedbackSubAttachmentFolder, s.getFeedbackAttachments());
out.closeEntry();
}
} // if
}
}
catch (Exception e)
{
caughtException = e.toString();
break;
}
} // if the user is still in site
} // while -- there is submission
if (caughtException == null)
{
// continue
if (withGradeFile)
{
// create a grades.csv file into zip
ZipEntry gradesCSVEntry = new ZipEntry(root + "grades.csv");
out.putNextEntry(gradesCSVEntry);
gradesBuffer.close();
out.write(gradesBAOS.toByteArray());
gradesCSVEntry.setSize(gradesBAOS.size());
out.closeEntry();
}
}
else
{
// log the error
exceptionMessage.append(" Exception " + caughtException + " for creating submission zip file for assignment " + "\"" + assignmentTitle + "\"\n");
}
}
catch (IOException e)
{
exceptionMessage.append("IOException for creating submission zip file for assignment " + "\"" + assignmentTitle + "\" exception: " + e + "\n");
} finally {
// Complete the ZIP file
if (out != null) {
try {
out.finish();
out.flush();
} catch (IOException e) {
// tried
}
try {
out.close();
} catch (IOException e) {
// tried
}
}
}
}
private void zipAttachments(ZipOutputStream out, String submittersName, String sSubAttachmentFolder, List attachments) {
int attachedUrlCount = 0;
InputStream content = null;
HashMap<String, Integer> done = new HashMap<String, Integer> ();
for (int j = 0; j < attachments.size(); j++)
{
Reference r = (Reference) attachments.get(j);
try
{
ContentResource resource = m_contentHostingService.getResource(r.getId());
String contentType = resource.getContentType();
ResourceProperties props = r.getProperties();
String displayName = props.getPropertyFormatted(props.getNamePropDisplayName());
displayName = escapeInvalidCharsEntry(displayName);
// for URL content type, encode a redirect to the body URL
if (contentType.equalsIgnoreCase(ResourceProperties.TYPE_URL))
{
displayName = "attached_URL_" + attachedUrlCount;
attachedUrlCount++;
}
// buffered stream input
content = resource.streamContent();
byte data[] = new byte[1024 * 10];
BufferedInputStream bContent = null;
try
{
bContent = new BufferedInputStream(content, data.length);
String candidateName = sSubAttachmentFolder + displayName;
String realName = null;
Integer already = done.get(candidateName);
if (already == null) {
realName = candidateName;
done.put(candidateName, 1);
} else {
realName = candidateName + "+" + already;
done.put(candidateName, already + 1);
}
ZipEntry attachmentEntry = new ZipEntry(realName);
out.putNextEntry(attachmentEntry);
int bCount = -1;
while ((bCount = bContent.read(data, 0, data.length)) != -1)
{
out.write(data, 0, bCount);
}
try
{
out.closeEntry(); // The zip entry need to be closed
}
catch (IOException ioException)
{
M_log.warn(":zipAttachments: problem closing zip entry " + ioException);
}
}
catch (IllegalArgumentException iException)
{
M_log.warn(":zipAttachments: problem creating BufferedInputStream with content and length " + data.length + iException);
}
finally
{
if (bContent != null)
{
try
{
bContent.close(); // The BufferedInputStream needs to be closed
}
catch (IOException ioException)
{
M_log.warn(":zipAttachments: problem closing FileChannel " + ioException);
}
}
}
}
catch (PermissionException e)
{
M_log.warn(" zipAttachments--PermissionException submittersName="
+ submittersName + " attachment reference=" + r);
}
catch (IdUnusedException e)
{
M_log.warn(" zipAttachments--IdUnusedException submittersName="
+ submittersName + " attachment reference=" + r);
}
catch (TypeException e)
{
M_log.warn(" zipAttachments--TypeException: submittersName="
+ submittersName + " attachment reference=" + r);
}
catch (IOException e)
{
M_log.warn(" zipAttachments--IOException: Problem in creating the attachment file: submittersName="
+ submittersName + " attachment reference=" + r + " error " + e);
}
catch (ServerOverloadException e)
{
M_log.warn(" zipAttachments--ServerOverloadException: submittersName="
+ submittersName + " attachment reference=" + r);
}
finally
{
if (content != null)
{
try
{
content.close(); // The input stream needs to be closed
}
catch (IOException ioException)
{
M_log.warn(":zipAttachments: problem closing Inputstream content " + ioException);
}
}
}
} // for
}
/**
* Get the string to form an assignment grade spreadsheet
*
* @param context
* The assignment context String
* @param assignmentId
* The id for the assignment object; when null, indicates all assignment in that context
*/
public String gradesSpreadsheetReference(String context, String assignmentId)
{
// based on all assignment in that context
String s = REFERENCE_ROOT + Entity.SEPARATOR + REF_TYPE_GRADES + Entity.SEPARATOR + context;
if (assignmentId != null)
{
// based on the specified assignment only
s = s.concat(Entity.SEPARATOR + assignmentId);
}
return s;
} // gradesSpreadsheetReference
/**
* Get the string to form an assignment submissions zip file
*
* @param context
* The assignment context String
* @param assignmentReference
* The reference for the assignment object;
*/
public String submissionsZipReference(String context, String assignmentReference)
{
// based on the specified assignment
return REFERENCE_ROOT + Entity.SEPARATOR + REF_TYPE_SUBMISSIONS + Entity.SEPARATOR + context + Entity.SEPARATOR
+ assignmentReference;
} // submissionsZipReference
/**
* Decode the submissionsZipReference string to get the assignment reference String
*
* @param sReference
* The submissionZipReference String
* @return The assignment reference String
*/
private String assignmentReferenceFromSubmissionsZipReference(String sReference)
{
// remove the String part relating to submissions zip reference
if (sReference.indexOf(Entity.SEPARATOR +"site") == -1)
{
return sReference.substring(sReference.lastIndexOf(Entity.SEPARATOR + "assignment"));
}
else
{
return sReference.substring(sReference.lastIndexOf(Entity.SEPARATOR + "assignment"), sReference.indexOf(Entity.SEPARATOR +"site"));
}
} // assignmentReferenceFromSubmissionsZipReference
/**
* Decode the submissionsZipReference string to get the group reference String
*
* @param sReference
* The submissionZipReference String
* @return The group reference String
*/
private String groupReferenceFromSubmissionsZipReference(String sReference)
{
// remove the String part relating to submissions zip reference
if (sReference.indexOf(Entity.SEPARATOR +"site") != -1)
{
return sReference.substring(sReference.lastIndexOf(Entity.SEPARATOR + "site"));
}
else
{
return null;
}
} // assignmentReferenceFromSubmissionsZipReference
/**********************************************************************************************************************************************************************************************************************************************************
* ResourceService implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* {@inheritDoc}
*/
public String getLabel()
{
return "assignment";
}
/**
* {@inheritDoc}
*/
public boolean willArchiveMerge()
{
return true;
}
/**
* {@inheritDoc}
*/
public HttpAccess getHttpAccess()
{
return new HttpAccess()
{
public void handleAccess(HttpServletRequest req, HttpServletResponse res, Reference ref,
Collection copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException,
EntityAccessOverloadException, EntityCopyrightException
{
if (SessionManager.getCurrentSessionUserId() == null)
{
// fail the request, user not logged in yet.
}
else
{
try
{
if (REF_TYPE_SUBMISSIONS.equals(ref.getSubType()))
{
String queryString = req.getQueryString();
res.setContentType("application/zip");
res.setHeader("Content-Disposition", "attachment; filename = bulk_download.zip");
OutputStream out = null;
try
{
out = res.getOutputStream();
// get the submissions zip blob
getSubmissionsZip(out, ref.getReference(), queryString);
}
catch (Throwable ignore)
{
M_log.error(this + " getHttpAccess handleAccess " + ignore.getMessage() + " ref=" + ref.getReference());
}
finally
{
if (out != null)
{
try
{
out.flush();
out.close();
}
catch (Throwable ignore)
{
M_log.warn(": handleAccess 1 " + ignore.getMessage());
}
}
}
}
else if (REF_TYPE_GRADES.equals(ref.getSubType()))
{
res.setContentType("application/vnd.ms-excel");
res.setHeader("Content-Disposition", "attachment; filename = export_grades_file.xls");
OutputStream out = null;
try
{
out = res.getOutputStream();
getGradesSpreadsheet(out, ref.getReference());
out.flush();
out.close();
}
catch (Throwable ignore)
{
M_log.warn(": handleAccess 2 " + ignore.getMessage());
}
finally
{
if (out != null)
{
try
{
out.close();
}
catch (Throwable ignore)
{
M_log.warn(": handleAccess 3 " + ignore.getMessage());
}
}
}
}
else
{
M_log.warn("handleAccess: throw IdUnusedException " + ref.getReference());
throw new IdUnusedException(ref.getReference());
}
}
catch (Throwable t)
{
M_log.warn(" HandleAccess: caught exception " + t.toString() + " and rethrow it!");
throw new EntityNotDefinedException(ref.getReference());
}
}
}
};
}
/**
* {@inheritDoc}
*/
public boolean parseEntityReference(String reference, Reference ref)
{
if (reference.startsWith(REFERENCE_ROOT))
{
String id = null;
String subType = null;
String container = null;
String context = null;
// Note: StringUtils.split would not produce the following first null part
// Still use StringUtil here.
String[] parts = StringUtil.split(reference, Entity.SEPARATOR);
// we will get null, assignment, [a|c|s|grades|submissions], context, [auid], id
if (parts.length > 2)
{
subType = parts[2];
if (parts.length > 3)
{
// context is the container
context = parts[3];
// submissions have the assignment unique id as a container
if ("s".equals(subType))
{
if (parts.length > 5)
{
container = parts[4];
id = parts[5];
}
}
// others don't
else
{
if (parts.length > 4)
{
id = parts[4];
}
}
}
}
ref.set(APPLICATION_ID, subType, id, container, context);
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
public Entity getEntity(Reference ref)
{
Entity rv = null;
try
{
// is it an AssignmentContent object
if (REF_TYPE_CONTENT.equals(ref.getSubType()))
{
rv = getAssignmentContent(ref.getReference());
}
// is it an Assignment object
else if (REF_TYPE_ASSIGNMENT.equals(ref.getSubType()))
{
rv = getAssignment(ref.getReference());
}
// is it an AssignmentSubmission object
else if (REF_TYPE_SUBMISSION.equals(ref.getSubType()))
{
rv = getSubmission(ref.getReference());
}
else
M_log.warn("getEntity(): unknown message ref subtype: " + ref.getSubType() + " in ref: " + ref.getReference());
}
catch (PermissionException e)
{
M_log.warn("getEntity(): " + e + " ref=" + ref.getReference());
}
catch (IdUnusedException e)
{
M_log.warn("getEntity(): " + e + " ref=" + ref.getReference());
}
catch (NullPointerException e)
{
M_log.warn("getEntity(): " + e + " ref=" + ref.getReference());
}
return rv;
}
/**
* {@inheritDoc}
*/
public Collection getEntityAuthzGroups(Reference ref, String userId)
{
Collection rv = new ArrayList();
// for AssignmentService assignments:
// if access set to SITE, use the assignment and site authzGroups.
// if access set to GROUPED, use the assignment, and the groups, but not the site authzGroups.
// if the user has SECURE_ALL_GROUPS in the context, ignore GROUPED access and treat as if SITE
try
{
// for assignment
if (REF_TYPE_ASSIGNMENT.equals(ref.getSubType()))
{
// assignment
rv.add(ref.getReference());
boolean grouped = false;
Collection groups = null;
// check SECURE_ALL_GROUPS - if not, check if the assignment has groups or not
// TODO: the last param needs to be a ContextService.getRef(ref.getContext())... or a ref.getContextAuthzGroup() -ggolden
if ((userId == null) || ((!securityService.isSuperUser(userId)) && (!securityService.unlock(userId, SECURE_ALL_GROUPS, SiteService.siteReference(ref.getContext())))))
{
// get the channel to get the message to get group information
// TODO: check for efficiency, cache and thread local caching usage -ggolden
if (ref.getId() != null)
{
Assignment a = findAssignment(ref.getReference());
if (a != null)
{
grouped = Assignment.AssignmentAccess.GROUPED == a.getAccess();
groups = a.getGroups();
}
}
}
if (grouped)
{
// groups
rv.addAll(groups);
}
// not grouped
else
{
// site
ref.addSiteContextAuthzGroup(rv);
}
}
else
{
rv.add(ref.getReference());
// for content and submission, use site security setting
ref.addSiteContextAuthzGroup(rv);
}
}
catch (Throwable e)
{
M_log.warn(" getEntityAuthzGroups(): " + e.getMessage() + " ref=" + ref.getReference());
}
return rv;
}
/**
* {@inheritDoc}
*/
public String getEntityUrl(Reference ref)
{
String rv = null;
try
{
// is it an AssignmentContent object
if (REF_TYPE_CONTENT.equals(ref.getSubType()))
{
AssignmentContent c = getAssignmentContent(ref.getReference());
rv = c.getUrl();
}
// is it an Assignment object
else if (REF_TYPE_ASSIGNMENT.equals(ref.getSubType()))
{
Assignment a = getAssignment(ref.getReference());
rv = a.getUrl();
}
// is it an AssignmentSubmission object
else if (REF_TYPE_SUBMISSION.equals(ref.getSubType()))
{
AssignmentSubmission s = getSubmission(ref.getReference());
rv = s.getUrl();
}
else
M_log.warn(" getEntityUrl(): unknown message ref subtype: " + ref.getSubType() + " in ref: " + ref.getReference());
}
catch (PermissionException e)
{
M_log.warn("getEntityUrl(): " + e + " ref=" + ref.getReference());
}
catch (IdUnusedException e)
{
M_log.warn("getEntityUrl(): " + e + " ref=" + ref.getReference());
}
catch (NullPointerException e)
{
M_log.warn("getEntityUrl(): " + e + " ref=" + ref.getReference());
}
return rv;
}
/**
* {@inheritDoc}
*/
public String archive(String siteId, Document doc, Stack stack, String archivePath, List attachments)
{
// prepare the buffer for the results log
StringBuilder results = new StringBuilder();
// String assignRef = assignmentReference(siteId, SiteService.MAIN_CONTAINER);
results.append("archiving " + getLabel() + " context " + Entity.SEPARATOR + siteId + Entity.SEPARATOR
+ SiteService.MAIN_CONTAINER + ".\n");
// start with an element with our very own (service) name
Element element = doc.createElement(AssignmentService.class.getName());
((Element) stack.peek()).appendChild(element);
stack.push(element);
Iterator assignmentsIterator = getAssignmentsForContext(siteId);
while (assignmentsIterator.hasNext())
{
Assignment assignment = (Assignment) assignmentsIterator.next();
// archive this assignment
Element el = assignment.toXml(doc, stack);
element.appendChild(el);
// in order to make the assignment.xml have a better structure
// the content id attribute removed from the assignment node
// the content will be a child of assignment node
el.removeAttribute("assignmentcontent");
// then archive the related content
AssignmentContent content = (AssignmentContent) assignment.getContent();
if (content != null)
{
Element contentEl = content.toXml(doc, stack);
// assignment node has already kept the context info
contentEl.removeAttribute("context");
// collect attachments
List atts = content.getAttachments();
for (int i = 0; i < atts.size(); i++)
{
Reference ref = (Reference) atts.get(i);
// if it's in the attachment area, and not already in the list
if ((ref.getReference().startsWith("/content/attachment/")) && (!attachments.contains(ref)))
{
attachments.add(ref);
}
// in order to make assignment.xml has the consistent format with the other xml files
// move the attachments to be the children of the content, instead of the attributes
String attributeString = "attachment" + i;
String attRelUrl = contentEl.getAttribute(attributeString);
contentEl.removeAttribute(attributeString);
Element attNode = doc.createElement("attachment");
attNode.setAttribute("relative-url", attRelUrl);
contentEl.appendChild(attNode);
} // for
// make the content a childnode of the assignment node
el.appendChild(contentEl);
Iterator submissionsIterator = getSubmissions(assignment).iterator();
while (submissionsIterator.hasNext())
{
AssignmentSubmission submission = (AssignmentSubmission) submissionsIterator.next();
// archive this assignment
Element submissionEl = submission.toXml(doc, stack);
el.appendChild(submissionEl);
}
} // if
} // while
stack.pop();
return results.toString();
} // archive
/**
* Replace the WT user id with the new qualified id
*
* @param el
* The XML element holding the perproties
* @param useIdTrans
* The HashMap to track old WT id to new CTools id
*/
protected void WTUserIdTrans(Element el, Map userIdTrans)
{
NodeList children4 = el.getChildNodes();
int length4 = children4.getLength();
for (int i4 = 0; i4 < length4; i4++)
{
Node child4 = children4.item(i4);
if (child4.getNodeType() == Node.ELEMENT_NODE)
{
Element element4 = (Element) child4;
if (element4.getTagName().equals("property"))
{
String creatorId = "";
String modifierId = "";
if (element4.hasAttribute("CHEF:creator"))
{
if ("BASE64".equalsIgnoreCase(element4.getAttribute("enc")))
{
creatorId = Xml.decodeAttribute(element4, "CHEF:creator");
}
else
{
creatorId = element4.getAttribute("CHEF:creator");
}
String newCreatorId = (String) userIdTrans.get(creatorId);
if (newCreatorId != null)
{
Xml.encodeAttribute(element4, "CHEF:creator", newCreatorId);
element4.setAttribute("enc", "BASE64");
}
}
else if (element4.hasAttribute("CHEF:modifiedby"))
{
if ("BASE64".equalsIgnoreCase(element4.getAttribute("enc")))
{
modifierId = Xml.decodeAttribute(element4, "CHEF:modifiedby");
}
else
{
modifierId = element4.getAttribute("CHEF:modifiedby");
}
String newModifierId = (String) userIdTrans.get(modifierId);
if (newModifierId != null)
{
Xml.encodeAttribute(element4, "CHEF:creator", newModifierId);
element4.setAttribute("enc", "BASE64");
}
}
}
}
}
} // WTUserIdTrans
/**
* {@inheritDoc}
*/
public String merge(String siteId, Element root, String archivePath, String fromSiteId, Map attachmentNames, Map userIdTrans,
Set userListAllowImport)
{
// prepare the buffer for the results log
StringBuilder results = new StringBuilder();
int count = 0;
try
{
// pass the DOM to get new assignment ids, and adjust attachments
NodeList children2 = root.getChildNodes();
int length2 = children2.getLength();
for (int i2 = 0; i2 < length2; i2++)
{
Node child2 = children2.item(i2);
if (child2.getNodeType() == Node.ELEMENT_NODE)
{
Element element2 = (Element) child2;
if (element2.getTagName().equals("assignment"))
{
// a flag showing if continuing merging the assignment
boolean goAhead = true;
AssignmentContentEdit contentEdit = null;
// element2 now - assignment node
// adjust the id of this assignment
// String newId = IdManager.createUuid();
element2.setAttribute("id", IdManager.createUuid());
element2.setAttribute("context", siteId);
// cloneNode(false) - no children cloned
Element el2clone = (Element) element2.cloneNode(false);
// traverse this assignment node first to check if the person who last modified, has the right role.
// if no right role, mark the flag goAhead to be false.
NodeList children3 = element2.getChildNodes();
int length3 = children3.getLength();
for (int i3 = 0; i3 < length3; i3++)
{
Node child3 = children3.item(i3);
if (child3.getNodeType() == Node.ELEMENT_NODE)
{
Element element3 = (Element) child3;
// add the properties childnode to the clone of assignment node
if (element3.getTagName().equals("properties"))
{
NodeList children6 = element3.getChildNodes();
int length6 = children6.getLength();
for (int i6 = 0; i6 < length6; i6++)
{
Node child6 = children6.item(i6);
if (child6.getNodeType() == Node.ELEMENT_NODE)
{
Element element6 = (Element) child6;
if (element6.getTagName().equals("property"))
{
if (element6.getAttribute("name").equalsIgnoreCase("CHEF:modifiedby"))
{
if ("BASE64".equalsIgnoreCase(element6.getAttribute("enc")))
{
String creatorId = Xml.decodeAttribute(element6, "value");
if (!userListAllowImport.contains(creatorId)) goAhead = false;
}
else
{
String creatorId = element6.getAttribute("value");
if (!userListAllowImport.contains(creatorId)) goAhead = false;
}
}
}
}
}
}
}
} // for
// then, go ahead to merge the content and assignment
if (goAhead)
{
for (int i3 = 0; i3 < length3; i3++)
{
Node child3 = children3.item(i3);
if (child3.getNodeType() == Node.ELEMENT_NODE)
{
Element element3 = (Element) child3;
// add the properties childnode to the clone of assignment node
if (element3.getTagName().equals("properties"))
{
// add the properties childnode to the clone of assignment node
el2clone.appendChild(element3.cloneNode(true));
}
else if (element3.getTagName().equals("content"))
{
// element3 now- content node
// adjust the id of this content
String newContentId = IdManager.createUuid();
element3.setAttribute("id", newContentId);
element3.setAttribute("context", siteId);
// clone the content node without the children of <properties>
Element el3clone = (Element) element3.cloneNode(false);
// update the assignmentcontent id in assignment node
String assignContentId = "/assignment/c/" + siteId + "/" + newContentId;
el2clone.setAttribute("assignmentcontent", assignContentId);
// for content node, process the attachment or properties kids
NodeList children5 = element3.getChildNodes();
int length5 = children5.getLength();
int attCount = 0;
for (int i5 = 0; i5 < length5; i5++)
{
Node child5 = children5.item(i5);
if (child5.getNodeType() == Node.ELEMENT_NODE)
{
Element element5 = (Element) child5;
// for the node of "properties"
if (element5.getTagName().equals("properties"))
{
// for the file from WT, preform userId translation when needed
if (!userIdTrans.isEmpty())
{
WTUserIdTrans(element3, userIdTrans);
}
} // for the node of properties
el3clone.appendChild(element5.cloneNode(true));
// for "attachment" children
if (element5.getTagName().equals("attachment"))
{
// map the attachment area folder name
// filter out the invalid characters in the attachment id
// map the attachment area folder name
String oldUrl = element5.getAttribute("relative-url");
if (oldUrl.startsWith("/content/attachment/" + fromSiteId + "/"))
{
String newUrl = "/content/attachment/" + siteId + oldUrl.substring(("/content/attachment" + fromSiteId).length());
element5.setAttribute("relative-url", Validator.escapeQuestionMark(newUrl));
// transfer attachment, replace the context string and add new attachment if necessary
newUrl = transferAttachment(fromSiteId, siteId, null, oldUrl.substring("/content".length()));
element5.setAttribute("relative-url", Validator.escapeQuestionMark(newUrl));
newUrl = (String) attachmentNames.get(oldUrl);
if (newUrl != null)
{
if (newUrl.startsWith("/attachment/"))
newUrl = "/content".concat(newUrl);
element5.setAttribute("relative-url", Validator
.escapeQuestionMark(newUrl));
}
}
// map any references to this site to the new site id
else if (oldUrl.startsWith("/content/group/" + fromSiteId + "/"))
{
String newUrl = "/content/group/" + siteId
+ oldUrl.substring(("/content/group/" + fromSiteId).length());
element5.setAttribute("relative-url", Validator.escapeQuestionMark(newUrl));
}
// put the attachment back to the attribute field of content
// to satisfy the input need of mergeAssignmentContent
String attachmentString = "attachment" + attCount;
el3clone.setAttribute(attachmentString, element5.getAttribute("relative-url"));
attCount++;
} // if
} // if
} // for
// create a newassignment content
contentEdit = mergeAssignmentContent(el3clone);
commitEdit(contentEdit);
}
}
} // for
// when importing, refer to property to determine draft status
if ("false".equalsIgnoreCase(m_serverConfigurationService.getString("import.importAsDraft")))
{
String draftAttribute = el2clone.getAttribute("draft");
if (draftAttribute.equalsIgnoreCase("true") || draftAttribute.equalsIgnoreCase("false"))
el2clone.setAttribute("draft", draftAttribute);
else
el2clone.setAttribute("draft", "true");
}
else
{
el2clone.setAttribute("draft", "true");
}
// merge in this assignment
AssignmentEdit edit = mergeAssignment(el2clone);
edit.setContent(contentEdit);
commitEdit(edit);
count++;
} // if goAhead
} // if
} // if
} // for
}
catch (Exception any)
{
M_log.warn(" merge(): exception: " + any.getMessage() + " siteId=" + siteId + " from site id=" + fromSiteId);
}
results.append("merging assignment " + siteId + " (" + count + ") assignments.\n");
return results.toString();
} // merge
/**
* {@inheritDoc}
*/
public String[] myToolIds()
{
String[] toolIds = { "sakai.assignment", "sakai.assignment.grades" };
return toolIds;
}
/**
* {@inheritDoc}
*/
public void transferCopyEntities(String fromContext, String toContext, List resourceIds){
transferCopyEntitiesRefMigrator(fromContext, toContext, resourceIds);
}
public Map<String, String> transferCopyEntitiesRefMigrator(String fromContext, String toContext, List resourceIds)
{
Map<String, String> transversalMap = new HashMap<String, String>();
// import Assignment objects
Iterator oAssignments = getAssignmentsForContext(fromContext);
while (oAssignments.hasNext())
{
Assignment oAssignment = (Assignment) oAssignments.next();
String oAssignmentId = oAssignment.getId();
boolean toBeImported = true;
if (resourceIds != null && resourceIds.size() > 0)
{
// if there is a list for import assignments, only import those assignments and relative submissions
toBeImported = false;
for (int m = 0; m < resourceIds.size() && !toBeImported; m++)
{
if (((String) resourceIds.get(m)).equals(oAssignmentId))
{
toBeImported = true;
}
}
}
if (toBeImported)
{
AssignmentEdit nAssignment = null;
AssignmentContentEdit nContent = null;
if (!m_assignmentStorage.check(oAssignmentId))
{
}
else
{
try
{
// add new Assignment content
String oContentReference = oAssignment.getContentReference();
String oContentId = contentId(oContentReference);
if (!m_contentStorage.check(oContentId))
throw new IdUnusedException(oContentId);
else
{
AssignmentContent oContent = getAssignmentContent(oContentReference);
nContent = addAssignmentContent(toContext);
// attributes
nContent.setAllowAttachments(oContent.getAllowAttachments());
nContent.setContext(toContext);
nContent.setGroupProject(oContent.getGroupProject());
nContent.setHonorPledge(oContent.getHonorPledge());
nContent.setHideDueDate(oContent.getHideDueDate());
nContent.setIndividuallyGraded(oContent.individuallyGraded());
// replace all occurrence of old context with new context inside instruction text
String instructions = oContent.getInstructions();
if (instructions.indexOf(fromContext) != -1)
{
instructions = instructions.replaceAll(fromContext, toContext);
}
nContent.setInstructions(instructions);
nContent.setMaxGradePoint(oContent.getMaxGradePoint());
nContent.setReleaseGrades(oContent.releaseGrades());
nContent.setTimeLastModified(oContent.getTimeLastModified());
nContent.setTitle(oContent.getTitle());
nContent.setTypeOfGrade(oContent.getTypeOfGrade());
nContent.setTypeOfSubmission(oContent.getTypeOfSubmission());
// review service
nContent.setAllowReviewService(oContent.getAllowReviewService());
// properties
ResourcePropertiesEdit p = nContent.getPropertiesEdit();
p.clear();
p.addAll(oContent.getProperties());
// update live properties
addLiveProperties(p);
// attachment
List oAttachments = oContent.getAttachments();
List nAttachments = m_entityManager.newReferenceList();
for (int n = 0; n < oAttachments.size(); n++)
{
Reference oAttachmentRef = (Reference) oAttachments.get(n);
String oAttachmentId = ((Reference) oAttachments.get(n)).getId();
if (oAttachmentId.indexOf(fromContext) != -1)
{
// transfer attachment, replace the context string and add new attachment if necessary
transferAttachment(fromContext, toContext, nAttachments, oAttachmentId);
}
else
{
nAttachments.add(oAttachmentRef);
}
}
nContent.replaceAttachments(nAttachments);
// complete the edit
m_contentStorage.commit(nContent);
((BaseAssignmentContentEdit) nContent).closeEdit();
}
}
catch (Exception e)
{
if (M_log.isWarnEnabled()) M_log.warn(" transferCopyEntities " + e.toString() + " oAssignmentId=" + oAssignmentId);
}
if (nContent != null)
{
try
{
// add new assignment
nAssignment = addAssignment(toContext);
// attribute
nAssignment.setCloseTime(oAssignment.getCloseTime());
nAssignment.setContentReference(nContent.getReference());
nAssignment.setContext(toContext);
// when importing, refer to property to determine draft status
if ("false".equalsIgnoreCase(m_serverConfigurationService.getString("import.importAsDraft")))
{
nAssignment.setDraft(oAssignment.getDraft());
}
else
{
nAssignment.setDraft(true);
}
nAssignment.setGroup(oAssignment.isGroup());
nAssignment.setDropDeadTime(oAssignment.getDropDeadTime());
nAssignment.setDueTime(oAssignment.getDueTime());
nAssignment.setOpenTime(oAssignment.getOpenTime());
nAssignment.setSection(oAssignment.getSection());
nAssignment.setTitle(oAssignment.getTitle());
nAssignment.setPosition_order(oAssignment.getPosition_order());
// properties
ResourcePropertiesEdit p = nAssignment.getPropertiesEdit();
p.clear();
p.addAll(oAssignment.getProperties());
// one more touch on the gradebook-integration link
String associatedGradebookAssignment = StringUtils.trimToNull(p.getProperty(PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
if (associatedGradebookAssignment != null) {
// see if the old assignment's associated gradebook item is an internal gradebook entry or externally defined
boolean isExternalAssignmentDefined = m_gradebookExternalAssessmentService.isExternalAssignmentDefined(oAssignment.getContent().getContext(), associatedGradebookAssignment);
if (isExternalAssignmentDefined)
{
// if this is an external defined (came from assignment)
// mark the link as "add to gradebook" for the new imported assignment, since the assignment is still of draft state
//later when user posts the assignment, the corresponding assignment will be created in gradebook.
p.removeProperty(PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
p.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, GRADEBOOK_INTEGRATION_ADD);
}
}
// remove the link btw assignment and announcement item. One can announce the open date afterwards
p.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE);
p.removeProperty("new_assignment_open_date_announced");
p.removeProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID);
// remove the link btw assignment and calendar item. One can add the due date to calendar afterwards
p.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
p.removeProperty("new_assignment_due_date_scheduled");
p.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
// update live properties
addLiveProperties(p);
// complete the edit
m_assignmentStorage.commit(nAssignment);
((BaseAssignmentEdit) nAssignment).closeEdit();
transversalMap.put("assignment/" + oAssignment.getId(), "assignment/" + nAssignment.getId());
M_log.info("old assignment id:"+oAssignment.getId()+" - new assignment id:"+nAssignment.getId());
try {
if (m_taggingManager.isTaggable()) {
for (TaggingProvider provider : m_taggingManager
.getProviders()) {
provider
.transferCopyTags(
m_assignmentActivityProducer
.getActivity(oAssignment),
m_assignmentActivityProducer
.getActivity(nAssignment));
}
}
} catch (PermissionException pe) {
M_log.error(this + " transferCopyEntities " + pe.toString() + " oAssignmentId=" + oAssignment.getId() + " nAssignmentId=" + nAssignment.getId());
}
}
catch (Exception ee)
{
M_log.error(this + " transferCopyEntities " + ee.toString() + " oAssignmentId=" + oAssignment.getId() + " nAssignmentId=" + nAssignment.getId());
}
}
} // if-else
} // if
} // for
return transversalMap;
} // importResources
/**
* manipulate the transfered attachment
* @param fromContext
* @param toContext
* @param nAttachments
* @param oAttachmentId
* @return the new reference
*/
private String transferAttachment(String fromContext, String toContext,
List nAttachments, String oAttachmentId)
{
String rv = "";
// replace old site id with new site id in attachments
String nAttachmentId = oAttachmentId.replaceAll(fromContext, toContext);
try
{
ContentResource attachment = m_contentHostingService.getResource(nAttachmentId);
if (nAttachments != null)
{
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
rv = attachment.getReference();
}
catch (IdUnusedException e)
{
try
{
ContentResource oAttachment = m_contentHostingService.getResource(oAttachmentId);
try
{
if (m_contentHostingService.isAttachmentResource(nAttachmentId))
{
// add the new resource into attachment collection area
ContentResource attachment = m_contentHostingService.addAttachmentResource(
Validator.escapeResourceName(oAttachment.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME)),
toContext,
ToolManager.getTool("sakai.assignment.grades").getTitle(),
oAttachment.getContentType(),
oAttachment.getContent(),
oAttachment.getProperties());
rv = attachment.getReference();
// add to attachment list
if (nAttachments != null)
{
nAttachments.add(m_entityManager.newReference(rv));
}
}
else
{
// add the new resource into resource area
ContentResource attachment = m_contentHostingService.addResource(
Validator.escapeResourceName(oAttachment.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME)),
toContext,
1,
oAttachment.getContentType(),
oAttachment.getContent(),
oAttachment.getProperties(),
NotificationService.NOTI_NONE);
rv = attachment.getReference();
// add to attachment list
if (nAttachments != null)
{
nAttachments.add(m_entityManager.newReference(rv));
}
}
}
catch (Exception eeAny)
{
// if the new resource cannot be added
M_log.warn(" transferCopyEntities: cannot add new attachment with id=" + nAttachmentId + " " + eeAny.getMessage());
}
}
catch (Exception eAny)
{
// if cannot find the original attachment, do nothing.
M_log.warn(" transferCopyEntities: cannot find the original attachment with id=" + oAttachmentId + " " + eAny.getMessage());
}
}
catch (Exception any)
{
M_log.warn(" transferCopyEntities" + any.getMessage() + " oAttachmentId=" + oAttachmentId + " nAttachmentId=" + nAttachmentId);
}
return rv;
}
/**
* {@inheritDoc}
*/
public String getEntityDescription(Reference ref)
{
String rv = "Assignment: " + ref.getReference();
try
{
// is it an AssignmentContent object
if (REF_TYPE_CONTENT.equals(ref.getSubType()))
{
AssignmentContent c = getAssignmentContent(ref.getReference());
rv = "AssignmentContent: " + c.getId() + " (" + c.getContext() + ")";
}
// is it an Assignment object
else if (REF_TYPE_ASSIGNMENT.equals(ref.getSubType()))
{
Assignment a = getAssignment(ref.getReference());
rv = "Assignment: " + a.getId() + " (" + a.getContext() + ")";
}
// is it an AssignmentSubmission object
else if (REF_TYPE_SUBMISSION.equals(ref.getSubType()))
{
AssignmentSubmission s = getSubmission(ref.getReference());
rv = "AssignmentSubmission: " + s.getId() + " (" + s.getContext() + ")";
}
else
M_log.warn(" getEntityDescription(): unknown message ref subtype: " + ref.getSubType() + " in ref: " + ref.getReference());
}
catch (PermissionException e)
{
M_log.warn(" getEntityDescription(): " + e.getMessage() + " ref=" + ref.getReference());
}
catch (IdUnusedException e)
{
M_log.warn(" getEntityDescription(): " + e.getMessage() + " ref=" + ref.getReference());
}
catch (NullPointerException e)
{
M_log.warn(" getEntityDescription(): " + e.getMessage() + " ref=" + ref.getReference());
}
return rv;
}
/**
* {@inheritDoc}
*/
public ResourceProperties getEntityResourceProperties(Reference ref)
{
ResourceProperties rv = null;
try
{
// is it an AssignmentContent object
if (REF_TYPE_CONTENT.equals(ref.getSubType()))
{
AssignmentContent c = getAssignmentContent(ref.getReference());
rv = c.getProperties();
}
// is it an Assignment object
else if (REF_TYPE_ASSIGNMENT.equals(ref.getSubType()))
{
Assignment a = getAssignment(ref.getReference());
rv = a.getProperties();
}
// is it an AssignmentSubmission object
else if (REF_TYPE_SUBMISSION.equals(ref.getSubType()))
{
AssignmentSubmission s = getSubmission(ref.getReference());
rv = s.getProperties();
}
else
M_log.warn(" getEntityResourceProperties: unknown message ref subtype: " + ref.getSubType() + " in ref: " + ref.getReference());
}
catch (PermissionException e)
{
M_log.warn(" getEntityResourceProperties(): " + e.getMessage() + " ref=" + ref.getReference());
}
catch (IdUnusedException e)
{
M_log.warn(" getEntityResourceProperties(): " + e.getMessage() + " ref=" + ref.getReference());
}
catch (NullPointerException e)
{
M_log.warn(" getEntityResourceProperties(): " + e.getMessage() + " ref=" + ref.getReference());
}
return rv;
}
/**
* {@inheritDoc}
*/
public boolean canSubmit(String context, Assignment a)
{
// return false if not allowed to submit at all
if (!allowAddSubmissionCheckGroups(context, a) && !allowAddAssignment(context) /*SAK-25555 return true if user is allowed to add assignment*/) return false;
String userId = SessionManager.getCurrentSessionUserId();
// if user can submit to this assignment
List visibleAssignments = assignments(context, userId);
if (visibleAssignments == null || !visibleAssignments.contains(a)) return false;
try
{
// get user
User u = UserDirectoryService.getUser(userId);
Time currentTime = TimeService.newTime();
// return false if the assignment is draft or is not open yet
Time openTime = a.getOpenTime();
if (a.getDraft() || (openTime != null && openTime.after(currentTime)))
{
return false;
}
// return false if the current time has passed the assignment close time
Time closeTime = a.getCloseTime();
// get user's submission
AssignmentSubmission submission = null;
submission = getSubmission(a.getReference(), u);
// check for allow resubmission or not first
// return true if resubmission is allowed and current time is before resubmission close time
// get the resubmit settings from submission object first
String allowResubmitNumString = submission != null?submission.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):null;
if (allowResubmitNumString != null && submission.getTimeSubmitted() != null)
{
try
{
int allowResubmitNumber = Integer.parseInt(allowResubmitNumString);
String allowResubmitCloseTime = submission != null ? (String) submission.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME):null;
Time resubmitCloseTime = null;
if (allowResubmitCloseTime != null)
{
// see if a resubmission close time is set on submission level
resubmitCloseTime = TimeService.newTime(Long.parseLong(allowResubmitCloseTime));
}
else
{
// otherwise, use assignment close time as the resubmission close time
resubmitCloseTime = a.getCloseTime();
}
return (allowResubmitNumber > 0 /* additional submission number allowed */ || allowResubmitNumber == -1 /* unlimited submission times allowed */) && resubmitCloseTime != null && currentTime.before(resubmitCloseTime);
}
catch (NumberFormatException e)
{
M_log.warn(" canSubmit(String, Assignment) " + e.getMessage() + " allowResubmitNumString=" + allowResubmitNumString);
}
}
if (submission == null || (submission != null && submission.getTimeSubmitted() == null))
{
// if there is no submission yet
if (closeTime != null && currentTime.after(closeTime))
{
return false;
}
else
{
return true;
}
}
else
{
if (!submission.getSubmitted() && !(closeTime != null && currentTime.after(closeTime)))
{
// return true for drafted submissions
return true;
}
else
return false;
}
}
catch (UserNotDefinedException e)
{
// cannot find user
M_log.warn(" canSubmit(String, Assignment) " + e.getMessage() + " assignment ref=" + a.getReference());
return false;
}
}
/**********************************************************************************************************************************************************************************************************************************************************
* Assignment Implementation
*********************************************************************************************************************************************************************************************************************************************************/
public class BaseAssignment implements Assignment
{
protected ResourcePropertiesEdit m_properties;
protected String m_id;
protected String m_assignmentContent;
protected String m_title;
protected String m_context;
protected String m_section;
protected Time m_visibleTime;
protected Time m_openTime;
protected Time m_dueTime;
protected Time m_closeTime;
protected Time m_dropDeadTime;
protected List m_authors;
protected boolean m_draft;
protected boolean m_hideDueDate;
protected boolean m_group;
protected int m_position_order;
/** The Collection of groups (authorization group id strings). */
protected Collection m_groups = new ArrayList();
/** The assignment access. */
protected AssignmentAccess m_access = AssignmentAccess.SITE;
protected boolean m_allowPeerAssessment;
protected Time m_peerAssessmentPeriodTime;
protected boolean m_peerAssessmentAnonEval;
protected boolean m_peerAssessmentStudentViewReviews;
protected int m_peerAssessmentNumReviews;
protected String m_peerAssessmentInstructions;
/**
* constructor
*/
public BaseAssignment()
{
m_properties = new BaseResourcePropertiesEdit();
}// constructor
/**
* Copy constructor
*/
public BaseAssignment(Assignment assignment)
{
setAll(assignment);
}// copy constructor
/**
* Constructor used in addAssignment
*/
public BaseAssignment(String id, String context)
{
m_properties = new BaseResourcePropertiesEdit();
addLiveProperties(m_properties);
m_id = id;
m_assignmentContent = "";
m_title = "";
m_context = context;
m_section = "";
m_authors = new ArrayList();
m_draft = true;
m_hideDueDate = false;
m_groups = new ArrayList();
m_position_order = 0;
m_allowPeerAssessment = false;
m_peerAssessmentPeriodTime = null;
m_peerAssessmentAnonEval = false;
m_peerAssessmentStudentViewReviews = false;
m_peerAssessmentNumReviews = 0;
m_peerAssessmentInstructions = null;
}
/**
* Reads the Assignment's attribute values from xml.
*
* @param s -
* Data structure holding the xml info.
*/
public BaseAssignment(Element el)
{
M_log.debug(" BASE ASSIGNMENT : ENTERING STORAGE CONSTRUCTOR");
m_properties = new BaseResourcePropertiesEdit();
int numAttributes = 0;
String intString = null;
String attributeString = null;
String tempString = null;
m_id = el.getAttribute("id");
M_log.debug(" BASE ASSIGNMENT : STORAGE CONSTRUCTOR : ASSIGNMENT ID : " + m_id);
m_title = el.getAttribute("title");
m_section = el.getAttribute("section");
m_draft = getBool(el.getAttribute("draft"));
m_hideDueDate = getBool(el.getAttribute("hideduedate"));
m_group = getBool(el.getAttribute("group"));
M_log.debug(" BASE ASSIGNMENT : STORAGE CONSTRUCTOR : READ THROUGH REG ATTS");
m_assignmentContent = el.getAttribute("assignmentcontent");
M_log.debug(" BASE ASSIGNMENT : STORAGE CONSTRUCTOR : CONTENT ID : "
+ m_assignmentContent);
m_openTime = getTimeObject(el.getAttribute("opendate"));
m_dueTime = getTimeObject(el.getAttribute("duedate"));
m_visibleTime = getTimeObject(el.getAttribute("visibledate"));
m_dropDeadTime = getTimeObject(el.getAttribute("dropdeaddate"));
m_closeTime = getTimeObject(el.getAttribute("closedate"));
m_context = el.getAttribute("context");
m_position_order = 0; // prevents null pointer if there is no position_order defined as well as helps with the sorting
try
{
m_position_order = Long.valueOf(el.getAttribute("position_order")).intValue();
}
catch (Exception e)
{
M_log.warn(": BaseAssignment(Element) " + e.getMessage());
}
m_allowPeerAssessment = getBool(el.getAttribute("allowpeerassessment"));
m_peerAssessmentPeriodTime = getTimeObject(el.getAttribute("peerassessmentperiodtime"));
m_peerAssessmentAnonEval = getBool(el.getAttribute("peerassessmentanoneval"));
m_peerAssessmentStudentViewReviews = getBool(el.getAttribute("peerassessmentstudentviewreviews"));
String numReviews = el.getAttribute("peerassessmentnumreviews");
m_peerAssessmentNumReviews = 0;
if(numReviews != null && !"".equals(numReviews)){
try{
m_peerAssessmentNumReviews = Integer.parseInt(numReviews);
}catch(Exception e){}
}
m_peerAssessmentInstructions = el.getAttribute("peerassessmentinstructions");
// READ THE AUTHORS
m_authors = new ArrayList();
intString = el.getAttribute("numberofauthors");
M_log.debug(" BASE ASSIGNMENT : STORAGE CONSTRUCTOR : number of authors : " + intString);
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
M_log.debug(" BASE ASSIGNMENT : STORAGE CONSTRUCTOR : reading author # " + x);
attributeString = "author" + x;
tempString = el.getAttribute(attributeString);
if (tempString != null)
{
M_log.debug(" BASE ASSIGNMENT : STORAGE CONSTRUCTOR : adding author # " + x
+ " id : " + tempString);
m_authors.add(tempString);
}
}
}
catch (Exception e)
{
M_log.warn(" BASE ASSIGNMENT : STORAGE CONSTRUCTOR : Exception reading authors : " + e);
}
// READ THE PROPERTIES AND INSTRUCTIONS
NodeList children = el.getChildNodes();
final int length = children.getLength();
for (int i = 0; i < length; i++)
{
Node child = children.item(i);
if (child.getNodeType() != Node.ELEMENT_NODE) continue;
Element element = (Element) child;
// look for properties
if (element.getTagName().equals("properties"))
{
// re-create properties
m_properties = new BaseResourcePropertiesEdit(element);
}
// look for an group
else if (element.getTagName().equals("group"))
{
m_groups.add(element.getAttribute("authzGroup"));
}
}
// extract access
AssignmentAccess access = AssignmentAccess.fromString(el.getAttribute("access"));
if (access != null)
{
m_access = access;
}
M_log.debug(" BASE ASSIGNMENT : LEAVING STORAGE CONSTRUCTOR");
}// storage constructor
/**
* @param services
* @return
*/
public ContentHandler getContentHandler(Map<String, Object> services)
{
final Entity thisEntity = this;
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.DefaultEntityHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String,
* org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if ("assignment".equals(qName) && entity == null)
{
m_id = attributes.getValue("id");
m_properties = new BaseResourcePropertiesEdit();
int numAttributes = 0;
String intString = null;
String attributeString = null;
String tempString = null;
m_title = attributes.getValue("title");
m_section = attributes.getValue("section");
m_draft = getBool(attributes.getValue("draft"));
m_hideDueDate = getBool(attributes.getValue("hideduedate"));
m_group = getBool(attributes.getValue("group"));
M_log.debug(this + " getContentHandler: READ THROUGH REG ATTS");
m_assignmentContent = attributes.getValue("assignmentcontent");
M_log.debug(this + " getContentHandler: STORAGE CONSTRUCTOR : CONTENT ID : "
+ m_assignmentContent);
m_openTime = getTimeObject(attributes.getValue("opendate"));
m_dueTime = getTimeObject(attributes.getValue("duedate"));
m_visibleTime = getTimeObject(attributes.getValue("visibledate"));
m_dropDeadTime = getTimeObject(attributes.getValue("dropdeaddate"));
m_closeTime = getTimeObject(attributes.getValue("closedate"));
m_context = attributes.getValue("context");
try
{
m_position_order = NumberUtils.toInt(attributes.getValue("position_order"));
}
catch (Exception e)
{
m_position_order = 0; // prevents null pointer if there is no position_order defined as well as helps with the sorting
}
m_allowPeerAssessment = getBool(attributes.getValue("allowpeerassessment"));
m_peerAssessmentPeriodTime = getTimeObject(attributes.getValue("peerassessmentperiodtime"));
m_peerAssessmentAnonEval = getBool(attributes.getValue("peerassessmentanoneval"));
m_peerAssessmentStudentViewReviews = getBool(attributes.getValue("peerassessmentstudentviewreviews"));
String numReviews = attributes.getValue("peerassessmentnumreviews");
m_peerAssessmentNumReviews = 0;
if(numReviews != null && !"".equals(numReviews)){
try{
m_peerAssessmentNumReviews = Integer.parseInt(numReviews);
}catch(Exception e){}
}
m_peerAssessmentInstructions = attributes.getValue("peerassessmentinstructions");
// READ THE AUTHORS
m_authors = new ArrayList();
intString = attributes.getValue("numberofauthors");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "author" + x;
tempString = attributes.getValue(attributeString);
if (tempString != null)
{
m_authors.add(tempString);
}
}
}
catch (Exception e)
{
M_log.warn(" BASE ASSIGNMENT getContentHandler startElement : Exception reading authors : " + e.toString());
}
// extract access
AssignmentAccess access = AssignmentAccess.fromString(attributes.getValue("access"));
if (access != null)
{
m_access = access;
}
entity = thisEntity;
}
else if (GROUP_LIST.equals(qName))
{
String groupRef = attributes.getValue(GROUP_NAME);
if (groupRef != null)
{
m_groups.add(groupRef);
}
}
else
{
M_log.debug(this + " BaseAssignment getContentHandler Unexpected Element " + qName);
}
}
}
};
}
/**
* Takes the Assignment's attribute values and puts them into the xml document.
*
* @param s -
* Data structure holding the object to be stored.
* @param doc -
* The xml document.
*/
public Element toXml(Document doc, Stack stack)
{
M_log.debug(this + " BASE ASSIGNMENT : ENTERING TOXML");
Element assignment = doc.createElement("assignment");
if (stack.isEmpty())
{
doc.appendChild(assignment);
}
else
{
((Element) stack.peek()).appendChild(assignment);
}
stack.push(assignment);
// SET ASSIGNMENT ATTRIBUTES
String numItemsString = null;
String attributeString = null;
String itemString = null;
// SAK-13408 -The XML implementation in Websphere throws an LSException if the
// attribute is null, while in Tomcat it assumes an empty string. The following
// sets the attribute to an empty string if the value is null.
assignment.setAttribute("id", m_id == null ? "" : m_id);
assignment.setAttribute("title", m_title == null ? "" : m_title);
assignment.setAttribute("section", m_section == null ? "" : m_section);
assignment.setAttribute("context", m_context == null ? "" : m_context);
assignment.setAttribute("assignmentcontent", m_assignmentContent == null ? "" : m_assignmentContent);
assignment.setAttribute("draft", getBoolString(m_draft));
assignment.setAttribute("group", getBoolString(m_group));
assignment.setAttribute("hideduedate", getBoolString(m_hideDueDate));
assignment.setAttribute("opendate", getTimeString(m_openTime));
assignment.setAttribute("duedate", getTimeString(m_dueTime));
assignment.setAttribute("visibledate", getTimeString(m_visibleTime));
assignment.setAttribute("dropdeaddate", getTimeString(m_dropDeadTime));
assignment.setAttribute("closedate", getTimeString(m_closeTime));
assignment.setAttribute("position_order", Long.valueOf(m_position_order).toString().trim());
assignment.setAttribute("allowpeerassessment", getBoolString(m_allowPeerAssessment));
assignment.setAttribute("peerassessmentperiodtime", getTimeString(m_peerAssessmentPeriodTime));
assignment.setAttribute("peerassessmentanoneval", getBoolString(m_peerAssessmentAnonEval));
assignment.setAttribute("peerassessmentstudentviewreviews", getBoolString(m_peerAssessmentStudentViewReviews));
assignment.setAttribute("peerassessmentnumreviews", "" + m_peerAssessmentNumReviews);
assignment.setAttribute("peerassessmentinstructions", m_peerAssessmentInstructions);
M_log.debug(this + " BASE ASSIGNMENT : TOXML : saved regular properties");
// SAVE THE AUTHORS
numItemsString = "" + m_authors.size();
M_log.debug(this + " BASE ASSIGNMENT : TOXML : saving " + numItemsString + " authors");
assignment.setAttribute("numberofauthors", numItemsString);
for (int x = 0; x < m_authors.size(); x++)
{
attributeString = "author" + x;
itemString = (String) m_authors.get(x);
if (itemString != null)
{
assignment.setAttribute(attributeString, itemString);
M_log.debug(this + " BASE ASSIGNMENT : TOXML : saving author : " + itemString);
}
}
// add groups
if ((m_groups != null) && (m_groups.size() > 0))
{
for (Iterator i = m_groups.iterator(); i.hasNext();)
{
String group = (String) i.next();
Element sect = doc.createElement("group");
assignment.appendChild(sect);
sect.setAttribute("authzGroup", group);
}
}
// add access
assignment.setAttribute("access", m_access.toString());
// SAVE THE PROPERTIES
m_properties.toXml(doc, stack);
M_log.debug(this + " BASE ASSIGNMENT : TOXML : SAVED PROPERTIES");
stack.pop();
M_log.debug("ASSIGNMENT : BASE ASSIGNMENT : LEAVING TOXML");
return assignment;
}// toXml
protected void setAll(Assignment assignment)
{
if (assignment != null)
{
m_id = assignment.getId();
m_assignmentContent = assignment.getContentReference();
m_authors = assignment.getAuthors();
m_title = assignment.getTitle();
m_context = assignment.getContext();
m_section = assignment.getSection();
m_openTime = assignment.getOpenTime();
m_dueTime = assignment.getDueTime();
m_visibleTime = assignment.getVisibleTime();
m_closeTime = assignment.getCloseTime();
m_dropDeadTime = assignment.getDropDeadTime();
m_draft = assignment.getDraft();
m_group = assignment.isGroup();
m_position_order = 0;
try
{
m_position_order = assignment.getPosition_order();
}
catch (Exception e)
{
M_log.warn(": setAll(Assignment) get position order " + e.getMessage());
}
m_properties = new BaseResourcePropertiesEdit();
m_properties.addAll(assignment.getProperties());
m_groups = assignment.getGroups();
m_access = assignment.getAccess();
m_allowPeerAssessment = assignment.getAllowPeerAssessment();
m_peerAssessmentPeriodTime = assignment.getPeerAssessmentPeriod();
m_peerAssessmentAnonEval = assignment.getPeerAssessmentAnonEval();
m_peerAssessmentStudentViewReviews = assignment.getPeerAssessmentStudentViewReviews();
m_peerAssessmentNumReviews = assignment.getPeerAssessmentNumReviews();
m_peerAssessmentInstructions = assignment.getPeerAssessmentInstructions();
}
}
public String getId()
{
return m_id;
}
/**
* Access the URL which can be used to access the resource.
*
* @return The URL which can be used to access the resource.
*/
public String getUrl()
{
return getAccessPoint(false) + Entity.SEPARATOR + "a" + Entity.SEPARATOR + m_context + Entity.SEPARATOR + m_id;
} // getUrl
/**
* Access the internal reference which can be used to access the resource from within the system.
*
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String getReference()
{
return assignmentReference(m_context, m_id);
} // getReference
/**
* @inheritDoc
*/
public String getReference(String rootProperty)
{
return getReference();
}
/**
* @inheritDoc
*/
public String getUrl(String rootProperty)
{
return getUrl();
}
/**
* Access the resource's properties.
*
* @return The resource's properties.
*/
public ResourceProperties getProperties()
{
return m_properties;
}
/**
* Access the list of authors.
*
* @return FlexStringArray of user ids.
*/
public List getAuthors()
{
return m_authors;
}
/**
* Add an author to the author list.
*
* @param author -
* The User to add to the author list.
*/
public void addAuthor(User author)
{
if (author != null) m_authors.add(author.getId());
}
/**
* Remove an author from the author list.
*
* @param author -
* the User to remove from the author list.
*/
public void removeAuthor(User author)
{
if (author != null) m_authors.remove(author.getId());
}
/**
* Access the creator of this object.
*
* @return String The creator's user id.
*/
public String getCreator()
{
return m_properties.getProperty(ResourceProperties.PROP_CREATOR);
}
/**
* Access the person of last modificaiton
*
* @return the User's Id
*/
public String getAuthorLastModified()
{
return m_properties.getProperty(ResourceProperties.PROP_MODIFIED_BY);
}
/**
* Access the title.
*
* @return The Assignment's title.
*/
public String getTitle()
{
return m_title;
}
public Time getPeerAssessmentPeriod()
{
return m_peerAssessmentPeriodTime;
}
public boolean getPeerAssessmentAnonEval(){
return m_peerAssessmentAnonEval;
}
public boolean getPeerAssessmentStudentViewReviews(){
return m_peerAssessmentStudentViewReviews;
}
public int getPeerAssessmentNumReviews(){
return m_peerAssessmentNumReviews;
}
public String getPeerAssessmentInstructions(){
return m_peerAssessmentInstructions;
}
public boolean getAllowPeerAssessment()
{
return m_allowPeerAssessment;
}
/**
* peer assessment is set for this assignment and the current time
* falls between the assignment close time and the peer asseessment period time
* @return
*/
public boolean isPeerAssessmentOpen(){
if(getAllowPeerAssessment()){
Time now = TimeService.newTime();
return now.before(getPeerAssessmentPeriod()) && now.after(getCloseTime());
}else{
return false;
}
}
/**
* peer assessment is set for this assignment but the close time hasn't passed
* @return
*/
public boolean isPeerAssessmentPending(){
if(getAllowPeerAssessment()){
Time now = TimeService.newTime();
return now.before(getCloseTime());
}else{
return false;
}
}
/**
* peer assessment is set for this assignment but the current time is passed
* the peer assessment period
* @return
*/
public boolean isPeerAssessmentClosed(){
if(getAllowPeerAssessment()){
Time now = TimeService.newTime();
return now.after(getPeerAssessmentPeriod());
}else{
return false;
}
}
/**
* @inheritDoc
*/
public String getStatus()
{
Time currentTime = TimeService.newTime();
if (this.getDraft())
return rb.getString("gen.dra1");
else if (this.getOpenTime().after(currentTime))
return rb.getString("gen.notope");
else if (this.getDueTime().after(currentTime))
return rb.getString("gen.open");
else if ((this.getCloseTime() != null) && (this.getCloseTime().before(currentTime)))
return rb.getString("gen.closed");
else
return rb.getString("gen.due");
}
/**
* Access the time that this object was created.
*
* @return The Time object representing the time of creation.
*/
public Time getTimeCreated()
{
try
{
return m_properties.getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
}
catch (EntityPropertyNotDefinedException e)
{
M_log.warn(":getTimeCreated() no time property defined " + e.getMessage());
}
catch (EntityPropertyTypeException e)
{
M_log.warn(":getTimeCreated() no time property defined " + e.getMessage());
}
return null;
}
/**
* Access the time of last modificaiton.
*
* @return The Time of last modification.
*/
public Time getTimeLastModified()
{
try
{
return m_properties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
}
catch (EntityPropertyNotDefinedException e)
{
M_log.warn(":getTimeLastModified() no time property defined " + e.getMessage());
}
catch (EntityPropertyTypeException e)
{
M_log.warn(":getTimeLastModified() no time property defined " + e.getMessage());
}
return null;
}
/**
* Access the AssignmentContent of this Assignment.
*
* @return The Assignment's AssignmentContent.
*/
public AssignmentContent getContent()
{
AssignmentContent retVal = null;
if (m_assignmentContent != null)
{
try
{
retVal = getAssignmentContent(m_assignmentContent);
}
catch (Exception e)
{
M_log.warn(":getContent() " + e.getMessage());
}
}
return retVal;
}
/**
* Access the reference of the AssignmentContent of this Assignment.
*
* @return The Assignment's reference.
*/
public String getContentReference()
{
return m_assignmentContent;
}
/**
* Access the id of the Assignment's group.
*
* @return The id of the group for which this Assignment is designed.
*/
public String getContext()
{
return m_context;
}
/**
* Access the section info
*
* @return The section String
*/
public String getSection()
{
return m_section;
}
/**
* Access the first time at which the assignment can be viewed; may be null.
*
* @return The Time at which the assignment is due, or null if unspecified.
*/
public Time getOpenTime()
{
return m_openTime;
}
/**
* @inheritDoc
*/
public String getOpenTimeString()
{
if ( m_openTime == null )
return "";
else
return m_openTime.toStringLocalFull();
}
/**
* Access the time at which the assignment is due; may be null.
*
* @return The Time at which the Assignment is due, or null if unspecified.
*/
public Time getDueTime()
{
return m_dueTime;
}
/**
* Access the time at which the assignment is visible; may be null.
*
* @return The Time at which the Assignment is visible, or null if unspecified.
*/
public Time getVisibleTime()
{
return m_visibleTime;
}
/**
* @inheritDoc
*/
public String getDueTimeString()
{
if ( m_dueTime == null )
return "";
else
return m_dueTime.toStringLocalFull();
}
public String getVisibleTimeString()
{
if ( m_visibleTime == null )
return "";
else
return m_visibleTime.toStringLocalFull();
}
/**
* Access the drop dead time after which responses to this assignment are considered late; may be null.
*
* @return The Time object representing the drop dead time, or null if unspecified.
*/
public Time getDropDeadTime()
{
return m_dropDeadTime;
}
/**
* @inheritDoc
*/
public String getDropDeadTimeString()
{
if ( m_dropDeadTime == null )
return "";
else
return m_dropDeadTime.toStringLocalFull();
}
/**
* Access the close time after which this assignment can no longer be viewed, and after which submissions will not be accepted. May be null.
*
* @return The Time after which the Assignment is closed, or null if unspecified.
*/
public Time getCloseTime()
{
if (m_closeTime == null)
{
m_closeTime = m_dueTime;
}
return m_closeTime;
}
/**
* @inheritDoc
*/
public String getCloseTimeString()
{
if ( m_closeTime == null )
return "";
else
return m_closeTime.toStringLocalFull();
}
/**
* Get whether this is a draft or final copy.
*
* @return True if this is a draft, false if it is a final copy.
*/
public boolean getDraft()
{
return m_draft;
}
public boolean getHideDueDate()
{
return m_hideDueDate;
}
public boolean isGroup()
{
return m_group;
}
/**
* Access the position order.
*
* @return The Assignment's positionorder.
*/
public int getPosition_order()
{
return m_position_order;
}
/**
* @inheritDoc
*/
public Collection getGroups()
{
return new ArrayList(m_groups);
}
/**
* @inheritDoc
*/
public AssignmentAccess getAccess()
{
return m_access;
}
/**
* Are these objects equal? If they are both Assignment objects, and they have matching id's, they are.
*
* @return true if they are equal, false if not.
*/
public boolean equals(Object obj)
{
if (!(obj instanceof Assignment)) return false;
return ((Assignment) obj).getId().equals(getId());
} // equals
/**
* Make a hash code that reflects the equals() logic as well. We want two objects, even if different instances, if they have the same id to hash the same.
*/
public int hashCode()
{
return getId().hashCode();
} // hashCode
/**
* Compare this object with the specified object for order.
*
* @return A negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
*/
public int compareTo(Object obj)
{
if (!(obj instanceof Assignment)) throw new ClassCastException();
// if the object are the same, say so
if (obj == this) return 0;
// start the compare by comparing their sort names
int compare = getTitle().compareTo(((Assignment) obj).getTitle());
// if these are the same
if (compare == 0)
{
// sort based on (unique) id
compare = getId().compareTo(((Assignment) obj).getId());
}
return compare;
} // compareTo
} // BaseAssignment
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentEdit implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* <p>
* BaseAssignmentEdit is an implementation of the CHEF AssignmentEdit object.
* </p>
*
* @author University of Michigan, CHEF Software Development Team
*/
public class BaseAssignmentEdit extends BaseAssignment implements AssignmentEdit, SessionBindingListener
{
/** The event code for this edit. */
protected String m_event = null;
/** Active flag. */
protected boolean m_active = false;
/**
* Construct from another Assignment object.
*
* @param Assignment
* The Assignment object to use for values.
*/
public BaseAssignmentEdit(Assignment assignment)
{
super(assignment);
} // BaseAssignmentEdit
/**
* Construct.
*
* @param id
* The assignment id.
*/
public BaseAssignmentEdit(String id, String context)
{
super(id, context);
} // BaseAssignmentEdit
/**
* Construct from information in XML.
*
* @param el
* The XML DOM Element definining the Assignment.
*/
public BaseAssignmentEdit(Element el)
{
super(el);
} // BaseAssignmentEdit
/**
* Clean up.
*/
protected void finalize()
{
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelEdit(this);
}
} // finalize
/**
* Set the title.
*
* @param title -
* The Assignment's title.
*/
public void setTitle(String title)
{
m_title = title;
}
public void setPeerAssessmentPeriod(Time time)
{
m_peerAssessmentPeriodTime = time;
}
public void setAllowPeerAssessment(boolean allow)
{
m_allowPeerAssessment = allow;
}
public void setPeerAssessmentAnonEval(boolean anonEval){
m_peerAssessmentAnonEval = anonEval;
}
public void setPeerAssessmentStudentViewReviews(boolean studentViewReviews){
m_peerAssessmentStudentViewReviews = studentViewReviews;
}
public void setPeerAssessmentNumReviews(int numReviews){
m_peerAssessmentNumReviews = numReviews;
}
public void setPeerAssessmentInstructions(String instructions){
m_peerAssessmentInstructions = instructions;
}
/**
* Set the reference of the AssignmentContent of this Assignment.
*
* @param String -
* the reference of the AssignmentContent.
*/
public void setContentReference(String contentReference)
{
if (contentReference != null) m_assignmentContent = contentReference;
}
/**
* Set the AssignmentContent of this Assignment.
*
* @param content -
* the Assignment's AssignmentContent.
*/
public void setContent(AssignmentContent content)
{
if (content != null) m_assignmentContent = content.getReference();
}
/**
* Set the context at the time of creation.
*
* @param context -
* the context string.
*/
public void setContext(String context)
{
m_context = context;
}
/**
* Set the section info
*
* @param sectionId -
* The section id
*/
public void setSection(String sectionId)
{
m_section = sectionId;
}
/**
* Set the first time at which the assignment can be viewed; may be null.
*
* @param opentime -
* The Time at which the Assignment opens.
*/
public void setOpenTime(Time opentime)
{
m_openTime = opentime;
}
/**
* Set the time at which the assignment is due; may be null.
*
* @param dueTime -
* The Time at which the Assignment is due.
*/
public void setDueTime(Time duetime)
{
m_dueTime = duetime;
}
/**
* Set the time at which the assignment is visible; may be null.
*
* @param visibleTime -
* The Time at which the Assignment is visible
*/
public void setVisibleTime(Time visibletime)
{
m_visibleTime = visibletime;
}
/**
* Set the drop dead time after which responses to this assignment are considered late; may be null.
*
* @param dropdeadtime -
* The Time object representing the drop dead time.
*/
public void setDropDeadTime(Time dropdeadtime)
{
m_dropDeadTime = dropdeadtime;
}
/**
* Set the time after which this assignment can no longer be viewed, and after which submissions will not be accepted. May be null.
*
* @param closetime -
* The Time after which the Assignment is closed, or null if unspecified.
*/
public void setCloseTime(Time closetime)
{
m_closeTime = closetime;
}
/**
* Set whether this is a draft or final copy.
*
* @param draft -
* true if this is a draft, false if it is a final copy.
*/
public void setDraft(boolean draft)
{
m_draft = draft;
}
public void setHideDueDate (boolean hide)
{
m_hideDueDate = hide;
}
public void setGroup(boolean group) {
m_group = group;
}
/**
* Set the position order field for the an assignment.
*
* @param position_order -
* The position order.
*/
public void setPosition_order(int position_order)
{
m_position_order = position_order;
}
/**
* Take all values from this object.
*
* @param user
* The user object to take values from.
*/
protected void set(Assignment assignment)
{
setAll(assignment);
} // set
/**
* Access the event code for this edit.
*
* @return The event code for this edit.
*/
protected String getEvent()
{
return m_event;
}
/**
* Set the event code for this edit.
*
* @param event
* The event code for this edit.
*/
protected void setEvent(String event)
{
m_event = event;
}
/**
* Access the resource's properties for modification
*
* @return The resource's properties.
*/
public ResourcePropertiesEdit getPropertiesEdit()
{
return m_properties;
} // getPropertiesEdit
/**
* Enable editing.
*/
protected void activate()
{
m_active = true;
} // activate
/**
* Check to see if the edit is still active, or has already been closed.
*
* @return true if the edit is active, false if it's been closed.
*/
public boolean isActiveEdit()
{
return m_active;
} // isActiveEdit
/**
* Close the edit object - it cannot be used after this.
*/
protected void closeEdit()
{
m_active = false;
} // closeEdit
/******************************************************************************************************************************************************************************************************************************************************
* Group awareness implementation
*****************************************************************************************************************************************************************************************************************************************************/
/**
* @inheritDoc
*/
public void setAccess(AssignmentAccess access)
{
m_access = access;
}
/**
* @inheritDoc
*/
public void setGroupAccess(Collection groups) throws PermissionException
{
// convenience (and what else are we going to do?)
if ((groups == null) || (groups.size() == 0))
{
clearGroupAccess();
return;
}
// is there any change? If we are already grouped, and the group list is the same, ignore the call
if ((m_access == AssignmentAccess.GROUPED) && (EntityCollections.isEqualEntityRefsToEntities(m_groups, groups))) return;
// there should not be a case where there's no context
if (m_context == null)
{
M_log.warn(" setGroupAccess() called with null context: " + getReference());
throw new PermissionException(SessionManager.getCurrentSessionUserId(), "access:site", getReference());
}
// isolate any groups that would be removed or added
Collection addedGroups = new ArrayList();
Collection removedGroups = new ArrayList();
EntityCollections.computeAddedRemovedEntityRefsFromNewEntitiesOldRefs(addedGroups, removedGroups, groups, m_groups);
// verify that the user has permission to remove
if (removedGroups.size() > 0)
{
// the Group objects the user has remove permission
Collection allowedGroups = getGroupsAllowRemoveAssignment(m_context);
for (Iterator i = removedGroups.iterator(); i.hasNext();)
{
String ref = (String) i.next();
// is ref a group the user can remove from?
if (!EntityCollections.entityCollectionContainsRefString(allowedGroups, ref))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), "access:group:remove", ref);
}
}
}
// verify that the user has permission to add in those contexts
if (addedGroups.size() > 0)
{
// the Group objects the user has add permission
Collection allowedGroups = getGroupsAllowAddAssignment(m_context);
for (Iterator i = addedGroups.iterator(); i.hasNext();)
{
String ref = (String) i.next();
// is ref a group the user can remove from?
if (!EntityCollections.entityCollectionContainsRefString(allowedGroups, ref))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), "access:group:add", ref);
}
}
}
// we are clear to perform this
m_access = AssignmentAccess.GROUPED;
EntityCollections.setEntityRefsFromEntities(m_groups, groups);
}
/**
* @inheritDoc
*/
public void clearGroupAccess() throws PermissionException
{
// is there any change? If we are already site, ignore the call
if (m_access == AssignmentAccess.SITE)
{
m_groups.clear();
return;
}
if (m_context == null)
{
// there should not be a case where there's no context
M_log.warn(" clearGroupAccess() called with null context. " + getReference());
throw new PermissionException(SessionManager.getCurrentSessionUserId(), "access:site", getReference());
}
else
{
// verify that the user has permission to add in the site context
if (!allowAddSiteAssignment(m_context))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), "access:site", getReference());
}
}
// we are clear to perform this
m_access = AssignmentAccess.SITE;
m_groups.clear();
}
/******************************************************************************************************************************************************************************************************************************************************
* SessionBindingListener implementation
*****************************************************************************************************************************************************************************************************************************************************/
public void valueBound(SessionBindingEvent event)
{
}
public void valueUnbound(SessionBindingEvent event)
{
M_log.debug(this + " BaseAssignmentEdit valueUnbound()");
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelEdit(this);
}
} // valueUnbound
} // BaseAssignmentEdit
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentContent Implementation
*********************************************************************************************************************************************************************************************************************************************************/
public class BaseAssignmentContent implements AssignmentContent
{
protected ResourcePropertiesEdit m_properties;
protected String m_id;
protected String m_context;
protected List m_attachments;
protected List m_authors;
protected String m_title;
protected String m_instructions;
protected int m_honorPledge;
protected int m_typeOfSubmission;
protected int m_typeOfGrade;
protected int m_maxGradePoint;
protected boolean m_groupProject;
protected boolean m_individuallyGraded;
protected boolean m_releaseGrades;
protected boolean m_hideDueDate;
protected boolean m_allowAttachments;
protected boolean m_allowReviewService;
protected boolean m_allowStudentViewReport;
String m_submitReviewRepo;
String m_generateOriginalityReport;
boolean m_checkTurnitin = true;
boolean m_checkInternet = true;
boolean m_checkPublications = true;
boolean m_checkInstitution = true;
boolean m_excludeBibliographic = true;
boolean m_excludeQuoted = true;
int m_excludeType = 0;
int m_excludeValue = 1;
protected Time m_timeCreated;
protected Time m_timeLastModified;
/**
* constructor
*/
public BaseAssignmentContent()
{
m_properties = new BaseResourcePropertiesEdit();
}// constructor
/**
* Copy constructor.
*/
public BaseAssignmentContent(AssignmentContent content)
{
setAll(content);
}
/**
* Constructor used in addAssignmentContent.
*/
public BaseAssignmentContent(String id, String context)
{
m_id = id;
m_context = context;
m_properties = new BaseResourcePropertiesEdit();
addLiveProperties(m_properties);
m_authors = new ArrayList();
m_attachments = m_entityManager.newReferenceList();
m_title = "";
m_instructions = "";
m_honorPledge = Assignment.HONOR_PLEDGE_NOT_SET;
m_typeOfSubmission = Assignment.ASSIGNMENT_SUBMISSION_TYPE_NOT_SET;
m_typeOfGrade = Assignment.GRADE_TYPE_NOT_SET;
m_maxGradePoint = 0;
m_timeCreated = TimeService.newTime();
m_timeLastModified = TimeService.newTime();
}
/**
* Reads the AssignmentContent's attribute values from xml.
*
* @param s -
* Data structure holding the xml info.
*/
public BaseAssignmentContent(Element el)
{
int numAttributes = 0;
String intString = null;
String attributeString = null;
String tempString = null;
Reference tempReference = null;
M_log.debug(" BaseAssignmentContent : Entering read");
m_id = el.getAttribute("id");
m_context = el.getAttribute("context");
m_title = el.getAttribute("title");
m_groupProject = getBool(el.getAttribute("groupproject"));
m_individuallyGraded = getBool(el.getAttribute("indivgraded"));
m_releaseGrades = getBool(el.getAttribute("releasegrades"));
m_allowAttachments = getBool(el.getAttribute("allowattach"));
m_hideDueDate = getBool(el.getAttribute("hideduedate"));
m_allowReviewService = getBool(el.getAttribute("allowreview"));
m_allowStudentViewReport = getBool(el.getAttribute("allowstudentview"));
m_submitReviewRepo = el.getAttribute("submitReviewRepo");
m_generateOriginalityReport = el.getAttribute("generateOriginalityReport");
m_checkTurnitin = getBool(el.getAttribute("checkTurnitin"));
m_checkInternet = getBool(el.getAttribute("checkInternet"));
m_checkPublications = getBool(el.getAttribute("checkPublications"));
m_checkInstitution = getBool(el.getAttribute("checkInstitution"));
m_excludeBibliographic = getBool(el.getAttribute("excludeBibliographic"));
m_excludeQuoted = getBool(el.getAttribute("excludeQuoted"));
String excludeTypeStr = el.getAttribute("excludeType");
try{
m_excludeType = Integer.parseInt(excludeTypeStr);
if(m_excludeType != 0 && m_excludeType != 1 && m_excludeType != 2){
m_excludeType = 0;
}
}catch (Exception e) {
m_excludeType = 0;
}
String excludeValueStr = el.getAttribute("excludeValue");
try{
m_excludeValue = Integer.parseInt(excludeValueStr);
if(m_excludeValue < 0 || m_excludeValue > 100){
m_excludeValue = 1;
}
}catch (Exception e) {
m_excludeValue = 1;
}
m_timeCreated = getTimeObject(el.getAttribute("datecreated"));
m_timeLastModified = getTimeObject(el.getAttribute("lastmod"));
m_instructions = FormattedText.decodeFormattedTextAttribute(el, "instructions");
try
{
m_honorPledge = Integer.parseInt(el.getAttribute("honorpledge"));
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentContent Exception parsing honor pledge int from xml file string : " + e);
}
try
{
m_typeOfSubmission = Integer.parseInt(el.getAttribute("submissiontype"));
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentContent Exception parsing submission type int from xml file string : " + e);
}
try
{
m_typeOfGrade = Integer.parseInt(el.getAttribute("typeofgrade"));
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentContent Exception parsing grade type int from xml file string : " + e);
}
try
{
// %%%zqian
// read the scaled max grade point first; if there is none, get the old max grade value and multiple by 10
String maxGradePoint = StringUtils.trimToNull(el.getAttribute("scaled_maxgradepoint"));
if (maxGradePoint == null)
{
maxGradePoint = StringUtils.trimToNull(el.getAttribute("maxgradepoint"));
if (maxGradePoint != null)
{
maxGradePoint = maxGradePoint + "0";
}
}
if (maxGradePoint != null)
{
m_maxGradePoint = Integer.parseInt(maxGradePoint);
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentContent Exception parsing maxgradepoint int from xml file string : " + e);
}
// READ THE AUTHORS
m_authors = new ArrayList();
intString = el.getAttribute("numberofauthors");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "author" + x;
tempString = el.getAttribute(attributeString);
if (tempString != null) m_authors.add(tempString);
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentContent: Exception reading authors : " + e);
}
// READ THE ATTACHMENTS
m_attachments = m_entityManager.newReferenceList();
M_log.debug(" BaseAssignmentContent: Reading attachments : ");
intString = el.getAttribute("numberofattachments");
M_log.debug(" BaseAssignmentContent: num attachments : " + intString);
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "attachment" + x;
tempString = el.getAttribute(attributeString);
if (tempString != null)
{
tempReference = m_entityManager.newReference(tempString);
m_attachments.add(tempReference);
M_log.debug(" BaseAssignmentContent: " + attributeString + " : " + tempString);
}
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentContent: Exception reading attachments : " + e);
}
// READ THE PROPERTIES
NodeList children = el.getChildNodes();
final int length = children.getLength();
for (int i = 0; i < length; i++)
{
Node child = children.item(i);
if (child.getNodeType() != Node.ELEMENT_NODE) continue;
Element element = (Element) child;
// look for properties
if (element.getTagName().equals("properties"))
{
// re-create properties
m_properties = new BaseResourcePropertiesEdit(element);
}
// old style of encoding
else if (element.getTagName().equals("instructions-html") || element.getTagName().equals("instructions-formatted")
|| element.getTagName().equals("instructions"))
{
if ((element.getChildNodes() != null) && (element.getChildNodes().item(0) != null))
{
m_instructions = element.getChildNodes().item(0).getNodeValue();
if (element.getTagName().equals("instructions"))
m_instructions = FormattedText.convertPlaintextToFormattedText(m_instructions);
if (element.getTagName().equals("instructions-formatted"))
m_instructions = FormattedText.convertOldFormattedText(m_instructions);
M_log.debug(" BaseAssignmentContent(Element): instructions : " + m_instructions);
}
if (m_instructions == null)
{
m_instructions = "";
}
}
}
M_log.debug(" BaseAssignmentContent(Element): LEAVING STORAGE CONSTRUTOR");
}// storage constructor
/**
* @param services
* @return
*/
public ContentHandler getContentHandler(Map<String, Object> services)
{
final Entity thisEntity = this;
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.DefaultEntityHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String,
* org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if ("content".equals(qName) && entity == null)
{
int numAttributes = 0;
String intString = null;
String attributeString = null;
String tempString = null;
Reference tempReference = null;
m_id = attributes.getValue("id");
m_context = attributes.getValue("context");
m_title = attributes.getValue("title");
m_groupProject = getBool(attributes.getValue("groupproject"));
m_individuallyGraded = getBool(attributes.getValue("indivgraded"));
m_releaseGrades = getBool(attributes.getValue("releasegrades"));
m_allowAttachments = getBool(attributes.getValue("allowattach"));
m_hideDueDate = getBool(attributes.getValue("hideduedate"));
m_allowReviewService = getBool(attributes.getValue("allowreview"));
m_allowStudentViewReport = getBool(attributes.getValue("allowstudentview"));
m_submitReviewRepo = attributes.getValue("submitReviewRepo");
m_generateOriginalityReport = attributes.getValue("generateOriginalityReport");
m_checkTurnitin = getBool(attributes.getValue("checkTurnitin"));
m_checkInternet = getBool(attributes.getValue("checkInternet"));
m_checkPublications = getBool(attributes.getValue("checkPublications"));
m_checkInstitution = getBool(attributes.getValue("checkInstitution"));
m_excludeBibliographic = getBool(attributes.getValue("excludeBibliographic"));
m_excludeQuoted = getBool(attributes.getValue("excludeQuoted"));
String excludeTypeStr = attributes.getValue("excludeType");
try{
m_excludeType = Integer.parseInt(excludeTypeStr);
if(m_excludeType != 0 && m_excludeType != 1 && m_excludeType != 2){
m_excludeType = 0;
}
}catch (Exception e) {
m_excludeType = 0;
}
String excludeValueStr = attributes.getValue("excludeValue");
try{
m_excludeValue = Integer.parseInt(excludeValueStr);
if(m_excludeValue < 0 || m_excludeValue > 100){
m_excludeValue = 1;
}
}catch (Exception e) {
m_excludeValue = 1;
}
m_timeCreated = getTimeObject(attributes.getValue("datecreated"));
m_timeLastModified = getTimeObject(attributes.getValue("lastmod"));
m_instructions = formattedTextDecodeFormattedTextAttribute(attributes, "instructions");
try
{
m_honorPledge = Integer.parseInt(attributes.getValue("honorpledge"));
}
catch (Exception e)
{
M_log.warn(" getContentHandler startElement Exception parsing honor pledge int from xml file string : " + e);
}
try
{
m_typeOfSubmission = Integer.parseInt(attributes.getValue("submissiontype"));
}
catch (Exception e)
{
M_log.warn(" getContentHandler startElement Exception parsing submission type int from xml file string : " + e);
}
try
{
m_typeOfGrade = Integer.parseInt(attributes.getValue("typeofgrade"));
}
catch (Exception e)
{
M_log.warn(" getContentHandler startElement Exception parsing grade type int from xml file string : " + e);
}
try
{
// %%%zqian
// read the scaled max grade point first; if there is none, get the old max grade value and multiple by 10
String maxGradePoint = StringUtils.trimToNull(attributes.getValue("scaled_maxgradepoint"));
if (maxGradePoint == null)
{
maxGradePoint = StringUtils.trimToNull(attributes.getValue("maxgradepoint"));
if (maxGradePoint != null)
{
maxGradePoint = maxGradePoint + "0";
}
}
m_maxGradePoint = maxGradePoint != null ? Integer.parseInt(maxGradePoint) : m_maxGradePoint;
}
catch (Exception e)
{
M_log.warn(" getContentHandler startElement Exception parsing maxgradepoint int from xml file string : " + e);
}
// READ THE AUTHORS
m_authors = new ArrayList();
intString = attributes.getValue("numberofauthors");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "author" + x;
tempString = attributes.getValue(attributeString);
if (tempString != null) m_authors.add(tempString);
}
}
catch (Exception e)
{
M_log.warn(" getContentHandler startElement Exception reading authors : " + e);
}
// READ THE ATTACHMENTS
m_attachments = m_entityManager.newReferenceList();
intString = attributes.getValue("numberofattachments");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "attachment" + x;
tempString = attributes.getValue(attributeString);
if (tempString != null)
{
tempReference = m_entityManager.newReference(tempString);
m_attachments.add(tempReference);
}
}
}
catch (Exception e)
{
M_log.warn(" getContentHandler startElement DbCachedContent : Exception reading attachments : " + e);
}
entity = thisEntity;
}
else
{
M_log.warn(" getContentHandler startElement Unexpected Element " + qName);
}
}
}
};
}
/**
* Takes the AssignmentContent's attribute values and puts them into the xml document.
*
* @param s -
* Data structure holding the object to be stored.
* @param doc -
* The xml document.
*/
public Element toXml(Document doc, Stack stack)
{
M_log.debug(this + " BASE ASSIGNMENT : ENTERING TOXML");
Element content = doc.createElement("content");
if (stack.isEmpty())
{
doc.appendChild(content);
}
else
{
((Element) stack.peek()).appendChild(content);
}
stack.push(content);
String numItemsString = null;
String attributeString = null;
String itemString = null;
Reference tempReference = null;
// SAK-13408 -The XML implementation in Websphere throws an LSException if the
// attribute is null, while in Tomcat it assumes an empty string. The following
// sets the attribute to an empty string if the value is null.
content.setAttribute("id", m_id == null ? "" : m_id);
content.setAttribute("context", m_context == null ? "" : m_context);
content.setAttribute("title", m_title == null ? "" : m_title);
content.setAttribute("groupproject", getBoolString(m_groupProject));
content.setAttribute("indivgraded", getBoolString(m_individuallyGraded));
content.setAttribute("releasegrades", getBoolString(m_releaseGrades));
content.setAttribute("allowattach", getBoolString(m_allowAttachments));
content.setAttribute("hideduedate", getBoolString(m_hideDueDate));
content.setAttribute("allowreview", getBoolString(m_allowReviewService));
content.setAttribute("allowstudentview", getBoolString(m_allowStudentViewReport));
content.setAttribute("submitReviewRepo", m_submitReviewRepo);
content.setAttribute("generateOriginalityReport", m_generateOriginalityReport);
content.setAttribute("checkTurnitin", getBoolString(m_checkTurnitin));
content.setAttribute("checkInternet", getBoolString(m_checkInternet));
content.setAttribute("checkPublications", getBoolString(m_checkPublications));
content.setAttribute("checkInstitution", getBoolString(m_checkInstitution));
content.setAttribute("excludeBibliographic", getBoolString(m_excludeBibliographic));
content.setAttribute("excludeQuoted", getBoolString(m_excludeQuoted));
content.setAttribute("excludeType", Integer.toString(m_excludeType));
content.setAttribute("excludeValue", Integer.toString(m_excludeValue));
content.setAttribute("honorpledge", String.valueOf(m_honorPledge));
content.setAttribute("submissiontype", String.valueOf(m_typeOfSubmission));
content.setAttribute("typeofgrade", String.valueOf(m_typeOfGrade));
content.setAttribute("scaled_maxgradepoint", String.valueOf(m_maxGradePoint));
content.setAttribute("datecreated", getTimeString(m_timeCreated));
content.setAttribute("lastmod", getTimeString(m_timeLastModified));
M_log.debug(this + " BASE CONTENT : TOXML : SAVED REGULAR PROPERTIES");
// SAVE THE AUTHORS
numItemsString = "" + m_authors.size();
content.setAttribute("numberofauthors", numItemsString);
for (int x = 0; x < m_authors.size(); x++)
{
attributeString = "author" + x;
itemString = (String) m_authors.get(x);
if (itemString != null) content.setAttribute(attributeString, itemString);
}
M_log.debug(this + " BASE CONTENT : TOXML : SAVED AUTHORS");
// SAVE THE ATTACHMENTS
numItemsString = "" + m_attachments.size();
content.setAttribute("numberofattachments", numItemsString);
for (int x = 0; x < m_attachments.size(); x++)
{
attributeString = "attachment" + x;
tempReference = (Reference) m_attachments.get(x);
itemString = tempReference.getReference();
if (itemString != null) content.setAttribute(attributeString, itemString);
}
// SAVE THE PROPERTIES
m_properties.toXml(doc, stack);
M_log.debug(this + " BASE CONTENT : TOXML : SAVED REGULAR PROPERTIES");
stack.pop();
// SAVE THE INSTRUCTIONS
FormattedText.encodeFormattedTextAttribute(content, "instructions", m_instructions);
return content;
}// toXml
protected void setAll(AssignmentContent content)
{
if (content != null)
{
m_id = content.getId();
m_context = content.getContext();
m_authors = content.getAuthors();
m_attachments = content.getAttachments();
m_title = content.getTitle();
m_instructions = content.getInstructions();
m_honorPledge = content.getHonorPledge();
m_typeOfSubmission = content.getTypeOfSubmission();
m_typeOfGrade = content.getTypeOfGrade();
m_maxGradePoint = content.getMaxGradePoint();
m_groupProject = content.getGroupProject();
m_individuallyGraded = content.individuallyGraded();
m_releaseGrades = content.releaseGrades();
m_allowAttachments = content.getAllowAttachments();
m_hideDueDate = content.getHideDueDate();
//Uct
m_allowReviewService = content.getAllowReviewService();
m_allowStudentViewReport = content.getAllowStudentViewReport();
m_submitReviewRepo = content.getSubmitReviewRepo();
m_generateOriginalityReport = content.getGenerateOriginalityReport();
m_checkTurnitin = content.isCheckTurnitin();
m_checkInternet = content.isCheckInternet();
m_checkPublications = content.isCheckPublications();
m_checkInstitution = content.isCheckInstitution();
m_excludeBibliographic = content.isExcludeBibliographic();
m_excludeQuoted = content.isExcludeQuoted();
m_excludeType = content.getExcludeType();
m_excludeValue = content.getExcludeValue();
m_timeCreated = content.getTimeCreated();
m_timeLastModified = content.getTimeLastModified();
m_properties = new BaseResourcePropertiesEdit();
m_properties.addAll(content.getProperties());
}
}
public String getId()
{
return m_id;
}
/**
* Access the URL which can be used to access the resource.
*
* @return The URL which can be used to access the resource.
*/
public String getUrl()
{
return getAccessPoint(false) + Entity.SEPARATOR + "c" + Entity.SEPARATOR + m_context + Entity.SEPARATOR + m_id;
} // getUrl
/**
* Access the internal reference which can be used to access the resource from within the system.
*
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String getReference()
{
return contentReference(m_context, m_id);
} // getReference
/**
* @inheritDoc
*/
public String getReference(String rootProperty)
{
return getReference();
}
/**
* @inheritDoc
*/
public String getUrl(String rootProperty)
{
return getUrl();
}
/**
* Access the resource's properties.
*
* @return The resource's properties.
*/
public ResourceProperties getProperties()
{
return m_properties;
}
/******************************************************************************************************************************************************************************************************************************************************
* AttachmentContainer Implementation
*****************************************************************************************************************************************************************************************************************************************************/
/**
* Access the attachments.
*
* @return The set of attachments (a ReferenceVector containing Reference objects) (may be empty).
*/
public List getAttachments()
{
return m_attachments;
}
/******************************************************************************************************************************************************************************************************************************************************
* AssignmentContent Implementation
*****************************************************************************************************************************************************************************************************************************************************/
/**
* Access the AssignmentContent's context at the time of creation.
*
* @return String - the context string.
*/
public String getContext()
{
return m_context;
}
/**
* Access the list of authors.
*
* @return FlexStringArray of user ids.
*/
public List getAuthors()
{
return m_authors;
}
/**
* Access the creator of this object.
*
* @return The User object representing the creator.
*/
public String getCreator()
{
return m_properties.getProperty(ResourceProperties.PROP_CREATOR);
}
/**
* Access the person of last modificaiton
*
* @return the User
*/
public String getAuthorLastModified()
{
return m_properties.getProperty(ResourceProperties.PROP_MODIFIED_BY);
}
/**
* Access the title.
*
* @return The Assignment's title.
*/
public String getTitle()
{
return m_title;
}
/**
* Access the instructions.
*
* @return The Assignment Content's instructions.
*/
public String getInstructions()
{
return m_instructions;
}
/**
* Get the type of valid submission.
*
* @return int - Type of Submission.
*/
public int getTypeOfSubmission()
{
return m_typeOfSubmission;
}
/**
* Access a string describing the type of grade.
*
* @param gradeType -
* The integer representing the type of grade.
* @return Description of the type of grade.
*/
public String getTypeOfGradeString(int type)
{
String retVal = null;
switch (type)
{
case 1:
retVal = rb.getString("ungra");
break;
case 2:
retVal = rb.getString("letter");
break;
case 3:
retVal = rb.getString("points");
break;
case 4:
retVal = rb.getString("passfail");
break;
case 5:
retVal = rb.getString("check");
break;
default:
retVal = "Unknown Grade Type";
break;
}
return retVal;
}
/**
* Get the grade type.
*
* @return gradeType - The type of grade.
*/
public int getTypeOfGrade()
{
return m_typeOfGrade;
}
/**
* Get the maximum grade for grade type = SCORE_GRADE_TYPE(3)
*
* @return The maximum grade score.
*/
public int getMaxGradePoint()
{
return m_maxGradePoint;
}
/**
* Get the maximum grade for grade type = SCORE_GRADE_TYPE(3) Formated to show one decimal place
*
* @return The maximum grade score.
*/
public String getMaxGradePointDisplay()
{
// formated to show one decimal place, for example, 1000 to 100.0
String one_decimal_maxGradePoint = m_maxGradePoint / 10 + "." + (m_maxGradePoint % 10);
// get localized number format
NumberFormat nbFormat = NumberFormat.getInstance();
try {
Locale locale = null;
ResourceLoader rb = new ResourceLoader();
locale = rb.getLocale();
nbFormat = NumberFormat.getNumberInstance(locale);
}
catch (Exception e) {
M_log.warn("Error while retrieving local number format, using default ", e);
}
nbFormat.setMaximumFractionDigits(1);
nbFormat.setMinimumFractionDigits(1);
nbFormat.setGroupingUsed(false);
// show grade in localized number format
Double dblGrade = new Double(one_decimal_maxGradePoint);
one_decimal_maxGradePoint = nbFormat.format(dblGrade);
return one_decimal_maxGradePoint;
}
/**
* Get whether this project can be a group project.
*
* @return True if this can be a group project, false otherwise.
*/
public boolean getGroupProject()
{
return m_groupProject;
}
/**
* Get whether group projects should be individually graded.
*
* @return individGraded - true if projects are individually graded, false if grades are given to the group.
*/
public boolean individuallyGraded()
{
return m_individuallyGraded;
}
/**
* Gets whether grades can be released once submissions are graded.
*
* @return true if grades can be released once submission are graded, false if they must be released manually.
*/
public boolean releaseGrades()
{
return m_releaseGrades;
}
/**
* Get the Honor Pledge type; values are NONE and ENGINEERING_HONOR_PLEDGE.
*
* @return the Honor Pledge value.
*/
public int getHonorPledge()
{
return m_honorPledge;
}
/**
* Does this Assignment allow attachments?
*
* @return true if the Assignment allows attachments, false otherwise?
*/
public boolean getAllowAttachments()
{
return m_allowAttachments;
}
/**
* Does this Assignment have a hidden due date
*
* @return true if the Assignment due date hidden, false otherwise?
*/
public boolean getHideDueDate()
{
return m_hideDueDate;
}
/**
* Does this Assignment allow review service?
*
* @return true if the Assignment allows review service, false otherwise?
*/
public boolean getAllowReviewService()
{
return m_allowReviewService;
}
public boolean getAllowStudentViewReport() {
return m_allowStudentViewReport;
}
/**
* Access the time that this object was created.
*
* @return The Time object representing the time of creation.
*/
public Time getTimeCreated()
{
return m_timeCreated;
}
/**
* Access the time of last modificaiton.
*
* @return The Time of last modification.
*/
public Time getTimeLastModified()
{
return m_timeLastModified;
}
/**
* Is this AssignmentContent selected for use by an Assignment ?
*/
public boolean inUse()
{
boolean retVal = false;
Assignment assignment = null;
List allAssignments = getAssignments(m_context);
for (int x = 0; x < allAssignments.size(); x++)
{
assignment = (Assignment) allAssignments.get(x);
if (assignment.getContentReference().equals(getReference())) return true;
}
return retVal;
}
/**
* Are these objects equal? If they are both AssignmentContent objects, and they have matching id's, they are.
*
* @return true if they are equal, false if not.
*/
public boolean equals(Object obj)
{
if (!(obj instanceof AssignmentContent)) return false;
return ((AssignmentContent) obj).getId().equals(getId());
} // equals
/**
* Make a hash code that reflects the equals() logic as well. We want two objects, even if different instances, if they have the same id to hash the same.
*/
public int hashCode()
{
return getId().hashCode();
} // hashCode
/**
* Compare this object with the specified object for order.
*
* @return A negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
*/
public int compareTo(Object obj)
{
if (!(obj instanceof AssignmentContent)) throw new ClassCastException();
// if the object are the same, say so
if (obj == this) return 0;
// start the compare by comparing their sort names
int compare = getTitle().compareTo(((AssignmentContent) obj).getTitle());
// if these are the same
if (compare == 0)
{
// sort based on (unique) id
compare = getId().compareTo(((AssignmentContent) obj).getId());
}
return compare;
} // compareTo
public String getSubmitReviewRepo() {
return m_submitReviewRepo;
}
public void setSubmitReviewRepo(String m_submitReviewRepo) {
this.m_submitReviewRepo = m_submitReviewRepo;
}
public String getGenerateOriginalityReport() {
return m_generateOriginalityReport;
}
public void setGenerateOriginalityReport(String m_generateOriginalityReport) {
this.m_generateOriginalityReport = m_generateOriginalityReport;
}
public boolean isCheckTurnitin() {
return m_checkTurnitin;
}
public void setCheckTurnitin(boolean m_checkTurnitin) {
this.m_checkTurnitin = m_checkTurnitin;
}
public boolean isCheckInternet() {
return m_checkInternet;
}
public void setCheckInternet(boolean m_checkInternet) {
this.m_checkInternet = m_checkInternet;
}
public boolean isCheckPublications() {
return m_checkPublications;
}
public void setCheckPublications(boolean m_checkPublications) {
this.m_checkPublications = m_checkPublications;
}
public boolean isCheckInstitution() {
return m_checkInstitution;
}
public void setCheckInstitution(boolean m_checkInstitution) {
this.m_checkInstitution = m_checkInstitution;
}
public boolean isExcludeBibliographic() {
return m_excludeBibliographic;
}
public void setExcludeBibliographic(boolean m_excludeBibliographic) {
this.m_excludeBibliographic = m_excludeBibliographic;
}
public boolean isExcludeQuoted() {
return m_excludeQuoted;
}
public void setExcludeQuoted(boolean m_excludeQuoted) {
this.m_excludeQuoted = m_excludeQuoted;
}
public int getExcludeType(){
return m_excludeType;
}
public void setExcludeType(int m_excludeType){
this.m_excludeType = m_excludeType;
}
public int getExcludeValue(){
return m_excludeValue;
}
public void setExcludeValue(int m_excludeValue){
this.m_excludeValue = m_excludeValue;
}
}// BaseAssignmentContent
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentContentEdit implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* <p>
* BaseAssignmentContentEdit is an implementation of the CHEF AssignmentContentEdit object.
* </p>
*
* @author University of Michigan, CHEF Software Development Team
*/
public class BaseAssignmentContentEdit extends BaseAssignmentContent implements AttachmentContainer, AssignmentContentEdit,
SessionBindingListener
{
/** The event code for this edit. */
protected String m_event = null;
/** Active flag. */
protected boolean m_active = false;
/**
* Construct from another AssignmentContent object.
*
* @param AssignmentContent
* The AssignmentContent object to use for values.
*/
public BaseAssignmentContentEdit(AssignmentContent assignmentContent)
{
super(assignmentContent);
} // BaseAssignmentContentEdit
/**
* Construct.
*
* @param id
* The AssignmentContent id.
*/
public BaseAssignmentContentEdit(String id, String context)
{
super(id, context);
} // BaseAssignmentContentEdit
/**
* Construct from information in XML.
*
* @param el
* The XML DOM Element definining the AssignmentContent.
*/
public BaseAssignmentContentEdit(Element el)
{
super(el);
} // BaseAssignmentContentEdit
/**
* Clean up.
*/
protected void finalize()
{
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelEdit(this);
}
} // finalize
/******************************************************************************************************************************************************************************************************************************************************
* AttachmentContainer Implementation
*****************************************************************************************************************************************************************************************************************************************************/
/**
* Add an attachment.
*
* @param ref -
* The attachment Reference.
*/
public void addAttachment(Reference ref)
{
if (ref != null) m_attachments.add(ref);
}
/**
* Remove an attachment.
*
* @param ref -
* The attachment Reference to remove (the one removed will equal this, they need not be ==).
*/
public void removeAttachment(Reference ref)
{
if (ref != null) m_attachments.remove(ref);
}
/**
* Replace the attachment set.
*
* @param attachments -
* A ReferenceVector that will become the new set of attachments.
*/
public void replaceAttachments(List attachments)
{
m_attachments = attachments;
}
/**
* Clear all attachments.
*/
public void clearAttachments()
{
m_attachments.clear();
}
/******************************************************************************************************************************************************************************************************************************************************
* AssignmentContentEdit Implementation
*****************************************************************************************************************************************************************************************************************************************************/
/**
* Set the title.
*
* @param title -
* The Assignment's title.
*/
public void setTitle(String title)
{
m_title = title;
}
/**
* Set the instructions.
*
* @param instructions -
* The Assignment's instructions.
*/
public void setInstructions(String instructions)
{
m_instructions = instructions;
}
/**
* Set the context at the time of creation.
*
* @param context -
* the context string.
*/
public void setContext(String context)
{
m_context = context;
}
/**
* Set the type of valid submission.
*
* @param int -
* Type of Submission.
*/
public void setTypeOfSubmission(int type)
{
m_typeOfSubmission = type;
}
/**
* Set the grade type.
*
* @param gradeType -
* The type of grade.
*/
public void setTypeOfGrade(int gradeType)
{
m_typeOfGrade = gradeType;
}
/**
* Set the maximum grade for grade type = SCORE_GRADE_TYPE(3)
*
* @param maxPoints -
* The maximum grade score.
*/
public void setMaxGradePoint(int maxPoints)
{
m_maxGradePoint = maxPoints;
}
/**
* Set whether this project can be a group project.
*
* @param groupProject -
* True if this can be a group project, false otherwise.
*/
public void setGroupProject(boolean groupProject)
{
m_groupProject = groupProject;
}
/**
* Set whether group projects should be individually graded.
*
* @param individGraded -
* true if projects are individually graded, false if grades are given to the group.
*/
public void setIndividuallyGraded(boolean individGraded)
{
m_individuallyGraded = individGraded;
}
/**
* Sets whether grades can be released once submissions are graded.
*
* @param release -
* true if grades can be released once submission are graded, false if they must be released manually.
*/
public void setReleaseGrades(boolean release)
{
m_releaseGrades = release;
}
public void setHideDueDate(boolean hide)
{
m_hideDueDate = hide;
}
/**
* Set the Honor Pledge type; values are NONE and ENGINEERING_HONOR_PLEDGE.
*
* @param pledgeType -
* the Honor Pledge value.
*/
public void setHonorPledge(int pledgeType)
{
m_honorPledge = pledgeType;
}
/**
* Does this Assignment allow using the review service?
*
* @param allow -
* true if the Assignment allows review service, false otherwise?
*/
public void setAllowReviewService(boolean allow)
{
m_allowReviewService = allow;
}
/**
* Does this Assignment allow students to view the report?
*
* @param allow -
* true if the Assignment allows students to view the report, false otherwise?
*/
public void setAllowStudentViewReport(boolean allow) {
m_allowStudentViewReport = allow;
}
/**
* Does this Assignment allow attachments?
*
* @param allow -
* true if the Assignment allows attachments, false otherwise?
*/
public void setAllowAttachments(boolean allow)
{
m_allowAttachments = allow;
}
/**
* Add an author to the author list.
*
* @param author -
* The User to add to the author list.
*/
public void addAuthor(User author)
{
if (author != null) m_authors.add(author.getId());
}
/**
* Remove an author from the author list.
*
* @param author -
* the User to remove from the author list.
*/
public void removeAuthor(User author)
{
if (author != null) m_authors.remove(author.getId());
}
/**
* Set the time last modified.
*
* @param lastmod -
* The Time at which the Content was last modified.
*/
public void setTimeLastModified(Time lastmod)
{
if (lastmod != null) m_timeLastModified = lastmod;
}
/**
* Take all values from this object.
*
* @param AssignmentContent
* The AssignmentContent object to take values from.
*/
protected void set(AssignmentContent assignmentContent)
{
setAll(assignmentContent);
} // set
/**
* Access the event code for this edit.
*
* @return The event code for this edit.
*/
protected String getEvent()
{
return m_event;
}
/**
* Set the event code for this edit.
*
* @param event
* The event code for this edit.
*/
protected void setEvent(String event)
{
m_event = event;
}
/**
* Access the resource's properties for modification
*
* @return The resource's properties.
*/
public ResourcePropertiesEdit getPropertiesEdit()
{
return m_properties;
} // getPropertiesEdit
/**
* Enable editing.
*/
protected void activate()
{
m_active = true;
} // activate
/**
* Check to see if the edit is still active, or has already been closed.
*
* @return true if the edit is active, false if it's been closed.
*/
public boolean isActiveEdit()
{
return m_active;
} // isActiveEdit
/**
* Close the edit object - it cannot be used after this.
*/
protected void closeEdit()
{
m_active = false;
} // closeEdit
/******************************************************************************************************************************************************************************************************************************************************
* SessionBindingListener implementation
*****************************************************************************************************************************************************************************************************************************************************/
public void valueBound(SessionBindingEvent event)
{
}
public void valueUnbound(SessionBindingEvent event)
{
M_log.debug(" BaseAssignmentContent valueUnbound()");
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelEdit(this);
}
} // valueUnbound
} // BaseAssignmentContentEdit
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentSubmission implementation
*********************************************************************************************************************************************************************************************************************************************************/
public class BaseAssignmentSubmission implements AssignmentSubmission
{
protected final String STATUS_DRAFT = "Drafted";
protected final String STATUS_SUBMITTED = "Submitted";
protected final String STATUS_RETURNED = "Returned";
protected final String STATUS_GRADED = "Graded";
protected ResourcePropertiesEdit m_properties;
protected String m_id;
protected String m_assignment;
protected String m_context;
protected List m_submitters;
protected String m_submitterId;
protected List m_submissionLog;
protected List m_grades;
protected Time m_timeSubmitted;
protected Time m_timeReturned;
protected Time m_timeLastModified;
protected List m_submittedAttachments;
protected List m_feedbackAttachments;
protected String m_submittedText;
protected String m_feedbackComment;
protected String m_feedbackText;
protected String m_grade;
protected boolean m_submitted;
protected boolean m_returned;
protected boolean m_graded;
protected String m_gradedBy;
protected boolean m_gradeReleased;
protected boolean m_honorPledgeFlag;
protected boolean m_hideDueDate;
//The score given by the review service
protected Integer m_reviewScore;
// The report given by the content review service
protected String m_reviewReport;
// The status of the review service
protected String m_reviewStatus;
protected String m_reviewIconUrl;
protected String m_reviewError;
// return the variables
// Get new values from review service if defaults
public int getReviewScore() {
// Code to get updated score if default
M_log.debug(this + " getReviewScore for submission " + this.getId() + " and review service is: " + (this.getAssignment().getContent().getAllowReviewService()));
if (!this.getAssignment().getContent().getAllowReviewService()) {
M_log.debug(this + " getReviewScore Content review is not enabled for this assignment");
return -2;
}
if (m_submittedAttachments.isEmpty()) {
M_log.debug(this + " getReviewScore No attachments submitted.");
return -2;
}
else
{
//we may have already retrived this one
if (m_reviewScore != null && m_reviewScore > -1) {
M_log.debug("returning stored value of " + m_reviewScore);
return m_reviewScore.intValue();
}
ContentResource cr = getFirstAcceptableAttachement();
if (cr == null )
{
M_log.debug(this + " getReviewScore No suitable attachments found in list");
return -2;
}
try {
//we need to find the first attachment the CR will accept
String contentId = cr.getId();
M_log.debug(this + " getReviewScore checking for score for content: " + contentId);
Long status = contentReviewService.getReviewStatus(contentId);
if (status != null && (status.equals(ContentReviewItem.NOT_SUBMITTED_CODE) || status.equals(ContentReviewItem.SUBMITTED_AWAITING_REPORT_CODE))) {
M_log.debug(this + " getReviewStatus returned a status of: " + status);
return -2;
}
int score = contentReviewService.getReviewScore(contentId);
m_reviewScore = score;
M_log.debug(this + " getReviewScore CR returned a score of: " + score);
return score;
}
catch (QueueException cie) {
//should we add the item
try {
M_log.debug(this + " getReviewScore Item is not in queue we will try add it");
String contentId = cr.getId();
String userId = this.getSubmitterId();
try {
contentReviewService.queueContent(userId, null, getAssignment().getReference(), contentId);
}
catch (QueueException qe) {
M_log.warn(" getReviewScore Unable to queue content with content review Service: " + qe.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
catch (Exception e) {
M_log.warn(this + " getReviewScore " + e.getMessage());
return -1;
}
}
}
public String getReviewReport() {
// Code to get updated report if default
if (m_submittedAttachments.isEmpty()) {
M_log.debug(this.getId() + " getReviewReport No attachments submitted.");
return "Error";
}
else
{
try {
ContentResource cr = getFirstAcceptableAttachement();
if (cr == null )
{
M_log.debug(this + " getReviewReport No suitable attachments found in list");
return "error";
}
String contentId = cr.getId();
if (allowGradeSubmission(getReference()))
return contentReviewService.getReviewReportInstructor(contentId);
else
return contentReviewService.getReviewReportStudent(contentId);
} catch (Exception e) {
M_log.warn(":getReviewReport() " + e.getMessage());
return "Error";
}
}
}
private ContentResource getFirstAcceptableAttachement() {
String contentId = null;
try {
for( int i =0; i < m_submittedAttachments.size();i++ ) {
Reference ref = (Reference)m_submittedAttachments.get(i);
ContentResource contentResource = (ContentResource)ref.getEntity();
if (contentReviewService.isAcceptableContent(contentResource)) {
return (ContentResource)contentResource;
}
}
}
catch (Exception e) {
M_log.warn(":getFirstAcceptableAttachment() " + e.getMessage());
e.printStackTrace();
}
return null;
}
public String getReviewStatus() {
return m_reviewStatus;
}
public String getReviewError() {
// Code to get error report
if (m_submittedAttachments.isEmpty()) {
M_log.debug(this.getId() + " getReviewError No attachments submitted.");
return null;
}
else
{
try {
ContentResource cr = getFirstAcceptableAttachement();
if (cr == null )
{
M_log.debug(this + " getReviewError No suitable attachments found in list");
return null;
}
String contentId = cr.getId();
// This should use getLocalizedReviewErrorMessage(contentId)
// to get a i18n message of the error
Long status = contentReviewService.getReviewStatus(contentId);
String errorMessage = null;
if (status != null) {
if (status.equals(ContentReviewItem.REPORT_ERROR_NO_RETRY_CODE)) {
errorMessage = rb.getString("content_review.error.REPORT_ERROR_NO_RETRY_CODE");
} else if (status.equals(ContentReviewItem.REPORT_ERROR_RETRY_CODE)) {
errorMessage = rb.getString("content_review.error.REPORT_ERROR_RETRY_CODE");
} else if (status.equals(ContentReviewItem.SUBMISSION_ERROR_NO_RETRY_CODE)) {
errorMessage = rb.getString("content_review.error.SUBMISSION_ERROR_NO_RETRY_CODE");
} else if (status.equals(ContentReviewItem.SUBMISSION_ERROR_RETRY_CODE)) {
errorMessage = rb.getString("content_review.error.SUBMISSION_ERROR_RETRY_CODE");
} else if (status.equals(ContentReviewItem.SUBMISSION_ERROR_RETRY_EXCEEDED)) {
errorMessage = rb.getString("content_review.error.SUBMISSION_ERROR_RETRY_EXCEEDED_CODE");
} else if (status.equals(ContentReviewItem.SUBMISSION_ERROR_USER_DETAILS_CODE)) {
errorMessage = rb.getString("content_review.error.SUBMISSION_ERROR_USER_DETAILS_CODE");
} else if (ContentReviewItem.SUBMITTED_AWAITING_REPORT_CODE.equals(status)
|| ContentReviewItem.NOT_SUBMITTED_CODE.equals(status)) {
errorMessage = rb.getString("content_review.pending.info");
}
}
if (errorMessage == null) {
errorMessage = rb.getString("content_review.error");
}
return errorMessage;
} catch (Exception e) {
//e.printStackTrace();
M_log.warn(this + ":getReviewError() " + e.getMessage());
return null;
}
}
}
public String getReviewIconUrl() {
if (m_reviewIconUrl == null )
m_reviewIconUrl = contentReviewService.getIconUrlforScore(Long.valueOf(this.getReviewScore()));
return m_reviewIconUrl;
}
/**
* constructor
*/
public BaseAssignmentSubmission()
{
m_properties = new BaseResourcePropertiesEdit();
}// constructor
/**
* Copy constructor.
*/
public BaseAssignmentSubmission(AssignmentSubmission submission)
{
setAll(submission);
}
/**
* Constructor used by addSubmission.
*/
public BaseAssignmentSubmission(String id, String assignId, String submitterId, String submitTime, String submitted, String graded)
{
// must set initial review status
m_reviewStatus = "";
m_reviewScore = -1;
m_reviewReport = "Not available yet";
m_reviewError = "";
m_id = id;
m_assignment = assignId;
m_properties = new BaseResourcePropertiesEdit();
addLiveProperties(m_properties);
m_submitters = new ArrayList();
m_submissionLog = new ArrayList();
m_grades = new ArrayList();
m_feedbackAttachments = m_entityManager.newReferenceList();
m_submittedAttachments = m_entityManager.newReferenceList();
m_submitted = false;
m_returned = false;
m_graded = false;
m_gradedBy = null;
m_gradeReleased = false;
m_submittedText = "";
m_feedbackComment = "";
m_feedbackText = "";
m_grade = "";
m_timeLastModified = TimeService.newTime();
m_submitterId = submitterId;
if (submitterId == null)
{
String currentUser = SessionManager.getCurrentSessionUserId();
if (currentUser == null) currentUser = "";
m_submitters.add(currentUser);
m_submitterId = currentUser;
}
else
{
m_submitters.add(submitterId);
}
if (submitted != null)
{
m_submitted = Boolean.valueOf(submitted).booleanValue();
}
if (graded != null)
{
m_graded = Boolean.valueOf(graded).booleanValue();
}
}
// todo work out what this does
/**
* Reads the AssignmentSubmission's attribute values from xml.
*
* @param s -
* Data structure holding the xml info.
*/
public BaseAssignmentSubmission(Element el)
{
int numAttributes = 0;
String intString = null;
String attributeString = null;
String tempString = null;
Reference tempReference = null;
M_log.debug(" BaseAssigmentSubmission : ENTERING STORAGE CONSTRUCTOR");
m_id = el.getAttribute("id");
m_context = el.getAttribute("context");
// %%%zqian
// read the scaled grade point first; if there is none, get the old grade value
String grade = StringUtils.trimToNull(el.getAttribute("scaled_grade"));
if (grade == null)
{
grade = StringUtils.trimToNull(el.getAttribute("grade"));
if (grade != null)
{
try
{
Integer.parseInt(grade);
// for the grades in points, multiple those by 10
grade = grade + "0";
}
catch (Exception e)
{
M_log.warn(":BaseAssignmentSubmission(Element el) " + e.getMessage());
}
}
}
m_grade = grade;
m_assignment = el.getAttribute("assignment");
m_timeSubmitted = getTimeObject(el.getAttribute("datesubmitted"));
m_timeReturned = getTimeObject(el.getAttribute("datereturned"));
m_assignment = el.getAttribute("assignment");
m_timeLastModified = getTimeObject(el.getAttribute("lastmod"));
m_submitted = getBool(el.getAttribute("submitted"));
m_returned = getBool(el.getAttribute("returned"));
m_graded = getBool(el.getAttribute("graded"));
m_gradedBy = el.getAttribute("gradedBy");
m_gradeReleased = getBool(el.getAttribute("gradereleased"));
m_honorPledgeFlag = getBool(el.getAttribute("pledgeflag"));
m_hideDueDate = getBool(el.getAttribute("hideduedate"));
m_submittedText = FormattedText.decodeFormattedTextAttribute(el, "submittedtext");
m_feedbackComment = FormattedText.decodeFormattedTextAttribute(el, "feedbackcomment");
m_feedbackText = FormattedText.decodeFormattedTextAttribute(el, "feedbacktext");
m_submitterId = el.getAttribute("submitterid");
m_submissionLog = new ArrayList();
m_grades = new ArrayList();
intString = el.getAttribute("numberoflogs");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "log" + x;
tempString = el.getAttribute(attributeString);
if (tempString != null) m_submissionLog.add(tempString);
}
}
catch (Exception e)
{
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : Exception reading logs : " + e);
}
intString = el.getAttribute("numberofgrades");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "grade" + x;
tempString = el.getAttribute(attributeString);
if (tempString != null) m_grades.add(tempString);
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission: CONSTRUCTOR : Exception reading grades : " + e);
}
// READ THE SUBMITTERS
m_submitters = new ArrayList();
M_log.debug(" BaseAssignmentSubmission : CONSTRUCTOR : Reading submitters : ");
intString = el.getAttribute("numberofsubmitters");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "submitter" + x;
tempString = el.getAttribute(attributeString);
if (tempString != null) m_submitters.add(tempString);
}
}
catch (Exception e)
{
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : Exception reading submitters : " + e);
}
// READ THE FEEDBACK ATTACHMENTS
m_feedbackAttachments = m_entityManager.newReferenceList();
intString = el.getAttribute("numberoffeedbackattachments");
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : num feedback attachments : " + intString);
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "feedbackattachment" + x;
tempString = el.getAttribute(attributeString);
if (tempString != null)
{
tempReference = m_entityManager.newReference(tempString);
m_feedbackAttachments.add(tempReference);
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : " + attributeString + " : "
+ tempString);
}
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission: CONSTRUCTOR : Exception reading feedback attachments : " + e);
}
// READ THE SUBMITTED ATTACHMENTS
m_submittedAttachments = m_entityManager.newReferenceList();
intString = el.getAttribute("numberofsubmittedattachments");
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : num submitted attachments : " + intString);
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "submittedattachment" + x;
tempString = el.getAttribute(attributeString);
if (tempString != null)
{
tempReference = m_entityManager.newReference(tempString);
m_submittedAttachments.add(tempReference);
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : " + attributeString + " : "
+ tempString);
}
}
}
catch (Exception e)
{
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : Exception reading submitted attachments : " + e);
}
// READ THE PROPERTIES, SUBMITTED TEXT, FEEDBACK COMMENT, FEEDBACK TEXT
NodeList children = el.getChildNodes();
final int length = children.getLength();
for (int i = 0; i < length; i++)
{
Node child = children.item(i);
if (child.getNodeType() != Node.ELEMENT_NODE) continue;
Element element = (Element) child;
// look for properties
if (element.getTagName().equals("properties"))
{
// re-create properties
m_properties = new BaseResourcePropertiesEdit(element);
}
// old style encoding
else if (element.getTagName().equals("submittedtext"))
{
if ((element.getChildNodes() != null) && (element.getChildNodes().item(0) != null))
{
m_submittedText = element.getChildNodes().item(0).getNodeValue();
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : submittedtext : " + m_submittedText);
}
if (m_submittedText == null)
{
m_submittedText = "";
}
}
// old style encoding
else if (element.getTagName().equals("feedbackcomment"))
{
if ((element.getChildNodes() != null) && (element.getChildNodes().item(0) != null))
{
m_feedbackComment = element.getChildNodes().item(0).getNodeValue();
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : feedbackcomment : "
+ m_feedbackComment);
}
if (m_feedbackComment == null)
{
m_feedbackComment = "";
}
}
// old style encoding
else if (element.getTagName().equals("feedbacktext"))
{
if ((element.getChildNodes() != null) && (element.getChildNodes().item(0) != null))
{
m_feedbackText = element.getChildNodes().item(0).getNodeValue();
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : FEEDBACK TEXT : " + m_feedbackText);
}
if (m_feedbackText == null)
{
m_feedbackText = "";
}
}
}
try {
if (el.getAttribute("reviewScore")!=null)
m_reviewScore = Integer.parseInt(el.getAttribute("reviewScore"));
else
m_reviewScore = -1;
}
catch (NumberFormatException nfe) {
m_reviewScore = -1;
M_log.warn(":BaseAssignmentSubmission(Element) " + nfe.getMessage());
}
try {
// The report given by the content review service
if (el.getAttribute("reviewReport")!=null)
m_reviewReport = el.getAttribute("reviewReport");
else
m_reviewReport = "no report available";
// The status of the review service
if (el.getAttribute("reviewStatus")!=null)
m_reviewStatus = el.getAttribute("reviewStatus");
else
m_reviewStatus = "";
// The status of the review service
if (el.getAttribute("reviewError")!=null)
m_reviewError = el.getAttribute("reviewError");
else
m_reviewError = "";
}
catch (Exception e) {
M_log.error("error constructing Submission: " + e);
}
//get the review Status from ContentReview rather than using old ones
if (contentReviewService != null) {
m_reviewStatus = this.getReviewStatus();
m_reviewScore = this.getReviewScore();
m_reviewError = this.getReviewError();
}
M_log.debug(" BaseAssignmentSubmission: LEAVING STORAGE CONSTRUCTOR");
}// storage constructor
/**
* @param services
* @return
*/
public ContentHandler getContentHandler(Map<String, Object> services)
{
final Entity thisEntity = this;
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.DefaultEntityHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String,
* org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if ("submission".equals(qName) && entity == null)
{
try {
if (StringUtils.trimToNull(attributes.getValue("reviewScore"))!=null)
m_reviewScore = Integer.parseInt(attributes.getValue("reviewScore"));
else
m_reviewScore = -1;
}
catch (NumberFormatException nfe) {
m_reviewScore = -1;
M_log.warn(":AssignmentSubmission:getContentHandler:DefaultEntityHandler " + nfe.getMessage());
}
try {
// The report given by the content review service
if (attributes.getValue("reviewReport")!=null)
m_reviewReport = attributes.getValue("reviewReport");
else
m_reviewReport = "no report available";
// The status of the review service
if (attributes.getValue("reviewStatus")!=null)
m_reviewStatus = attributes.getValue("reviewStatus");
else
m_reviewStatus = "";
// The status of the review service
if (attributes.getValue("reviewError")!=null) {
m_reviewError = attributes.getValue("reviewError");
} else {
m_reviewError = "";
}
}
catch (Exception e) {
M_log.error("error constructing Submission: " + e);
}
int numAttributes = 0;
String intString = null;
String attributeString = null;
String tempString = null;
Reference tempReference = null;
m_id = attributes.getValue("id");
// M_log.info(this + " BASE SUBMISSION : CONSTRUCTOR : m_id : " + m_id);
m_context = attributes.getValue("context");
// M_log.info(this + " BASE SUBMISSION : CONSTRUCTOR : m_context : " + m_context);
// %%%zqian
// read the scaled grade point first; if there is none, get the old grade value
String grade = StringUtils.trimToNull(attributes.getValue("scaled_grade"));
if (grade == null)
{
grade = StringUtils.trimToNull(attributes.getValue("grade"));
if (grade != null)
{
try
{
Integer.parseInt(grade);
// for the grades in points, multiple those by 10
grade = grade + "0";
}
catch (Exception e)
{
M_log.warn(":BaseAssignmentSubmission:getContentHanler:DefaultEnityHandler " + e.getMessage());
}
}
}
m_grade = grade;
m_assignment = attributes.getValue("assignment");
m_timeSubmitted = getTimeObject(attributes.getValue("datesubmitted"));
m_timeReturned = getTimeObject(attributes.getValue("datereturned"));
m_assignment = attributes.getValue("assignment");
m_timeLastModified = getTimeObject(attributes.getValue("lastmod"));
m_submitted = getBool(attributes.getValue("submitted"));
m_returned = getBool(attributes.getValue("returned"));
m_graded = getBool(attributes.getValue("graded"));
m_gradedBy = attributes.getValue("gradedBy");
m_gradeReleased = getBool(attributes.getValue("gradereleased"));
m_honorPledgeFlag = getBool(attributes.getValue("pledgeflag"));
m_hideDueDate = getBool(attributes.getValue("hideduedate"));
m_submittedText = formattedTextDecodeFormattedTextAttribute(attributes, "submittedtext");
m_feedbackComment = formattedTextDecodeFormattedTextAttribute(attributes, "feedbackcomment");
m_feedbackText = formattedTextDecodeFormattedTextAttribute(attributes, "feedbacktext");
m_submitterId = attributes.getValue("submitterid");
m_submissionLog = new ArrayList();
m_grades = new ArrayList();
intString = attributes.getValue("numberoflogs");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "log" + x;
tempString = attributes.getValue(attributeString);
if (tempString != null) {
m_submissionLog.add(tempString);
}
}
}
catch (Exception e)
{
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : Exception reading logs : " + e);
}
intString = attributes.getValue("numberofgrades");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "grade" + x;
tempString = attributes.getValue(attributeString);
if (tempString != null) m_grades.add(tempString);
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission: CONSTRUCTOR : Exception reading logs : " + e);
}
// READ THE SUBMITTERS
m_submitters = new ArrayList();
intString = attributes.getValue("numberofsubmitters");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "submitter" + x;
tempString = attributes.getValue(attributeString);
if (tempString != null) {
m_submitters.add(tempString);
}
// for backward compatibility of assignments without submitter ids
if (m_submitterId == null) {
m_submitterId = tempString;
}
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission getContentHandler : Exception reading submitters : " + e);
}
// READ THE FEEDBACK ATTACHMENTS
m_feedbackAttachments = m_entityManager.newReferenceList();
intString = attributes.getValue("numberoffeedbackattachments");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "feedbackattachment" + x;
tempString = attributes.getValue(attributeString);
if (tempString != null)
{
tempReference = m_entityManager.newReference(tempString);
m_feedbackAttachments.add(tempReference);
}
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission getContentHandler : Exception reading feedback attachments : " + e);
}
// READ THE SUBMITTED ATTACHMENTS
m_submittedAttachments = m_entityManager.newReferenceList();
intString = attributes.getValue("numberofsubmittedattachments");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "submittedattachment" + x;
tempString = attributes.getValue(attributeString);
if (tempString != null)
{
tempReference = m_entityManager.newReference(tempString);
m_submittedAttachments.add(tempReference);
}
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission getContentHandler: Exception reading submitted attachments : " + e);
}
entity = thisEntity;
}
}
}
};
}
/**
* Takes the AssignmentContent's attribute values and puts them into the xml document.
*
* @param s -
* Data structure holding the object to be stored.
* @param doc -
* The xml document.
*/
public Element toXml(Document doc, Stack stack)
{
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission : ENTERING TOXML");
Element submission = doc.createElement("submission");
if (stack.isEmpty())
{
doc.appendChild(submission);
}
else
{
((Element) stack.peek()).appendChild(submission);
}
stack.push(submission);
String numItemsString = null;
String attributeString = null;
String itemString = null;
Reference tempReference = null;
// SAK-13408 -The XML implementation in Websphere throws an LSException if the
// attribute is null, while in Tomcat it assumes an empty string. The following
// sets the attribute to an empty string if the value is null.
submission.setAttribute("reviewScore",m_reviewScore == null ? "" : Integer.toString(m_reviewScore));
submission.setAttribute("reviewReport",m_reviewReport == null ? "" : m_reviewReport);
submission.setAttribute("reviewStatus",m_reviewStatus == null ? "" : m_reviewStatus);
submission.setAttribute("reviewError",m_reviewError == null ? "" : m_reviewError);
submission.setAttribute("id", m_id == null ? "" : m_id);
submission.setAttribute("context", m_context == null ? "" : m_context);
submission.setAttribute("scaled_grade", m_grade == null ? "" : m_grade);
submission.setAttribute("assignment", m_assignment == null ? "" : m_assignment);
submission.setAttribute("datesubmitted", getTimeString(m_timeSubmitted));
submission.setAttribute("datereturned", getTimeString(m_timeReturned));
submission.setAttribute("lastmod", getTimeString(m_timeLastModified));
submission.setAttribute("submitted", getBoolString(m_submitted));
submission.setAttribute("returned", getBoolString(m_returned));
submission.setAttribute("graded", getBoolString(m_graded));
submission.setAttribute("gradedBy", m_gradedBy == null ? "" : m_gradedBy);
submission.setAttribute("gradereleased", getBoolString(m_gradeReleased));
submission.setAttribute("pledgeflag", getBoolString(m_honorPledgeFlag));
submission.setAttribute("hideduedate", getBoolString(m_hideDueDate));
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: SAVED REGULAR PROPERTIES");
submission.setAttribute("submitterid", m_submitterId == null ? "": m_submitterId);
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: SAVED SUBMITTER ID : " + m_submitterId);
numItemsString = "" + m_submissionLog.size();
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: # logs " + numItemsString);
submission.setAttribute("numberoflogs", numItemsString);
for (int x = 0; x < m_submissionLog.size(); x++)
{
attributeString = "log" + x;
itemString = (String) m_submissionLog.get(x);
if (itemString != null) {
submission.setAttribute(attributeString, itemString);
}
}
numItemsString = "" + m_grades.size();
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: # grades " + numItemsString);
submission.setAttribute("numberofgrades", numItemsString);
for (int x = 0; x < m_grades.size(); x++)
{
attributeString = "grade" + x;
itemString = (String) m_grades.get(x);
if (itemString != null) {
submission.setAttribute(attributeString, itemString);
}
}
// SAVE THE SUBMITTERS
numItemsString = "" + m_submitters.size();
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: # submitters " + numItemsString);
submission.setAttribute("numberofsubmitters", numItemsString);
for (int x = 0; x < m_submitters.size(); x++)
{
attributeString = "submitter" + x;
itemString = (String) m_submitters.get(x);
if (itemString != null) {
submission.setAttribute(attributeString, itemString);
}
}
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: SAVED SUBMITTERS");
// SAVE THE FEEDBACK ATTACHMENTS
numItemsString = "" + m_feedbackAttachments.size();
submission.setAttribute("numberoffeedbackattachments", numItemsString);
if (M_log.isDebugEnabled()) M_log.debug("DB : DbCachedStorage : DbCachedAssignmentSubmission : entering fb attach loop : size : "
+ numItemsString);
for (int x = 0; x < m_feedbackAttachments.size(); x++)
{
attributeString = "feedbackattachment" + x;
tempReference = (Reference) m_feedbackAttachments.get(x);
itemString = tempReference.getReference();
if (itemString != null) {
submission.setAttribute(attributeString, itemString);
}
}
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: SAVED FEEDBACK ATTACHMENTS");
// SAVE THE SUBMITTED ATTACHMENTS
numItemsString = "" + m_submittedAttachments.size();
submission.setAttribute("numberofsubmittedattachments", numItemsString);
for (int x = 0; x < m_submittedAttachments.size(); x++)
{
attributeString = "submittedattachment" + x;
tempReference = (Reference) m_submittedAttachments.get(x);
itemString = tempReference.getReference();
if (itemString != null) {
submission.setAttribute(attributeString, itemString);
}
}
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: SAVED SUBMITTED ATTACHMENTS");
// SAVE THE PROPERTIES
m_properties.toXml(doc, stack);
stack.pop();
FormattedText.encodeFormattedTextAttribute(submission, "submittedtext", m_submittedText);
FormattedText.encodeFormattedTextAttribute(submission, "feedbackcomment", m_feedbackComment);
FormattedText.encodeFormattedTextAttribute(submission, "feedbacktext", m_feedbackText);
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: LEAVING TOXML");
return submission;
}// toXml
protected void setAll(AssignmentSubmission submission)
{
if (contentReviewService != null) {
m_reviewScore = submission.getReviewScore();
// The report given by the content review service
m_reviewReport = submission.getReviewReport();
// The status of the review service
m_reviewStatus = submission.getReviewStatus();
// Error msg, if any from review service
m_reviewError = submission.getReviewError();
}
m_id = submission.getId();
m_context = submission.getContext();
m_assignment = submission.getAssignmentId();
m_grade = submission.getGrade();
m_submitters = submission.getSubmitterIds();
m_submitted = submission.getSubmitted();
m_timeSubmitted = submission.getTimeSubmitted();
m_timeReturned = submission.getTimeReturned();
m_timeLastModified = submission.getTimeLastModified();
m_submittedAttachments = submission.getSubmittedAttachments();
m_feedbackAttachments = submission.getFeedbackAttachments();
m_submittedText = submission.getSubmittedText();
m_submitterId = submission.getSubmitterId();
m_submissionLog = submission.getSubmissionLog();
m_grades = submission.getGrades();
m_feedbackComment = submission.getFeedbackComment();
m_feedbackText = submission.getFeedbackText();
m_returned = submission.getReturned();
m_graded = submission.getGraded();
m_gradedBy = submission.getGradedBy();
m_gradeReleased = submission.getGradeReleased();
m_honorPledgeFlag = submission.getHonorPledgeFlag();
m_properties = new BaseResourcePropertiesEdit();
m_properties.addAll(submission.getProperties());
}
/**
* Access the URL which can be used to access the resource.
*
* @return The URL which can be used to access the resource.
*/
public String getUrl()
{
return getAccessPoint(false) + Entity.SEPARATOR + "s" + Entity.SEPARATOR + m_context + Entity.SEPARATOR + m_id;
} // getUrl
/**
* Access the internal reference which can be used to access the resource from within the system.
*
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String getReference()
{
return submissionReference(m_context, m_id, m_assignment);
} // getReference
/**
* @inheritDoc
*/
public String getReference(String rootProperty)
{
return getReference();
}
/**
* @inheritDoc
*/
public String getUrl(String rootProperty)
{
return getUrl();
}
/**
* Access the id of the resource.
*
* @return The id.
*/
public String getId()
{
return m_id;
}
/**
* Access the resource's properties.
*
* @return The resource's properties.
*/
public ResourceProperties getProperties()
{
return m_properties;
}
/******************************************************************************************************************************************************************************************************************************************************
* AssignmentSubmission implementation
*****************************************************************************************************************************************************************************************************************************************************/
/**
* Access the AssignmentSubmission's context at the time of creation.
*
* @return String - the context string.
*/
public String getContext()
{
return m_context;
}
/**
* Access the Assignment for this Submission
*
* @return the Assignment
*/
public Assignment getAssignment()
{
Assignment retVal = null;
if (m_assignment != null)
{
retVal = m_assignmentStorage.get(m_assignment);
}
// track event
//EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT, retVal.getReference(), false));
return retVal;
}
/**
* Access the Id for the Assignment for this Submission
*
* @return String - the Assignment Id
*/
public String getAssignmentId()
{
return m_assignment;
}
/**
* Get whether this is a final submission.
*
* @return True if a final submission, false if still a draft.
*/
public boolean getSubmitted()
{
return m_submitted;
}
public String getSubmitterId() {
return m_submitterId;
}
public List getSubmissionLog() {
return m_submissionLog;
}
public List getGrades() {
return m_grades;
}
public String getGradeForUser(String id) {
if (m_grades != null) {
Iterator<String> _it = m_grades.iterator();
while (_it.hasNext()) {
String _s = _it.next();
if (_s.startsWith(id + "::")) {
return _s.endsWith("null") ? null: _s.substring(_s.indexOf("::") + 2);
}
}
}
return null;
}
/**
*
* @return Array of User objects.
*/
public User[] getSubmitters() {
List retVal = new ArrayList();
Assignment a = getAssignment();
if (a.isGroup()) {
try {
Site site = SiteService.getSite(a.getContext());
Group _g = site.getGroup(m_submitterId);
if (_g != null) {
Iterator<Member> _members = _g.getMembers().iterator();
while (_members.hasNext()) {
Member _member = _members.next();
try
{
retVal.add(UserDirectoryService.getUser(_member.getUserId()));
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission Group getSubmitters" + e.getMessage() + _member.getUserId());
}
}
}
} catch (IdUnusedException _iue) {
throw new IllegalStateException("Site ("+a.getContext()+") not found: "+_iue, _iue);
}
} else {
for (int x = 0; x < m_submitters.size(); x++)
{
String userId = (String) m_submitters.get(x);
try
{
retVal.add(UserDirectoryService.getUser(userId));
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission getSubmitters" + e.getMessage() + userId);
}
}
}
// compare users on sortname
java.util.Collections.sort(retVal, new UserComparator());
// get the User[] array
int size = retVal.size();
User[] rv = new User[size];
for(int k = 0; k<size; k++)
{
rv[k] = (User) retVal.get(k);
}
return rv;
}
/**
* Access the list of Users who submitted this response to the Assignment.
*
* @return FlexStringArray of user ids.
*/
public List getSubmitterIds()
{
Assignment a = getAssignment();
if (a.isGroup()) {
List retVal = new ArrayList();
try {
Site site = SiteService.getSite(a.getContext());
Group _g = site.getGroup(m_submitterId);
if (_g != null) {
Iterator<Member> _members = _g.getMembers().iterator();
while (_members.hasNext()) {
Member _member = _members.next();
retVal.add(_member.getUserId());
}
}
return retVal;
} catch (IdUnusedException _iue) {
return null;
}
} else {
return m_submitters;
}
}
/**
* {@inheritDoc}
*/
public String getSubmitterIdString ()
{
String rv = "";
if (m_submitters != null)
{
for (int j = 0; j < m_submitters.size(); j++)
{
rv = rv.concat((String) m_submitters.get(j));
}
}
return rv;
}
/**
* Set the time at which this response was submitted; null signifies the response is unsubmitted.
*
* @return Time of submission.
*/
public Time getTimeSubmitted()
{
return m_timeSubmitted;
}
/**
* @inheritDoc
*/
public String getTimeSubmittedString()
{
if ( m_timeSubmitted == null )
return "";
else
return m_timeSubmitted.toStringLocalFull();
}
/**
* Get whether the grade has been released.
*
* @return True if the Submissions's grade has been released, false otherwise.
*/
public boolean getGradeReleased()
{
return m_gradeReleased;
}
/**
* Access the grade recieved.
*
* @return The Submission's grade..
*/
public String getGrade()
{
return getGrade(true);
}
/**
* {@inheritDoc}
*/
public String getGrade(boolean overrideWithGradebookValue)
{
String rv = m_grade;
if (!overrideWithGradebookValue)
{
// use assignment submission grade
return m_grade;
}
else
{
// use grade from associated Gradebook
Assignment m = getAssignment();
String gAssignmentName = StringUtils.trimToNull(m.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
if (gAssignmentName != null)
{
GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = m.getContext();
// return student score from Gradebook
String userId = m_submitterId;
SecurityAdvisor securityAdvisor = new MySecurityAdvisor(
SessionManager.getCurrentSessionUserId(),
new ArrayList<String>(Arrays.asList("gradebook.gradeAll", "gradebook.gradeSection", "gradebook.editAssignments", "gradebook.viewOwnGrades")),
gradebookUid);
try
{
// add the grade permission ("gradebook.gradeAll", "gradebook.gradeSection", "gradebook.editAssignments", or "gradebook.viewOwnGrades") in order to use g.getAssignmentScoreString()
securityService.pushAdvisor(securityAdvisor);
if (g.isGradebookDefined(gradebookUid) && g.isAssignmentDefined(gradebookUid, gAssignmentName))
{
String gString = StringUtils.trimToNull(g.getAssignmentScoreString(gradebookUid, gAssignmentName, userId));
if (gString != null)
{
rv = gString;
}
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission getGrade getAssignmentScoreString from GradebookService " + e.getMessage() + " context=" + m_context + " assignment id=" + m_assignment + " userId=" + userId + " gAssignmentName=" + gAssignmentName);
}
finally
{
// remove advisor
securityService.popAdvisor(securityAdvisor);
}
}
}
return rv;
}
/**
* Access the grade recieved.
*
* @return The Submission's grade..
*/
public String getGradeDisplay()
{
Assignment m = getAssignment();
String grade = getGrade();
if (m.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE)
{
if (grade != null && grade.length() > 0 && !"0".equals(grade))
{
String one_decimal_gradePoint = "";
try
{
Integer.parseInt(grade);
// if point grade, display the grade with one decimal place
one_decimal_gradePoint = grade.substring(0, grade.length() - 1) + "." + grade.substring(grade.length() - 1);
}
catch (NumberFormatException e) {
try {
Float.parseFloat(grade);
one_decimal_gradePoint = grade;
}
catch (Exception e1) {
return grade;
}
}
// get localized number format
NumberFormat nbFormat = NumberFormat.getInstance();
try {
Locale locale = null;
ResourceLoader rb = new ResourceLoader();
locale = rb.getLocale();
nbFormat = NumberFormat.getNumberInstance(locale);
}
catch (Exception e) {
M_log.warn("Error while retrieving local number format, using default ", e);
}
nbFormat.setMaximumFractionDigits(1);
nbFormat.setMinimumFractionDigits(1);
nbFormat.setGroupingUsed(false);
// show grade in localized number format
try {
Double dblGrade = new Double(one_decimal_gradePoint);
one_decimal_gradePoint = nbFormat.format(dblGrade);
}
catch (Exception e) {
return grade;
}
return one_decimal_gradePoint;
}
else
{
return StringUtils.trimToEmpty(grade);
}
}
else if (m.getContent().getTypeOfGrade() == Assignment.UNGRADED_GRADE_TYPE) {
String ret = "";
if (grade != null) {
if (grade.equalsIgnoreCase("gen.nograd")) ret = rb.getString("gen.nograd");
}
return ret;
}
else if (m.getContent().getTypeOfGrade() == Assignment.PASS_FAIL_GRADE_TYPE) {
String ret = rb.getString("ungra");
if (grade != null) {
if (grade.equalsIgnoreCase("Pass")) ret = rb.getString("pass");
else if (grade.equalsIgnoreCase("Fail")) ret = rb.getString("fail");
}
return ret;
}
else if (m.getContent().getTypeOfGrade() == Assignment.CHECK_GRADE_TYPE) {
String ret = rb.getString("ungra");
if (grade != null) {
if (grade.equalsIgnoreCase("Checked")) ret = rb.getString("gen.checked");
}
return ret;
}
else
{
if (grade != null && grade.length() > 0)
{
return StringUtils.trimToEmpty(grade);
}
else
{
// return "ungraded" in stead
return rb.getString("ungra");
}
}
}
/**
* Get the time of last modification;
*
* @return The time of last modification.
*/
public Time getTimeLastModified()
{
return m_timeLastModified;
}
/**
* Text submitted in response to the Assignment.
*
* @return The text of the submission.
*/
public String getSubmittedText()
{
return m_submittedText;
}
/**
* Access the list of attachments to this response to the Assignment.
*
* @return ReferenceVector of the list of attachments as Reference objects;
*/
public List getSubmittedAttachments()
{
return m_submittedAttachments;
}
/**
* Get the general comments by the grader
*
* @return The text of the grader's comments; may be null.
*/
public String getFeedbackComment()
{
return m_feedbackComment;
}
/**
* Access the text part of the instructors feedback; usually an annotated copy of the submittedText
*
* @return The text of the grader's feedback.
*/
public String getFeedbackText()
{
return m_feedbackText;
}
/**
* Access the formatted text part of the instructors feedback; usually an annotated copy of the submittedText
*
* @return The formatted text of the grader's feedback.
*/
public String getFeedbackFormattedText()
{
if (m_feedbackText == null || m_feedbackText.length() == 0)
return m_feedbackText;
String value = fixAssignmentFeedback(m_feedbackText);
StringBuffer buf = new StringBuffer(value);
int pos = -1;
while ((pos = buf.indexOf("{{")) != -1)
{
buf.replace(pos, pos + "{{".length(), "<span class='highlight'>");
}
while ((pos = buf.indexOf("}}")) != -1)
{
buf.replace(pos, pos + "}}".length(), "</span>");
}
return FormattedText.escapeHtmlFormattedText(buf.toString());
}
/**
* Apply the fix to pre 1.1.05 assignments submissions feedback.
*/
private String fixAssignmentFeedback(String value)
{
if (value == null || value.length() == 0) return value;
StringBuffer buf = new StringBuffer(value);
int pos = -1;
// <br/> -> \n
while ((pos = buf.indexOf("<br/>")) != -1)
{
buf.replace(pos, pos + "<br/>".length(), "\n");
}
// <span class='chefAlert'>( -> {{
while ((pos = buf.indexOf("<span class='chefAlert'>(")) != -1)
{
buf.replace(pos, pos + "<span class='chefAlert'>(".length(), "{{");
}
// )</span> -> }}
while ((pos = buf.indexOf(")</span>")) != -1)
{
buf.replace(pos, pos + ")</span>".length(), "}}");
}
while ((pos = buf.indexOf("<ins>")) != -1)
{
buf.replace(pos, pos + "<ins>".length(), "{{");
}
while ((pos = buf.indexOf("</ins>")) != -1)
{
buf.replace(pos, pos + "</ins>".length(), "}}");
}
return buf.toString();
} // fixAssignmentFeedback
/**
* Access the list of attachments returned to the students in the process of grading this assignment; usually a modified or annotated version of the attachment submitted.
*
* @return ReferenceVector of the Resource objects pointing to the attachments.
*/
public List getFeedbackAttachments()
{
return m_feedbackAttachments;
}
/**
* Get whether this Submission was rejected by the grader.
*
* @return True if this response was rejected by the grader, false otherwise.
*/
public boolean getReturned()
{
return m_returned;
}
/**
* Get whether this Submission has been graded.
*
* @return True if the submission has been graded, false otherwise.
*/
public boolean getGraded()
{
return m_graded;
}
/**
* Get the grader id (used to determine auto or instructor grading)
*/
public String getGradedBy(){
return m_gradedBy;
}
/**
* Get the time on which the graded submission was returned; null means the response is not yet graded.
*
* @return the time (may be null)
*/
public Time getTimeReturned()
{
return m_timeReturned;
}
/**
* Access the checked status of the honor pledge flag.
*
* @return True if the honor pledge is checked, false otherwise.
*/
public boolean getHonorPledgeFlag()
{
return m_honorPledgeFlag;
}
/**
* Returns the status of the submission : Not Started, submitted, returned or graded.
*
* @return The Submission's status.
*/
public String getStatus()
{
Assignment assignment = getAssignment();
boolean allowGrade = assignment != null ? allowGradeSubmission(assignment.getReference()):false;
String retVal = "";
Time submitTime = getTimeSubmitted();
Time returnTime = getTimeReturned();
Time lastModTime = getTimeLastModified();
if (getSubmitted() || (!getSubmitted() && allowGrade))
{
if (submitTime != null)
{
if (getReturned())
{
if (returnTime != null && returnTime.before(submitTime))
{
if (!getGraded())
{
retVal = rb.getString("gen.resub") + " " + submitTime.toStringLocalFull();
if (submitTime.after(getAssignment().getDueTime()))
retVal = retVal + rb.getString("gen.late2");
}
else
retVal = rb.getString("gen.returned");
}
else
retVal = rb.getString("gen.returned");
}
else if (getGraded() && allowGrade)
{
retVal = getGradeOrComment();
}
else
{
if (allowGrade)
{
// ungraded submission
retVal = rb.getString("ungra");
}
else
{
// submitted
retVal = rb.getString("gen.subm4");
if(submitTime != null)
{
retVal = rb.getString("gen.subm4") + " " + submitTime.toStringLocalFull();
}
}
}
}
else
{
if (getReturned())
{
// instructor can return grading to non-submitted user
retVal = rb.getString("gen.returned");
}
else if (getGraded() && allowGrade)
{
// instructor can grade non-submitted ones
retVal = getGradeOrComment();
}
else
{
if (allowGrade)
{
// show "no submission" to graders
retVal = rb.getString("listsub.nosub");
}
else
{
// show "not started" to students
retVal = rb.getString("gen.notsta");
}
}
}
}
else
{
if (getGraded())
{
if (getReturned())
{
if (lastModTime != null && returnTime != null && lastModTime.after(TimeService.newTime(returnTime.getTime() + 1000 * 10)) && !allowGrade)
{
// working on a returned submission now
retVal = rb.getString("gen.dra2") + " " + rb.getString("gen.inpro");
}
else
{
// not submitted submmission has been graded and returned
retVal = rb.getString("gen.returned");
}
}
else if (allowGrade){
// grade saved but not release yet, show this to graders
retVal = getGradeOrComment();
}else{
// submission saved, not submitted.
retVal = rb.getString("gen.dra2") + " " + rb.getString("gen.inpro");
}
}
else
{
if (allowGrade)
retVal = rb.getString("ungra");
else
// submission saved, not submitted.
retVal = rb.getString("gen.dra2") + " " + rb.getString("gen.inpro");
}
}
return retVal;
}
private String getGradeOrComment() {
String retVal;
if (getGrade() != null && getGrade().length() > 0)
retVal = rb.getString("grad3");
else
retVal = rb.getString("gen.commented");
return retVal;
}
/**
* Are these objects equal? If they are both AssignmentSubmission objects, and they have matching id's, they are.
*
* @return true if they are equal, false if not.
*/
public boolean equals(Object obj)
{
if (!(obj instanceof AssignmentSubmission)) return false;
return ((AssignmentSubmission) obj).getId().equals(getId());
} // equals
/**
* Make a hash code that reflects the equals() logic as well. We want two objects, even if different instances, if they have the same id to hash the same.
*/
public int hashCode()
{
return getId().hashCode();
} // hashCode
/**
* Compare this object with the specified object for order.
*
* @return A negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
*/
public int compareTo(Object obj)
{
if (!(obj instanceof AssignmentSubmission)) throw new ClassCastException();
// if the object are the same, say so
if (obj == this) return 0;
// start the compare by comparing their sort names
int compare = getTimeSubmitted().toString().compareTo(((AssignmentSubmission) obj).getTimeSubmitted().toString());
// if these are the same
if (compare == 0)
{
// sort based on (unique) id
compare = getId().compareTo(((AssignmentSubmission) obj).getId());
}
return compare;
} // compareTo
/**
* {@inheritDoc}
*/
public int getResubmissionNum()
{
String numString = StringUtils.trimToNull(m_properties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
return numString != null?Integer.valueOf(numString).intValue():0;
}
/**
* {@inheritDoc}
*/
public Time getCloseTime()
{
String closeTimeString = StringUtils.trimToNull(m_properties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME));
if (closeTimeString != null && getResubmissionNum() != 0)
{
// return the close time if it is set
return TimeService.newTime(Long.parseLong(closeTimeString));
}
else
{
// else use the assignment close time setting
Assignment a = getAssignment();
return a!=null?a.getCloseTime():null;
}
}
} // AssignmentSubmission
/***************************************************************************
* AssignmentSubmissionEdit implementation
**************************************************************************/
/**
* <p>
* BaseAssignmentSubmissionEdit is an implementation of the CHEF AssignmentSubmissionEdit object.
* </p>
*
* @author University of Michigan, CHEF Software Development Team
*/
public class BaseAssignmentSubmissionEdit extends BaseAssignmentSubmission implements AssignmentSubmissionEdit,
SessionBindingListener
{
/** The event code for this edit. */
protected String m_event = null;
/** Active flag. */
protected boolean m_active = false;
/**
* Construct from another AssignmentSubmission object.
*
* @param AssignmentSubmission
* The AssignmentSubmission object to use for values.
*/
public BaseAssignmentSubmissionEdit(AssignmentSubmission assignmentSubmission)
{
super(assignmentSubmission);
} // BaseAssignmentSubmissionEdit
/**
* Construct.
*
* @param id
* The AssignmentSubmission id.
*/
public BaseAssignmentSubmissionEdit(String id, String assignmentId, String submitterId, String submitTime, String submitted, String graded)
{
super(id, assignmentId, submitterId, submitTime, submitted, graded);
} // BaseAssignmentSubmissionEdit
/**
* Construct from information in XML.
*
* @param el
* The XML DOM Element definining the AssignmentSubmission.
*/
public BaseAssignmentSubmissionEdit(Element el)
{
super(el);
} // BaseAssignmentSubmissionEdit
/**
* Clean up.
*/
protected void finalize()
{
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelEdit(this);
}
} // finalize
/**
* Set the context at the time of creation.
*
* @param context -
* the context string.
*/
public void setContext(String context)
{
m_context = context;
}
/**
* Set the Assignment for this Submission
*
* @param assignment -
* the Assignment
*/
public void setAssignment(Assignment assignment)
{
if (assignment != null)
{
m_assignment = assignment.getId();
}
else
m_assignment = "";
}
/**
* Set whether this is a final submission.
*
* @param submitted -
* True if a final submission, false if still a draft.
*/
public void setSubmitted(boolean submitted)
{
m_submitted = submitted;
}
/**
* Add a User to the submitters list.
*
* @param submitter -
* the User to add.
*/
public void addSubmitter(User submitter)
{
if (submitter != null) m_submitters.add(submitter.getId());
}
public void setSubmitterId(String id) {
m_submitterId = id;
}
public void addSubmissionLogEntry(String entry) {
if (m_submissionLog != null) m_submissionLog.add(entry);
}
public void addGradeForUser(String uid, String grade) {
if (m_grades != null)
{
Iterator<String> _it = m_grades.iterator();
while (_it.hasNext()) {
String _val = _it.next();
if (_val.startsWith(uid + "::")) {
m_grades.remove(_val);
break;
}
}
if (grade != null && !(grade.equals("null"))) {
m_grades.add(uid + "::" + grade);
}
}
}
/**
* Remove an User from the submitter list
*
* @param submitter -
* the User to remove.
*/
public void removeSubmitter(User submitter)
{
if (submitter != null) m_submitters.remove(submitter.getId());
}
/**
* Remove all user from the submitter list
*/
public void clearSubmitters()
{
m_submitters.clear();
}
/**
* Set the time at which this response was submitted; setting it to null signifies the response is unsubmitted.
*
* @param timeSubmitted -
* Time of submission.
*/
public void setTimeSubmitted(Time value)
{
m_timeSubmitted = value;
}
/**
* Set whether the grade has been released.
*
* @param released -
* True if the Submissions's grade has been released, false otherwise.
*/
public void setGradeReleased(boolean released)
{
m_gradeReleased = released;
}
/**
* Sets the grade for the Submisssion.
*
* @param grade -
* The Submission's grade.
*/
public void setGrade(String grade)
{
m_grade = grade;
}
/**
* Text submitted in response to the Assignment.
*
* @param submissionText -
* The text of the submission.
*/
public void setSubmittedText(String value)
{
m_submittedText = value;
}
/**
* Add an attachment to the list of submitted attachments.
*
* @param attachment -
* The Reference object pointing to the attachment.
*/
public void addSubmittedAttachment(Reference attachment)
{
if (attachment != null) m_submittedAttachments.add(attachment);
}
/**
* Remove an attachment from the list of submitted attachments
*
* @param attachment -
* The Reference object pointing to the attachment.
*/
public void removeSubmittedAttachment(Reference attachment)
{
if (attachment != null) m_submittedAttachments.remove(attachment);
}
/**
* Remove all submitted attachments.
*/
public void clearSubmittedAttachments()
{
m_submittedAttachments.clear();
}
/**
* Set the general comments by the grader.
*
* @param comment -
* the text of the grader's comments; may be null.
*/
public void setFeedbackComment(String value)
{
m_feedbackComment = value;
}
/**
* Set the text part of the instructors feedback; usually an annotated copy of the submittedText
*
* @param feedback -
* The text of the grader's feedback.
*/
public void setFeedbackText(String value)
{
m_feedbackText = value;
}
/**
* Add an attachment to the list of feedback attachments.
*
* @param attachment -
* The Resource object pointing to the attachment.
*/
public void addFeedbackAttachment(Reference attachment)
{
if (attachment != null) m_feedbackAttachments.add(attachment);
}
/**
* Remove an attachment from the list of feedback attachments.
*
* @param attachment -
* The Resource pointing to the attachment to remove.
*/
public void removeFeedbackAttachment(Reference attachment)
{
if (attachment != null) m_feedbackAttachments.remove(attachment);
}
/**
* Remove all feedback attachments.
*/
public void clearFeedbackAttachments()
{
m_feedbackAttachments.clear();
}
/**
* Set whether this Submission was rejected by the grader.
*
* @param returned -
* true if this response was rejected by the grader, false otherwise.
*/
public void setReturned(boolean value)
{
m_returned = value;
}
/**
* Set whether this Submission has been graded.
*
* @param graded -
* true if the submission has been graded, false otherwise.
*/
public void setGraded(boolean value)
{
m_graded = value;
}
/**
* set the grader id (used to distinguish between auto and instructor grading)
*/
public void setGradedBy(String gradedBy){
m_gradedBy = gradedBy;
}
/**
* Set the time at which the graded Submission was returned; setting it to null means it is not yet graded.
*
* @param timeReturned -
* The time at which the graded Submission was returned.
*/
public void setTimeReturned(Time timeReturned)
{
m_timeReturned = timeReturned;
}
/**
* Set the checked status of the honor pledge flag.
*
* @param honorPledgeFlag -
* True if the honor pledge is checked, false otherwise.
*/
public void setHonorPledgeFlag(boolean honorPledgeFlag)
{
m_honorPledgeFlag = honorPledgeFlag;
}
/**
* Set the time last modified.
*
* @param lastmod -
* The Time at which the Assignment was last modified.
*/
public void setTimeLastModified(Time lastmod)
{
if (lastmod != null) m_timeLastModified = lastmod;
}
public void postAttachment(List attachments){
//Send the attachment to the review service
try {
ContentResource cr = getFirstAcceptableAttachement(attachments);
Assignment ass = this.getAssignment();
if (ass != null && cr != null)
{
contentReviewService.queueContent(null, null, ass.getReference(), cr.getId());
}
else
{
// error, assignment couldn't be found. Log the error
M_log.debug(this + " BaseAssignmentSubmissionEdit postAttachment: Unable to find assignment associated with submission id= " + this.m_id + " and assignment id=" + this.m_assignment);
}
} catch (QueueException qe) {
M_log.warn(" BaseAssignmentSubmissionEdit postAttachment: Unable to add content to Content Review queue: " + qe.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
private ContentResource getFirstAcceptableAttachement(List attachments) {
for( int i =0; i < attachments.size();i++ ) {
Reference attachment = (Reference)attachments.get(i);
try {
ContentResource res = m_contentHostingService.getResource(attachment.getId());
if (contentReviewService.isAcceptableContent(res)) {
return res;
}
} catch (PermissionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
M_log.warn(":geFirstAcceptableAttachment " + e.getMessage());
} catch (IdUnusedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
M_log.warn(":geFirstAcceptableAttachment " + e.getMessage());
} catch (TypeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
M_log.warn(":geFirstAcceptableAttachment " + e.getMessage());
}
}
return null;
}
/**
* Take all values from this object.
*
* @param AssignmentSubmission
* The AssignmentSubmission object to take values from.
*/
protected void set(AssignmentSubmission assignmentSubmission)
{
setAll(assignmentSubmission);
} // set
/**
* Access the event code for this edit.
*
* @return The event code for this edit.
*/
protected String getEvent()
{
return m_event;
}
/**
* Set the event code for this edit.
*
* @param event
* The event code for this edit.
*/
protected void setEvent(String event)
{
m_event = event;
}
/**
* Access the resource's properties for modification
*
* @return The resource's properties.
*/
public ResourcePropertiesEdit getPropertiesEdit()
{
return m_properties;
} // getPropertiesEdit
/**
* Enable editing.
*/
protected void activate()
{
m_active = true;
} // activate
/**
* Check to see if the edit is still active, or has already been closed.
*
* @return true if the edit is active, false if it's been closed.
*/
public boolean isActiveEdit()
{
return m_active;
} // isActiveEdit
/**
* Close the edit object - it cannot be used after this.
*/
protected void closeEdit()
{
m_active = false;
} // closeEdit
/******************************************************************************************************************************************************************************************************************************************************
* SessionBindingListener implementation
*****************************************************************************************************************************************************************************************************************************************************/
public void valueBound(SessionBindingEvent event)
{
}
public void valueUnbound(SessionBindingEvent event)
{
M_log.debug(this + " BaseAssignmentSubmissionEdit valueUnbound()");
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelEdit(this);
}
} // valueUnbound
public void setReviewScore(int score) {
this.m_reviewScore = score;
}
public void setReviewIconUrl(String url) {
this.m_reviewIconUrl = url;
}
public void setReviewStatus(String status) {
this.m_reviewStatus = status;
}
public void setReviewError(String error) {
this.m_reviewError = error;
}
} // BaseAssignmentSubmissionEdit
/**********************************************************************************************************************************************************************************************************************************************************
* Assignment Storage
*********************************************************************************************************************************************************************************************************************************************************/
protected interface AssignmentStorage
{
/**
* Open.
*/
public void open();
/**
* Close.
*/
public void close();
/**
* Check if an Assignment by this id exists.
*
* @param id
* The assignment id.
* @return true if an Assignment by this id exists, false if not.
*/
public boolean check(String id);
/**
* Get the Assignment with this id, or null if not found.
*
* @param id
* The Assignment id.
* @return The Assignment with this id, or null if not found.
*/
public Assignment get(String id);
/**
* Get all Assignments.
*
* @return The list of all Assignments.
*/
public List getAll(String context);
/**
* Add a new Assignment with this id.
*
* @param id
* The Assignment id.
* @param context
* The context.
* @return The locked Assignment object with this id, or null if the id is in use.
*/
public AssignmentEdit put(String id, String context);
/**
* Get a lock on the Assignment with this id, or null if a lock cannot be gotten.
*
* @param id
* The Assignment id.
* @return The locked Assignment with this id, or null if this records cannot be locked.
*/
public AssignmentEdit edit(String id);
/**
* Commit the changes and release the lock.
*
* @param Assignment
* The Assignment to commit.
*/
public void commit(AssignmentEdit assignment);
/**
* Cancel the changes and release the lock.
*
* @param Assignment
* The Assignment to commit.
*/
public void cancel(AssignmentEdit assignment);
/**
* Remove this Assignment.
*
* @param Assignment
* The Assignment to remove.
*/
public void remove(AssignmentEdit assignment);
} // AssignmentStorage
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentContent Storage
*********************************************************************************************************************************************************************************************************************************************************/
protected interface AssignmentContentStorage
{
/**
* Open.
*/
public void open();
/**
* Close.
*/
public void close();
/**
* Check if a AssignmentContent by this id exists.
*
* @param id
* The AssignmentContent id.
* @return true if a AssignmentContent by this id exists, false if not.
*/
public boolean check(String id);
/**
* Get the AssignmentContent with this id, or null if not found.
*
* @param id
* The AssignmentContent id.
* @return The AssignmentContent with this id, or null if not found.
*/
public AssignmentContent get(String id);
/**
* Get all AssignmentContents.
*
* @return The list of all AssignmentContents.
*/
public List getAll(String context);
/**
* Add a new AssignmentContent with this id.
*
* @param id
* The AssignmentContent id.
* @param context
* The context.
* @return The locked AssignmentContent object with this id, or null if the id is in use.
*/
public AssignmentContentEdit put(String id, String context);
/**
* Get a lock on the AssignmentContent with this id, or null if a lock cannot be gotten.
*
* @param id
* The AssignmentContent id.
* @return The locked AssignmentContent with this id, or null if this records cannot be locked.
*/
public AssignmentContentEdit edit(String id);
/**
* Commit the changes and release the lock.
*
* @param AssignmentContent
* The AssignmentContent to commit.
*/
public void commit(AssignmentContentEdit content);
/**
* Cancel the changes and release the lock.
*
* @param AssignmentContent
* The AssignmentContent to commit.
*/
public void cancel(AssignmentContentEdit content);
/**
* Remove this AssignmentContent.
*
* @param AssignmentContent
* The AssignmentContent to remove.
*/
public void remove(AssignmentContentEdit content);
} // AssignmentContentStorage
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentSubmission Storage
*********************************************************************************************************************************************************************************************************************************************************/
protected interface AssignmentSubmissionStorage
{
/**
* Open.
*/
public void open();
/**
* Close.
*/
public void close();
/**
* Check if a AssignmentSubmission by this id exists.
*
* @param id
* The AssignmentSubmission id.
* @return true if a AssignmentSubmission by this id exists, false if not.
*/
public boolean check(String id);
/**
* Get the AssignmentSubmission with this id, or null if not found.
*
* @param id
* The AssignmentSubmission id.
* @return The AssignmentSubmission with this id, or null if not found.
*/
public AssignmentSubmission get(String id);
/**
* Get the AssignmentSubmission with this assignment id and user id.
*
* @param assignmentId
* The Assignment id.
* @param userId
* The user id
* @return The AssignmentSubmission with this id, or null if not found.
*/
public AssignmentSubmission get(String assignmentId, String userId);
/**
* Get the number of submissions which has been submitted.
*
* @param assignmentId -
* the id of Assignment who's submissions you would like.
* @return List over all the submissions for an Assignment.
*/
public int getSubmittedSubmissionsCount(String assignmentId);
/**
* Get the number of submissions which has not been submitted and graded.
*
* @param assignment -
* the Assignment who's submissions you would like.
* @return List over all the submissions for an Assignment.
*/
public int getUngradedSubmissionsCount(String assignmentId);
/**
* Get all AssignmentSubmissions.
*
* @return The list of all AssignmentSubmissions.
*/
public List getAll(String context);
/**
* Add a new AssignmentSubmission with this id.
*
* @param id
* The AssignmentSubmission id.
* @param context
* The context.
* @return The locked AssignmentSubmission object with this id, or null if the id is in use.
*/
public AssignmentSubmissionEdit put(String id, String assignmentId, String submitterId, String submitTime, String submitted, String graded);
/**
* Get a lock on the AssignmentSubmission with this id, or null if a lock cannot be gotten.
*
* @param id
* The AssignmentSubmission id.
* @return The locked AssignmentSubmission with this id, or null if this records cannot be locked.
*/
public AssignmentSubmissionEdit edit(String id);
/**
* Commit the changes and release the lock.
*
* @param AssignmentSubmission
* The AssignmentSubmission to commit.
*/
public void commit(AssignmentSubmissionEdit submission);
/**
* Cancel the changes and release the lock.
*
* @param AssignmentSubmission
* The AssignmentSubmission to commit.
*/
public void cancel(AssignmentSubmissionEdit submission);
/**
* Remove this AssignmentSubmission.
*
* @param AssignmentSubmission
* The AssignmentSubmission to remove.
*/
public void remove(AssignmentSubmissionEdit submission);
} // AssignmentSubmissionStorage
/**
* Utility function which returns the string representation of the long value of the time object.
*
* @param t -
* the Time object.
* @return A String representation of the long value of the time object.
*/
protected String getTimeString(Time t)
{
String retVal = "";
if (t != null) retVal = t.toString();
return retVal;
}
/**
* Utility function which returns a string from a boolean value.
*
* @param b -
* the boolean value.
* @return - "True" if the input value is true, "false" otherwise.
*/
protected String getBoolString(boolean b)
{
if (b)
return "true";
else
return "false";
}
/**
* Utility function which returns a boolean value from a string.
*
* @param s -
* The input string.
* @return the boolean true if the input string is "true", false otherwise.
*/
protected boolean getBool(String s)
{
boolean retVal = false;
if (s != null)
{
if (s.equalsIgnoreCase("true")) retVal = true;
}
return retVal;
}
/**
* Utility function which converts a string into a chef time object.
*
* @param timeString -
* String version of a time in long format, representing the standard ms since the epoch, Jan 1, 1970 00:00:00.
* @return A chef Time object.
*/
protected Time getTimeObject(String timeString)
{
Time aTime = null;
timeString = StringUtils.trimToNull(timeString);
if (timeString != null)
{
try
{
aTime = TimeService.newTimeGmt(timeString);
}
catch (Exception e)
{
M_log.warn(":geTimeObject " + e.getMessage());
try
{
long longTime = Long.parseLong(timeString);
aTime = TimeService.newTime(longTime);
}
catch (Exception ee)
{
M_log.warn(" getTimeObject Base Exception creating time object from xml file : " + ee.getMessage() + " timeString=" + timeString);
}
}
}
return aTime;
}
protected String getGroupNameFromContext(String context)
{
String retVal = "";
if (context != null)
{
int index = context.indexOf("group-");
if (index != -1)
{
String[] parts = StringUtil.splitFirst(context, "-");
if (parts.length > 1)
{
retVal = parts[1];
}
}
else
{
retVal = context;
}
}
return retVal;
}
/**********************************************************************************************************************************************************************************************************************************************************
* StorageUser implementations (no container)
*********************************************************************************************************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentStorageUser implementation
*********************************************************************************************************************************************************************************************************************************************************/
protected class AssignmentStorageUser implements SingleStorageUser, SAXEntityReader
{
private Map<String,Object> m_services;
/**
* Construct a new resource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Entity newResource(Entity container, String id, Object[] others)
{
return new BaseAssignment(id, (String) others[0]);
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Entity newResource(Entity container, Element element)
{
return new BaseAssignment(element);
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Entity newResource(Entity container, Entity other)
{
return new BaseAssignment((Assignment) other);
}
/**
* Construct a new resource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Edit newResourceEdit(Entity container, String id, Object[] others)
{
BaseAssignmentEdit e = new BaseAssignmentEdit(id, (String) others[0]);
e.activate();
return e;
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Edit newResourceEdit(Entity container, Element element)
{
BaseAssignmentEdit e = new BaseAssignmentEdit(element);
e.activate();
return e;
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Edit newResourceEdit(Entity container, Entity other)
{
BaseAssignmentEdit e = new BaseAssignmentEdit((Assignment) other);
e.activate();
return e;
}
/**
* Collect the fields that need to be stored outside the XML (for the resource).
*
* @return An array of field values to store in the record outside the XML (for the resource).
*/
public Object[] storageFields(Entity r)
{
Object rv[] = new Object[1];
rv[0] = ((Assignment) r).getContext();
return rv;
}
/***********************************************************************
* SAXEntityReader
*/
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.SAXEntityReader#getDefaultHandler(java.util.Map)
*/
public DefaultEntityHandler getDefaultHandler(final Map<String, Object> services)
{
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String,
* org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if (entity == null)
{
if ("assignment".equals(qName))
{
BaseAssignment ba = new BaseAssignment();
entity = ba;
setContentHandler(ba.getContentHandler(services), uri,
localName, qName, attributes);
}
else
{
M_log.warn(" AssignmentStorageUser getDefaultHandler startElement Unexpected Element in XML [" + qName + "]");
}
}
}
}
};
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.SAXEntityReader#getServices()
*/
public Map<String, Object> getServices()
{
if (m_services == null)
{
m_services = new HashMap<String, Object>();
}
return m_services;
}
}// AssignmentStorageUser
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentContentStorageUser implementation
*********************************************************************************************************************************************************************************************************************************************************/
protected class AssignmentContentStorageUser implements SingleStorageUser, SAXEntityReader
{
private Map<String,Object> m_services;
/**
* Construct a new resource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Entity newResource(Entity container, String id, Object[] others)
{
return new BaseAssignmentContent(id, (String) others[0]);
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Entity newResource(Entity container, Element element)
{
return new BaseAssignmentContent(element);
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Entity newResource(Entity container, Entity other)
{
return new BaseAssignmentContent((AssignmentContent) other);
}
/**
* Construct a new rsource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Edit newResourceEdit(Entity container, String id, Object[] others)
{
BaseAssignmentContentEdit e = new BaseAssignmentContentEdit(id, (String) others[0]);
e.activate();
return e;
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Edit newResourceEdit(Entity container, Element element)
{
BaseAssignmentContentEdit e = new BaseAssignmentContentEdit(element);
e.activate();
return e;
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Edit newResourceEdit(Entity container, Entity other)
{
BaseAssignmentContentEdit e = new BaseAssignmentContentEdit((AssignmentContent) other);
e.activate();
return e;
}
/**
* Collect the fields that need to be stored outside the XML (for the resource).
*
* @return An array of field values to store in the record outside the XML (for the resource).
*/
public Object[] storageFields(Entity r)
{
Object rv[] = new Object[1];
rv[0] = ((AssignmentContent) r).getCreator();
return rv;
}
/***********************************************************************
* SAXEntityReader
*/
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.SAXEntityReader#getDefaultHandler(java.util.Map)
*/
public DefaultEntityHandler getDefaultHandler(final Map<String, Object> services)
{
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String,
* org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if (entity == null)
{
if ("content".equals(qName))
{
BaseAssignmentContent bac = new BaseAssignmentContent();
entity = bac;
setContentHandler(bac.getContentHandler(services), uri,
localName, qName, attributes);
}
else
{
M_log.warn(" AssignmentContentStorageUser getDefaultEntityHandler startElement Unexpected Element in XML [" + qName + "]");
}
}
}
}
};
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.SAXEntityReader#getServices()
*/
public Map<String, Object> getServices()
{
if (m_services == null)
{
m_services = new HashMap<String, Object>();
}
return m_services;
}
}// ContentStorageUser
/**********************************************************************************************************************************************************************************************************************************************************
* SubmissionStorageUser implementation
*********************************************************************************************************************************************************************************************************************************************************/
protected class AssignmentSubmissionStorageUser implements SingleStorageUser, SAXEntityReader
{
private Map<String,Object> m_services;
/**
* Construct a new resource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Entity newResource(Entity container, String id, Object[] others)
{
return new BaseAssignmentSubmission(id, (String) others[0], (String) others[1], (String) others[2], (String) others[3], (String) others[4]);
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Entity newResource(Entity container, Element element)
{
return new BaseAssignmentSubmission(element);
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Entity newResource(Entity container, Entity other)
{
return new BaseAssignmentSubmission((AssignmentSubmission) other);
}
/**
* Construct a new rsource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Edit newResourceEdit(Entity container, String id, Object[] others)
{
BaseAssignmentSubmissionEdit e = new BaseAssignmentSubmissionEdit(id, (String) others[0], (String) others[1], (String) others[2], (String) others[3], (String) others[4]);
e.activate();
return e;
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Edit newResourceEdit(Entity container, Element element)
{
BaseAssignmentSubmissionEdit e = new BaseAssignmentSubmissionEdit(element);
e.activate();
return e;
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Edit newResourceEdit(Entity container, Entity other)
{
BaseAssignmentSubmissionEdit e = new BaseAssignmentSubmissionEdit((AssignmentSubmission) other);
e.activate();
return e;
}
/**
* Collect the fields that need to be stored outside the XML (for the resource).
*
* @return An array of field values to store in the record outside the XML (for the resource).
*/
public Object[] storageFields(Entity r)
{
/*"context", "SUBMITTER_ID", "SUBMIT_TIME", "SUBMITTED", "GRADED"*/
Object rv[] = new Object[5];
rv[0] = ((AssignmentSubmission) r).getAssignmentId();
rv[1] = ((AssignmentSubmission) r).getSubmitterId();
Time submitTime = ((AssignmentSubmission) r).getTimeSubmitted();
rv[2] = (submitTime != null)?String.valueOf(submitTime.getTime()):null;
rv[3] = Boolean.valueOf(((AssignmentSubmission) r).getSubmitted()).toString();
rv[4] = Boolean.valueOf(((AssignmentSubmission) r).getGraded()).toString();
return rv;
}
/***********************************************************************
* SAXEntityReader
*/
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.SAXEntityReader#getDefaultHandler(java.util.Map)
*/
public DefaultEntityHandler getDefaultHandler(final Map<String, Object> services)
{
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String,
* org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if (entity == null)
{
if ("submission".equals(qName))
{
BaseAssignmentSubmission bas = new BaseAssignmentSubmission();
entity = bas;
setContentHandler(bas.getContentHandler(services), uri,
localName, qName, attributes);
}
else
{
M_log.warn(" AssignmentSubmissionStorageUser getDefaultHandler startElement: Unexpected Element in XML [" + qName + "]");
}
}
}
}
};
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.SAXEntityReader#getServices()
*/
public Map<String, Object> getServices()
{
if (m_services == null)
{
m_services = new HashMap<String, Object>();
}
return m_services;
}
}// SubmissionStorageUser
private class UserComparator implements Comparator
{
public UserComparator() {}
public int compare(Object o1, Object o2) {
User _u1 = (User)o1;
User _u2 = (User)o2;
return _u1.compareTo(_u2);
}
}
/**
* the AssignmentComparator clas
*/
static private class AssignmentComparator implements Comparator
{
/**
* the criteria
*/
String m_criteria = null;
/**
* the criteria
*/
String m_asc = null;
/**
* is group submission
*/
boolean m_group_submission = false;
/**
* constructor
* @param criteria
* The sort criteria string
* @param asc
* The sort order string. TRUE_STRING if ascending; "false" otherwise.
*/
public AssignmentComparator(String criteria, String asc)
{
m_criteria = criteria;
m_asc = asc;
} // constructor
public AssignmentComparator(String criteria, String asc, boolean group)
{
m_criteria = criteria;
m_asc = asc;
m_group_submission = group;
}
/**
* implementing the compare function
*
* @param o1
* The first object
* @param o2
* The second object
* @return The compare result. 1 is o1 < o2; -1 otherwise
*/
public int compare(Object o1, Object o2)
{
int result = -1;
/************** for sorting submissions ********************/
if ("submitterName".equals(m_criteria))
{
String name1 = getSubmitterSortname(o1);
String name2 = getSubmitterSortname(o2);
result = name1.compareTo(name2);
}
/** *********** for sorting assignments ****************** */
else if ("duedate".equals(m_criteria))
{
// sorted by the assignment due date
Time t1 = ((Assignment) o1).getDueTime();
Time t2 = ((Assignment) o2).getDueTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if ("sortname".equals(m_criteria))
{
// sorted by the user's display name
String s1 = null;
String userId1 = (String) o1;
if (userId1 != null)
{
try
{
User u1 = UserDirectoryService.getUser(userId1);
s1 = u1!=null?u1.getSortName():null;
}
catch (Exception e)
{
M_log.warn(" AssignmentComparator.compare " + e.getMessage() + " id=" + userId1);
}
}
String s2 = null;
String userId2 = (String) o2;
if (userId2 != null)
{
try
{
User u2 = UserDirectoryService.getUser(userId2);
s2 = u2!=null?u2.getSortName():null;
}
catch (Exception e)
{
M_log.warn(" AssignmentComparator.compare " + e.getMessage() + " id=" + userId2);
}
}
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
result = s1.compareTo(s2);
}
}
// sort ascending or descending
if (m_asc.equals(Boolean.FALSE.toString()))
{
result = -result;
}
return result;
}
/**
* get the submitter sortname String for the AssignmentSubmission object
* @param o2
* @return
*/
private String getSubmitterSortname(Object o2) {
String rv = "";
if (o2 instanceof AssignmentSubmission)
{
// get Assignment
AssignmentSubmission _submission =(AssignmentSubmission) o2;
if (_submission.getAssignment().isGroup()) {
// get the Group
try {
Site _site = SiteService.getSite( _submission.getAssignment().getContext() );
rv = _site.getGroup(_submission.getSubmitterId()).getTitle();
} catch (Throwable _dfd) { }
} else {
User[] users2 = ((AssignmentSubmission) o2).getSubmitters();
if (users2 != null)
{
StringBuffer users2Buffer = new StringBuffer();
for (int i = 0; i < users2.length; i++)
{
users2Buffer.append(users2[i].getSortName() + " ");
}
rv = users2Buffer.toString();
}
}
}
return rv;
}
}
/**
* {@inheritDoc}
*/
public void updateEntityReferences(String toContext, Map<String, String> transversalMap){
if(transversalMap != null && transversalMap.size() > 0){
Set<Entry<String, String>> entrySet = (Set<Entry<String, String>>) transversalMap.entrySet();
String toSiteId = toContext;
Iterator assignmentsIter = getAssignmentsForContext(toSiteId);
while (assignmentsIter.hasNext())
{
Assignment assignment = (Assignment) assignmentsIter.next();
String assignmentId = assignment.getId();
try
{
String msgBody = assignment.getContent().getInstructions();
StringBuffer msgBodyPreMigrate = new StringBuffer(msgBody);
msgBody = LinkMigrationHelper.migrateAllLinks(entrySet, msgBody);
SecurityAdvisor securityAdvisor = new MySecurityAdvisor(SessionManager.getCurrentSessionUserId(),
new ArrayList<String>(Arrays.asList(SECURE_UPDATE_ASSIGNMENT_CONTENT)),
assignment.getContentReference());
try
{
if(!msgBody.equals(msgBodyPreMigrate.toString())){
// add permission to update assignment content
securityService.pushAdvisor(securityAdvisor);
AssignmentContentEdit cEdit = editAssignmentContent(assignment.getContentReference());
cEdit.setInstructions(msgBody);
commitEdit(cEdit);
}
}
catch (Exception e)
{
// exception
M_log.warn("UpdateEntityReference: cannot get assignment content for " + assignment.getId() + e.getMessage());
}
finally
{
// remove advisor
securityService.popAdvisor(securityAdvisor);
}
}
catch(Exception ee)
{
M_log.warn("UpdateEntityReference: remove Assignment and all references for " + assignment.getId() + ee.getMessage());
}
}
}
}
public void transferCopyEntities(String fromContext, String toContext, List ids, boolean cleanup){
transferCopyEntitiesRefMigrator(fromContext, toContext, ids, cleanup);
}
public Map<String, String> transferCopyEntitiesRefMigrator(String fromContext, String toContext, List ids, boolean cleanup)
{
Map<String, String> transversalMap = new HashMap<String, String>();
try
{
if(cleanup == true)
{
String toSiteId = toContext;
Iterator assignmentsIter = getAssignmentsForContext(toSiteId);
while (assignmentsIter.hasNext())
{
Assignment assignment = (Assignment) assignmentsIter.next();
String assignmentId = assignment.getId();
SecurityAdvisor securityAdvisor = new MySecurityAdvisor(SessionManager.getCurrentSessionUserId(),
new ArrayList<String>(Arrays.asList(SECURE_UPDATE_ASSIGNMENT, SECURE_REMOVE_ASSIGNMENT)),
assignmentId);
try
{
// advisor to allow edit and remove assignment
securityService.pushAdvisor(securityAdvisor);
AssignmentEdit aEdit = editAssignment(assignmentId);
// remove this assignment with all its associated items
removeAssignmentAndAllReferences(aEdit);
}
catch(Exception ee)
{
M_log.warn(":transferCopyEntities: remove Assignment and all references for " + assignment.getId() + ee.getMessage());
}
finally
{
// remove SecurityAdvisor
securityService.popAdvisor(securityAdvisor);
}
}
}
transversalMap.putAll(transferCopyEntitiesRefMigrator(fromContext, toContext, ids));
}
catch (Exception e)
{
M_log.info(this + "transferCopyEntities: End removing Assignmentt data" + e.getMessage());
}
return transversalMap;
}
/**
* This is to mimic the FormattedText.decodeFormattedTextAttribute but use SAX serialization instead
* @return
*/
protected String formattedTextDecodeFormattedTextAttribute(Attributes attributes, String baseAttributeName)
{
String ret;
// first check if an HTML-encoded attribute exists, for example "foo-html", and use it if available
ret = StringUtils.trimToNull(xmlDecodeAttribute(attributes, baseAttributeName + "-html"));
if (ret != null) return ret;
// next try the older kind of formatted text like "foo-formatted", and convert it if found
ret = StringUtils.trimToNull(xmlDecodeAttribute(attributes, baseAttributeName + "-formatted"));
ret = FormattedText.convertOldFormattedText(ret);
if (ret != null) return ret;
// next try just a plaintext attribute and convert the plaintext to formatted text if found
// convert from old plaintext instructions to new formatted text instruction
ret = xmlDecodeAttribute(attributes, baseAttributeName);
ret = FormattedText.convertPlaintextToFormattedText(ret);
return ret;
}
/**
* this is to mimic the Xml.decodeAttribute
* @param el
* @param tag
* @return
*/
protected String xmlDecodeAttribute(Attributes attributes, String tag)
{
String charset = StringUtils.trimToNull(attributes.getValue("charset"));
if (charset == null) charset = "UTF-8";
String body = StringUtils.trimToNull(attributes.getValue(tag));
if (body != null)
{
try {
byte[] decoded = Base64.decodeBase64(body); // UTF-8 by default
body = org.apache.commons.codec.binary.StringUtils.newString(decoded, charset);
} catch (IllegalStateException e) {
M_log.warn(" XmlDecodeAttribute: " + e.getMessage() + " tag=" + tag);
}
}
if (body == null) body = "";
return body;
}
/**
* construct the right path for context string, used for permission checkings
* @param context
* @return
*/
public static String getContextReference(String context)
{
String resourceString = getAccessPoint(true) + Entity.SEPARATOR + "a" + Entity.SEPARATOR + context + Entity.SEPARATOR;
return resourceString;
}
/**
* the GroupSubmission clas
*/
public class GroupSubmission
{
/**
* the Group object
*/
Group m_group = null;
/**
* the AssignmentSubmission object
*/
AssignmentSubmission m_submission = null;
public GroupSubmission(Group g, AssignmentSubmission s)
{
m_group = g;
m_submission = s;
}
/**
* Returns the AssignmentSubmission object
*/
public AssignmentSubmission getSubmission()
{
return m_submission;
}
public Group getGroup()
{
return m_group;
}
}
private LRS_Statement getStatementForAssignmentGraded(LRS_Actor instructor, Event event, Assignment a, AssignmentSubmission s,
User studentUser) {
LRS_Verb verb = new LRS_Verb(SAKAI_VERB.scored);
LRS_Object lrsObject = new LRS_Object(m_serverConfigurationService.getPortalUrl() + event.getResource(),
"received-grade-assignment");
HashMap<String, String> nameMap = new HashMap<String, String>();
nameMap.put("en-US", "User received a grade");
lrsObject.setActivityName(nameMap);
HashMap<String, String> descMap = new HashMap<String, String>();
descMap.put("en-US", "User received a grade for their assginment: " + a.getTitle() + "; Submission #: " + s.getResubmissionNum());
lrsObject.setDescription(descMap);
LRS_Actor student = new LRS_Actor(studentUser.getEmail());
student.setName(studentUser.getDisplayName());
LRS_Context context = new LRS_Context(instructor);
context.setActivity("other", "assignment");
LRS_Statement statement = new LRS_Statement(student, verb, lrsObject, getLRS_Result(a, s, true), context);
return statement;
}
private LRS_Result getLRS_Result(Assignment a, AssignmentSubmission s, boolean completed) {
LRS_Result result = null;
AssignmentContent content = a.getContent();
if (3 == content.getTypeOfGrade() && NumberUtils.isNumber(s.getGradeDisplay())) { // Points
result = new LRS_Result(new Float(s.getGradeDisplay()), new Float(0.0), new Float(content.getMaxGradePointDisplay()), null);
result.setCompletion(completed);
} else {
result = new LRS_Result(completed);
result.setGrade(s.getGradeDisplay());
}
return result;
}
private LRS_Statement getStatementForUnsubmittedAssignmentGraded(LRS_Actor instructor, Event event, Assignment a,
AssignmentSubmission s, User studentUser) {
LRS_Verb verb = new LRS_Verb(SAKAI_VERB.scored);
LRS_Object lrsObject = new LRS_Object(m_serverConfigurationService.getAccessUrl() + event.getResource(), "received-grade-unsubmitted-assignment");
HashMap<String, String> nameMap = new HashMap<String, String>();
nameMap.put("en-US", "User received a grade");
lrsObject.setActivityName(nameMap);
HashMap<String, String> descMap = new HashMap<String, String>();
descMap.put("en-US", "User received a grade for an unsubmitted assginment: " + a.getTitle());
lrsObject.setDescription(descMap);
LRS_Actor student = new LRS_Actor(studentUser.getEmail());
student.setName(studentUser.getDisplayName());
LRS_Context context = new LRS_Context(instructor);
context.setActivity("other", "assignment");
LRS_Statement statement = new LRS_Statement(student, verb, lrsObject, getLRS_Result(a, s, false), context);
return statement;
}
} // BaseAssignmentService
|
assignment/assignment-impl/impl/src/java/org/sakaiproject/assignment/impl/BaseAssignmentService.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.assignment.impl;
import au.com.bytecode.opencsv.CSVWriter;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.WorkbookUtil;
import org.sakaiproject.announcement.api.AnnouncementChannel;
import org.sakaiproject.announcement.api.AnnouncementService;
import org.sakaiproject.assignment.api.*;
import org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer;
import org.sakaiproject.authz.api.*;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.authz.cover.FunctionManager;
import org.sakaiproject.calendar.api.Calendar;
import org.sakaiproject.calendar.api.CalendarEvent;
import org.sakaiproject.calendar.api.CalendarService;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.content.util.ZipContentUtil;
import org.sakaiproject.contentreview.exception.QueueException;
import org.sakaiproject.contentreview.exception.ReportException;
import org.sakaiproject.contentreview.exception.SubmissionException;
import org.sakaiproject.contentreview.model.ContentReviewItem;
import org.sakaiproject.contentreview.service.ContentReviewService;
import org.sakaiproject.email.cover.DigestService;
import org.sakaiproject.email.cover.EmailService;
import org.sakaiproject.entity.api.*;
import org.sakaiproject.event.api.Event;
import org.sakaiproject.event.api.LearningResourceStoreService;
import org.sakaiproject.event.api.LearningResourceStoreService.*;
import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Verb.SAKAI_VERB;
import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.event.cover.NotificationService;
import org.sakaiproject.exception.*;
import org.sakaiproject.id.cover.IdManager;
import org.sakaiproject.memory.api.CacheRefresher;
import org.sakaiproject.memory.api.MemoryService;
import org.sakaiproject.service.gradebook.shared.GradebookExternalAssessmentService;
import org.sakaiproject.service.gradebook.shared.GradebookService;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.taggable.api.TaggingManager;
import org.sakaiproject.taggable.api.TaggingProvider;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.SessionBindingEvent;
import org.sakaiproject.tool.api.SessionBindingListener;
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.util.*;
import org.sakaiproject.util.cover.LinkMigrationHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.Normalizer;
import java.text.NumberFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* <p>
* BaseAssignmentService is the abstract service class for Assignments.
* </p>
* <p>
* The Concrete Service classes extending this are the XmlFile and DbCached storage classes.
* </p>
*/
public abstract class BaseAssignmentService implements AssignmentService, EntityTransferrer, EntityTransferrerRefMigrator
{
/** Our logger. */
private static Log M_log = LogFactory.getLog(BaseAssignmentService.class);
/** the resource bundle */
private static ResourceLoader rb = new ResourceLoader("assignment");
/** A Storage object for persistent storage of Assignments. */
protected AssignmentStorage m_assignmentStorage = null;
/** A Storage object for persistent storage of Assignments. */
protected AssignmentContentStorage m_contentStorage = null;
/** A Storage object for persistent storage of Assignments. */
protected AssignmentSubmissionStorage m_submissionStorage = null;
/** The access point URL. */
protected static String m_relativeAccessPoint = null;
private static final String NEW_ASSIGNMENT_DUE_DATE_SCHEDULED = "new_assignment_due_date_scheduled";
protected static final String GROUP_LIST = "group";
protected static final String GROUP_NAME = "authzGroup";
protected static final String GROUP_SECTION_PROPERTY = "sections_category";
// the file types for zip download
protected static final String ZIP_COMMENT_FILE_TYPE = ".txt";
protected static final String ZIP_SUBMITTED_TEXT_FILE_TYPE = ".html";
// spring service injection
protected ContentReviewService contentReviewService;
public void setContentReviewService(ContentReviewService contentReviewService) {
this.contentReviewService = contentReviewService;
}
private AssignmentPeerAssessmentService assignmentPeerAssessmentService = null;
public void setAssignmentPeerAssessmentService(AssignmentPeerAssessmentService assignmentPeerAssessmentService){
this.assignmentPeerAssessmentService = assignmentPeerAssessmentService;
}
private SecurityService securityService = null;
public void setSecurityService(SecurityService securityService){
this.securityService = securityService;
}
String newline = "<br />\n";
/**********************************************************************************************************************************************************************************************************************************************************
* Abstractions, etc.
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Construct a Storage object for Assignments.
*
* @return The new storage object.
*/
protected abstract AssignmentStorage newAssignmentStorage();
/**
* Construct a Storage object for AssignmentContents.
*
* @return The new storage object.
*/
protected abstract AssignmentContentStorage newContentStorage();
/**
* Construct a Storage object for AssignmentSubmissions.
*
* @return The new storage object.
*/
protected abstract AssignmentSubmissionStorage newSubmissionStorage();
/**
* Access the partial URL that forms the root of resource URLs.
*
* @param relative -
* if true, form within the access path only (i.e. starting with /msg)
* @return the partial URL that forms the root of resource URLs.
*/
static protected String getAccessPoint(boolean relative)
{
return (relative ? "" : m_serverConfigurationService.getAccessUrl()) + m_relativeAccessPoint;
} // getAccessPoint
/**
* Access the internal reference which can be used to assess security clearance.
*
* @param id
* The assignment id string.
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String assignmentReference(String context, String id)
{
String retVal = null;
if (context == null)
retVal = getAccessPoint(true) + Entity.SEPARATOR + "a" + Entity.SEPARATOR + id;
else
retVal = getAccessPoint(true) + Entity.SEPARATOR + "a" + Entity.SEPARATOR + context + Entity.SEPARATOR + id;
return retVal;
} // assignmentReference
/**
* I feel silly having to look up the entire assignment object just to get the reference,
* but if there's no context, that seems to be the only way to do it.
* @param id
* @return
*/
public String assignmentReference(String id) {
String ref = null;
Assignment assignment = findAssignment(id);
if (assignment != null)
ref = assignment.getReference();
return ref;
} // assignmentReference
public List getSortedGroupUsers(Group _g) {
List retVal = new ArrayList();
Iterator<Member> _members = _g.getMembers().iterator();
while (_members.hasNext()) {
Member _member = _members.next();
try
{
retVal.add(UserDirectoryService.getUser(_member.getUserId()));
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission Group getSubmitters" + e.getMessage() + _member.getUserId());
}
}
java.util.Collections.sort(retVal, new UserComparator());
return retVal;
}
/**
* Access the internal reference which can be used to access the resource from within the system.
*
* @param id
* The content id string.
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String contentReference(String context, String id)
{
String retVal = null;
if (context == null)
retVal = getAccessPoint(true) + Entity.SEPARATOR + "c" + Entity.SEPARATOR + id;
else
retVal = getAccessPoint(true) + Entity.SEPARATOR + "c" + Entity.SEPARATOR + context + Entity.SEPARATOR + id;
return retVal;
} // contentReference
/**
* Access the internal reference which can be used to access the resource from within the system.
*
* @param id
* The submission id string.
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String submissionReference(String context, String id, String assignmentId)
{
String retVal = null;
if (context == null)
retVal = getAccessPoint(true) + Entity.SEPARATOR + "s" + Entity.SEPARATOR + id;
else
retVal = getAccessPoint(true) + Entity.SEPARATOR + "s" + Entity.SEPARATOR + context + Entity.SEPARATOR + assignmentId
+ Entity.SEPARATOR + id;
return retVal;
} // submissionReference
/**
* Access the assignment id extracted from an assignment reference.
*
* @param ref
* The assignment reference string.
* @return The the assignment id extracted from an assignment reference.
*/
protected String assignmentId(String ref)
{
if (ref == null) return ref;
int i = ref.lastIndexOf(Entity.SEPARATOR);
if (i == -1) return ref;
String id = ref.substring(i + 1);
return id;
} // assignmentId
/**
* Access the content id extracted from a content reference.
*
* @param ref
* The content reference string.
* @return The the content id extracted from a content reference.
*/
protected String contentId(String ref)
{
int i = ref.lastIndexOf(Entity.SEPARATOR);
if (i == -1) return ref;
String id = ref.substring(i + 1);
return id;
} // contentId
/**
* Access the submission id extracted from a submission reference.
*
* @param ref
* The submission reference string.
* @return The the submission id extracted from a submission reference.
*/
protected String submissionId(String ref)
{
int i = ref.lastIndexOf(Entity.SEPARATOR);
if (i == -1) return ref;
String id = ref.substring(i + 1);
return id;
} // submissionId
/**
* Check security permission.
*
* @param lock -
* The lock id string.
* @param resource -
* The resource reference string, or null if no resource is involved.
* @return true if allowed, false if not
*/
protected boolean unlockCheck(String lock, String resource)
{
if (!securityService.unlock(lock, resource))
{
return false;
}
return true;
}// unlockCheck
/**
* SAK-21525 Groups need to be queried, not just the site.
*
* @param lock The security function to be checked, 'asn.submit' for example.
* @param resource The resource to be accessed
* @param assignment An Assignment object. We use this for the group checks.
* @return
*/
protected boolean unlockCheckWithGroups(String lock, String resource, Assignment assignment)
{
// SAK-23755 addons:
// super user should be allowed
if (securityService.isSuperUser())
return true;
// all.groups permission should apply down to group level
String context = assignment.getContext();
String userId = SessionManager.getCurrentSessionUserId();
if (allowAllGroups(context) && securityService.unlock(lock, SiteService.siteReference(context)))
{
return true;
}
// group level users
Collection groupIds = null;
//SAK-23235 this method can be passed a null assignment -DH
if (assignment != null)
{
groupIds = assignment.getGroups();
}
if(groupIds != null && groupIds.size() > 0)
{
Iterator i = groupIds.iterator();
while(i.hasNext())
{
String groupId = (String) i.next();
boolean isAllowed
= securityService.unlock(lock,groupId);
if(isAllowed) return true;
}
if (SECURE_ADD_ASSIGNMENT_SUBMISSION.equals(lock) && assignment.isGroup())
return securityService.unlock(lock, resource);
else
return false;
}
else
{
return securityService.unlock(lock, SiteService.siteReference(context));
}
}// unlockCheckWithGroups
/**
* Check security permission.
*
* @param lock1
* The lock id string.
* @param lock2
* The lock id string.
* @param resource
* The resource reference string, or null if no resource is involved.
* @return true if either allowed, false if not
*/
protected boolean unlockCheck2(String lock1, String lock2, String resource)
{
// check the first lock
if (securityService.unlock(lock1, resource)) return true;
// if the second is different, check that
if ((!lock1.equals(lock2)) && (securityService.unlock(lock2, resource))) return true;
return false;
} // unlockCheck2
/**
* Check security permission.
*
* @param lock -
* The lock id string.
* @param resource -
* The resource reference string, or null if no resource is involved.
* @exception PermissionException
* Thrown if the user does not have access
*/
protected void unlock(String lock, String resource) throws PermissionException
{
if (!unlockCheck(lock, resource))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), lock, resource);
}
} // unlock
/**
* Check security permission.
*
* @param lock1
* The lock id string.
* @param lock2
* The lock id string.
* @param resource
* The resource reference string, or null if no resource is involved.
* @exception PermissionException
* Thrown if the user does not have access to either.
*/
protected void unlock2(String lock1, String lock2, String resource) throws PermissionException
{
if (!unlockCheck2(lock1, lock2, resource))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), lock1 + "/" + lock2, resource);
}
} // unlock2
/**********************************************************************************************************************************************************************************************************************************************************
* Dependencies and their setter methods
*********************************************************************************************************************************************************************************************************************************************************/
/** Dependency: MemoryService. */
protected MemoryService m_memoryService = null;
/**
* Dependency: MemoryService.
*
* @param service
* The MemoryService.
*/
public void setMemoryService(MemoryService service)
{
m_memoryService = service;
}
/** Dependency: ContentHostingService. */
protected ContentHostingService m_contentHostingService = null;
/**
* Dependency:ContentHostingService.
*
* @param service
* The ContentHostingService.
*/
public void setContentHostingService(ContentHostingService service)
{
m_contentHostingService = service;
}
/**
* Configuration: set the locks-in-db
*
* @param value true or false
* @deprecated 7 April 2014 - this has no effect anymore and should be removed in 11 release
*/
public void setCaching(String value) {} // intentionally blank
/** Dependency: EntityManager. */
protected EntityManager m_entityManager = null;
/**
* Dependency: EntityManager.
*
* @param service
* The EntityManager.
*/
public void setEntityManager(EntityManager service)
{
m_entityManager = service;
}
/** Dependency: ServerConfigurationService. */
static protected ServerConfigurationService m_serverConfigurationService = null;
/**
* Dependency: ServerConfigurationService.
*
* @param service
* The ServerConfigurationService.
*/
public void setServerConfigurationService(ServerConfigurationService service)
{
m_serverConfigurationService = service;
}
/** Dependency: TaggingManager. */
protected TaggingManager m_taggingManager = null;
/**
* Dependency: TaggingManager.
*
* @param manager
* The TaggingManager.
*/
public void setTaggingManager(TaggingManager manager)
{
m_taggingManager = manager;
}
/** Dependency: AssignmentActivityProducer. */
protected AssignmentActivityProducer m_assignmentActivityProducer = null;
/**
* Dependency: AssignmentActivityProducer.
*
* @param assignmentActivityProducer
* The AssignmentActivityProducer.
*/
public void setAssignmentActivityProducer(AssignmentActivityProducer assignmentActivityProducer)
{
m_assignmentActivityProducer = assignmentActivityProducer;
}
/** Dependency: GradebookService. */
protected GradebookService m_gradebookService = null;
/**
* Dependency: GradebookService
*
* @param gradebookService
* The GradebookService
*/
public void setGradebookService(GradebookService gradebookService)
{
m_gradebookService= gradebookService;
}
/** Dependency: GradebookExternalAssessmentService. */
protected GradebookExternalAssessmentService m_gradebookExternalAssessmentService = null;
/**
* Dependency: GradebookExternalAssessmentService
*
* @param gradebookExternalAssessmentService
* The GradebookExternalAssessmentService
*/
public void setGradebookExternalAssessmentService(GradebookExternalAssessmentService gradebookExternalAssessmentService)
{
m_gradebookExternalAssessmentService= gradebookExternalAssessmentService;
}
/** Dependency: CalendarService. */
protected CalendarService m_calendarService = null;
/**
* Dependency: CalendarService
*
* @param calendarService
* The CalendarService
*/
public void setCalendarService(CalendarService calendarService)
{
m_calendarService= calendarService;
}
/** Dependency: AnnouncementService. */
protected AnnouncementService m_announcementService = null;
/**
* Dependency: AnnouncementService
*
* @param announcementService
* The AnnouncementService
*/
public void setAnnouncementService(AnnouncementService announcementService)
{
m_announcementService= announcementService;
}
/** Dependency: allowGroupAssignments setting */
protected boolean m_allowGroupAssignments = true;
/**
* Dependency: allowGroupAssignments
*
* @param allowGroupAssignments
* the setting
*/
public void setAllowGroupAssignments(boolean allowGroupAssignments)
{
m_allowGroupAssignments = allowGroupAssignments;
}
/**
* Get
*
* @return allowGroupAssignments
*/
public boolean getAllowGroupAssignments()
{
return m_allowGroupAssignments;
}
/** Dependency: allowSubmitByInstructor setting */
protected boolean m_allowSubmitByInstructor = true;
/**
* Dependency: allowSubmitByInstructor
*
* @param allowSubmitByInstructor
* the setting
*/
public void setAllowSubmitByInstructor(boolean allowSubmitByInstructor)
{
m_allowSubmitByInstructor = allowSubmitByInstructor;
}
/**
* Get
*
* @return allowSubmitByInstructor
*/
public boolean getAllowSubmitByInstructor()
{
return m_allowSubmitByInstructor;
}
/** Dependency: allowGroupAssignmentsInGradebook setting */
protected boolean m_allowGroupAssignmentsInGradebook = true;
/**
* Dependency: allowGroupAssignmentsInGradebook
*
* @param allowGroupAssignmentsInGradebook
*/
public void setAllowGroupAssignmentsInGradebook(boolean allowGroupAssignmentsInGradebook)
{
m_allowGroupAssignmentsInGradebook = allowGroupAssignmentsInGradebook;
}
/**
* Get
*
* @return allowGroupAssignmentsGradebook
*/
public boolean getAllowGroupAssignmentsInGradebook()
{
return m_allowGroupAssignmentsInGradebook;
}
/**********************************************************************************************************************************************************************************************************************************************************
* Init and Destroy
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Final initialization, once all dependencies are set.
*/
public void init()
{
m_relativeAccessPoint = REFERENCE_ROOT;
M_log.info(this + " init()");
// construct storage helpers and read
m_assignmentStorage = newAssignmentStorage();
m_assignmentStorage.open();
m_contentStorage = newContentStorage();
m_contentStorage.open();
m_submissionStorage = newSubmissionStorage();
m_submissionStorage.open();
m_allowSubmitByInstructor = m_serverConfigurationService.getBoolean("assignments.instructor.submit.for.student", true);
if (!m_allowSubmitByInstructor) {
M_log.info("Instructor submission of assignments is disabled - add assignments.instructor.submit.for.student=true to sakai config to enable");
} else {
M_log.info("Instructor submission of assignments is enabled");
}
// register as an entity producer
m_entityManager.registerEntityProducer(this, REFERENCE_ROOT);
// register functions
FunctionManager.registerFunction(SECURE_ALL_GROUPS);
FunctionManager.registerFunction(SECURE_ADD_ASSIGNMENT);
FunctionManager.registerFunction(SECURE_ADD_ASSIGNMENT_SUBMISSION);
FunctionManager.registerFunction(SECURE_REMOVE_ASSIGNMENT);
FunctionManager.registerFunction(SECURE_ACCESS_ASSIGNMENT);
FunctionManager.registerFunction(SECURE_UPDATE_ASSIGNMENT);
FunctionManager.registerFunction(SECURE_GRADE_ASSIGNMENT_SUBMISSION);
FunctionManager.registerFunction(SECURE_ASSIGNMENT_RECEIVE_NOTIFICATIONS);
FunctionManager.registerFunction(SECURE_SHARE_DRAFTS);
//if no contentReviewService was set try discovering it
if (contentReviewService == null)
{
contentReviewService = (ContentReviewService) ComponentManager.get(ContentReviewService.class.getName());
}
} // init
/**
* Returns to uninitialized state.
*/
public void destroy()
{
m_assignmentStorage.close();
m_assignmentStorage = null;
m_contentStorage.close();
m_contentStorage = null;
m_submissionStorage.close();
m_submissionStorage = null;
M_log.info(this + " destroy()");
}
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentService implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Creates and adds a new Assignment to the service.
*
* @param context -
* Describes the portlet context - generated with DefaultId.getChannel().
* @return The new Assignment object.
* @throws IdInvalidException
* if the id contains prohibited characers.
* @throws IdUsedException
* if the id is already used in the service.
* @throws PermissionException
* if current User does not have permission to do this.
*/
public AssignmentEdit addAssignment(String context) throws PermissionException
{
M_log.debug(this + " ENTERING ADD ASSIGNMENT : CONTEXT : " + context);
String assignmentId = null;
boolean badId = false;
do
{
badId = !Validator.checkResourceId(assignmentId);
assignmentId = IdManager.createUuid();
if (m_assignmentStorage.check(assignmentId)) badId = true;
}
while (badId);
String key = assignmentReference(context, assignmentId);
// security check
if (!allowAddAssignment(context))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), SECURE_ADD_ASSIGNMENT, key);
}
// storage
AssignmentEdit assignment = m_assignmentStorage.put(assignmentId, context);
// event for tracking
((BaseAssignmentEdit) assignment).setEvent(AssignmentConstants.EVENT_ADD_ASSIGNMENT);
M_log.debug(this + " LEAVING ADD ASSIGNMENT WITH : ID : " + assignment.getId());
return assignment;
} // addAssignment
/**
* Add a new assignment to the directory, from a definition in XML. Must commitEdit() to make official, or cancelEdit() when done!
*
* @param el
* The XML DOM Element defining the assignment.
* @return A locked AssignmentEdit object (reserving the id).
* @exception IdInvalidException
* if the assignment id is invalid.
* @exception IdUsedException
* if the assignment id is already used.
* @exception PermissionException
* if the current user does not have permission to add an assignnment.
*/
public AssignmentEdit mergeAssignment(Element el) throws IdInvalidException, IdUsedException, PermissionException
{
// construct from the XML
Assignment assignmentFromXml = new BaseAssignment(el);
// check for a valid assignment name
if (!Validator.checkResourceId(assignmentFromXml.getId())) throw new IdInvalidException(assignmentFromXml.getId());
// check security (throws if not permitted)
unlock(SECURE_ADD_ASSIGNMENT, assignmentFromXml.getReference());
// reserve a assignment with this id from the info store - if it's in use, this will return null
AssignmentEdit assignment = m_assignmentStorage.put(assignmentFromXml.getId(), assignmentFromXml.getContext());
if (assignment == null)
{
throw new IdUsedException(assignmentFromXml.getId());
}
// transfer from the XML read assignment object to the AssignmentEdit
((BaseAssignmentEdit) assignment).set(assignmentFromXml);
((BaseAssignmentEdit) assignment).setEvent(AssignmentConstants.EVENT_ADD_ASSIGNMENT);
ResourcePropertiesEdit propertyEdit = (BaseResourcePropertiesEdit)assignment.getProperties();
try
{
propertyEdit.getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
}
catch(EntityPropertyNotDefinedException epnde)
{
String now = TimeService.newTime().toString();
propertyEdit.addProperty(ResourceProperties.PROP_CREATION_DATE, now);
}
catch(EntityPropertyTypeException epte)
{
M_log.error(this + " mergeAssignment error when trying to get creation time property " + epte);
}
return assignment;
}
/**
* Creates and adds a new Assignment to the service which is a copy of an existing Assignment.
*
* @param assignmentId -
* The Assignment to be duplicated.
* @return The new Assignment object, or null if the original Assignment does not exist.
* @throws PermissionException
* if current User does not have permission to do this.
*/
public AssignmentEdit addDuplicateAssignment(String context, String assignmentReference) throws PermissionException,
IdInvalidException, IdUsedException, IdUnusedException
{
M_log.debug(this + " ENTERING ADD DUPLICATE ASSIGNMENT WITH ID : " + assignmentReference);
AssignmentEdit retVal = null;
AssignmentContentEdit newContent = null;
if (assignmentReference != null)
{
String assignmentId = assignmentId(assignmentReference);
if (!m_assignmentStorage.check(assignmentId))
throw new IdUnusedException(assignmentId);
else
{
M_log.debug(this + " addDuplicateAssignment : assignment exists - will copy");
Assignment existingAssignment = getAssignment(assignmentReference);
newContent = addDuplicateAssignmentContent(context, existingAssignment.getContentReference());
commitEdit(newContent);
retVal = addAssignment(context);
retVal.setContentReference(newContent.getReference());
retVal.setTitle(existingAssignment.getTitle() + " - " + rb.getString("assignment.copy"));
retVal.setSection(existingAssignment.getSection());
retVal.setOpenTime(existingAssignment.getOpenTime());
retVal.setDueTime(existingAssignment.getDueTime());
retVal.setDropDeadTime(existingAssignment.getDropDeadTime());
retVal.setCloseTime(existingAssignment.getCloseTime());
retVal.setDraft(true);
retVal.setGroup(existingAssignment.isGroup());
ResourcePropertiesEdit pEdit = (BaseResourcePropertiesEdit) retVal.getProperties();
pEdit.addAll(existingAssignment.getProperties());
addLiveProperties(pEdit);
}
}
M_log.debug(this + " ADD DUPLICATE ASSIGNMENT : LEAVING ADD DUPLICATE ASSIGNMENT WITH ID : "
+ retVal != null ? retVal.getId() : "");
return retVal;
}
/**
* Access the Assignment with the specified reference.
*
* @param assignmentReference -
* The reference of the Assignment.
* @return The Assignment corresponding to the reference, or null if it does not exist.
* @throws IdUnusedException
* if there is no object with this reference.
* @throws PermissionException
* if the current user is not allowed to access this.
*/
public Assignment getAssignment(String assignmentReference) throws IdUnusedException, PermissionException
{
M_log.debug(this + " GET ASSIGNMENT : REF : " + assignmentReference);
// check security on the assignment
unlockCheck(SECURE_ACCESS_ASSIGNMENT, assignmentReference);
Assignment assignment = findAssignment(assignmentReference);
String currentUserId = SessionManager.getCurrentSessionUserId();
if (assignment == null) throw new IdUnusedException(assignmentReference);
return checkAssignmentAccessibleForUser(assignment, currentUserId);
}// getAssignment
/**
* Retrieves the current status of an assignment.
* @param assignmentReference
* @return
* @throws IdUnusedException
* @throws PermissionException
*/
public String getAssignmentStatus(String assignmentReference) throws IdUnusedException, PermissionException
{
M_log.debug(this + " GET ASSIGNMENT : REF : " + assignmentReference);
// check security on the assignment
unlockCheck(SECURE_ACCESS_ASSIGNMENT, assignmentReference);
Assignment assignment = findAssignment(assignmentReference);
if (assignment == null) throw new IdUnusedException(assignmentReference);
return assignment.getStatus();
} // getAssignmentStatus
/**
* Check visibility of an assignment for a given user. We consider an
* an assignment to be visible to the user if it has been opened and is
* not deleted. However, we allow access to deleted assignments if the
* user has already made a submission for the assignment.
*
* Note that this method does not check permissions at all. It should
* already be established that the user is permitted to access this
* assignment.
*
* @param assignment the assignment to check
* @param userId the user for whom to check
* @return true if the assignment is available (open, not deleted) or
* submitted by the specified user; false otherwise
*/
private boolean isAvailableOrSubmitted(Assignment assignment, String userId)
{
boolean accessible = false;
String deleted = assignment.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED);
if (deleted == null || "".equals(deleted))
{
// show not deleted, not draft, opened assignments
Time openTime = assignment.getOpenTime();
if (openTime != null && TimeService.newTime().after(openTime) && !assignment.getDraft())
{
accessible = true;
}
}
else if (deleted.equalsIgnoreCase(Boolean.TRUE.toString()) && (assignment.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
&& getSubmission(assignment.getReference(), userId) != null)
{
// and those deleted but not non-electronic assignments but the user has made submissions to them
accessible = true;
}
return accessible;
}
private Assignment checkAssignmentAccessibleForUser(Assignment assignment, String currentUserId) throws PermissionException {
if (assignment.getAccess() == Assignment.AssignmentAccess.GROUPED)
{
String context = assignment.getContext();
Collection<Group> asgGroups = assignment.getGroups();
Collection<Group> allowedGroups = getGroupsAllowGetAssignment(context, currentUserId);
// reject and throw PermissionException if there is no intersection
if (!allowAllGroups(context) && !isIntersectionGroupRefsToGroups(asgGroups, allowedGroups)) {
throw new PermissionException(currentUserId, SECURE_ACCESS_ASSIGNMENT, assignment.getReference());
}
}
if (assignment.getAccess() == Assignment.AssignmentAccess.GROUPED)
{
Collection<Group> asgGroups = assignment.getGroups();
Collection<Group> allowedGroups = getGroupsAllowGetAssignment(assignment.getContext(), currentUserId);
// reject and throw PermissionException if there is no intersection
if (!isIntersectionGroupRefsToGroups(asgGroups, allowedGroups)) {
throw new PermissionException(currentUserId, SECURE_ACCESS_ASSIGNMENT, assignment.getReference());
}
}
if (allowAddAssignment(assignment.getContext()))
{
// always return for users can add assignent in the context
return assignment;
}
else if (isAvailableOrSubmitted(assignment, currentUserId))
{
return assignment;
}
throw new PermissionException(currentUserId, SECURE_ACCESS_ASSIGNMENT, assignment.getReference());
}
protected Assignment findAssignment(String assignmentReference)
{
Assignment assignment = null;
String assignmentId = assignmentId(assignmentReference);
assignment = m_assignmentStorage.get(assignmentId);
return assignment;
}
/**
* Access all assignment objects - known to us (not from external providers).
*
* @return A list of assignment objects.
*/
protected List getAssignments(String context)
{
return assignments(context, null);
} // getAssignments
/**
* Access all assignment objects - known to us (not from external providers) and accessible by the user
*
* @return A list of assignment objects.
*/
protected List getAssignments(String context, String userId)
{
return assignments(context, userId);
} // getAssignments
//
private List assignments(String context, String userId)
{
List rv = new ArrayList();
if (!allowGetAssignment(context))
{
// no permission to read assignment in context
return rv;
}
else
{
List assignments = getUnfilteredAssignments(context);
if (userId == null)
{
userId = SessionManager.getCurrentSessionUserId();
}
// check for the site and group permissions of these assignments as well as visibility (release time, etc.)
rv = getAccessibleAssignments(assignments, context, userId);
}
return rv;
}
/**
* Access all assignment objects for a site without considering user permissions.
* This should be used with care; almost all scenarios should use {@link getAssignments(String)}
* or {@link getAssignments(String, String)}, which do enforce permissions and visibility.
*
* @return A list of Assignment objects.
*/
protected List getUnfilteredAssignments(String context)
{
List assignments = m_assignmentStorage.getAll(context);
return assignments;
}
/**
* Filter a list of assignments to those that the supplied user can access.
*
* This method is primarily provided to be called from assignments() for
* set-based efficiency over iteration in building a list of assignments
* for a given user.
*
* There are a few ways that we consider an assignment to be accessible:
* 1. The user can add assignments to the site, or
* 2. The assignment is grouped and the user can view assignments in at
* least one of those groups, or
* 3. The assignment is ungrouped and the user can view assignments in
* the site
* An additional state check applies, which is that the assignment is
* not visible if it is deleted, except when the user has made a
* submission for it already or can add (manage) assignments.
*
* These rules were extracted from assignments() and we are enforcing
* them here for a set, rather than a single assignment.
*
* This is a somewhat awkward signature; it should really either have just the
* assignments list or just the siteId, but the other methods are not refactored
* now. Namely, getAssignments calls assignments, which has some cache specifics
* and other items that would need to be refactored very carefully. Rather than
* potentially changing the behavior subtly, this only replaces the iterative
* permissions checks with set-based ones.
*
* @param assignments a list of assignments to filter; must all be from the same site
* @param siteId the Site ID for all assignments
* @param userId the user whose access should be checked for the assignments
* @return a list of the assignments that are accessible; will never be null but may be empty
*/
protected List<Assignment> getAccessibleAssignments(List<Assignment> assignments, String siteId, String userId)
{
// Make sure that everything is from the specified site
List<Assignment> siteAssignments = filterAssignmentsBySite(assignments, siteId);
// Check whether the user can add assignments for the site.
// If so, return the full list.
String siteRef = SiteService.siteReference(siteId);
boolean allowAdd = securityService.unlock(userId, SECURE_ALL_GROUPS, siteRef);
if (allowAdd)
{
return siteAssignments;
}
// Partition the assignments into grouped and ungrouped for access checks
List<List<Assignment>> partitioned = partitionAssignments(siteAssignments);
List<Assignment> grouped = partitioned.get(0);
List<Assignment> ungrouped = partitioned.get(1);
List<Assignment> permitted = new ArrayList<Assignment>();
// Check the user's site permissions and collect all of the ungrouped
// assignments if the user has permission
boolean allowSiteGet = securityService.unlock(userId, SECURE_ACCESS_ASSIGNMENT, siteRef);
if (allowSiteGet)
{
permitted.addAll(ungrouped);
}
// Collect grouped assignments that the user can access
permitted.addAll(filterGroupedAssignmentsForAccess(grouped, siteId, userId));
// Filter for visibility/submission state
List<Assignment> visible = (securityService.unlock(userId, SECURE_ADD_ASSIGNMENT, siteRef))? permitted : filterAssignmentsByVisibility(permitted, userId);
// We are left with the original list filtered by site/group permissions and visibility/submission state
return visible;
}
/**
* Filter a list of assignments to those in a given site.
*
* @param assignments the list of assignments to filter; none may be null
* @param siteId the site ID to use to filter
* @return a new list with only the assignments that belong to the site;
* never null, but empty if the site doesn't exist, the assignments
* list is empty, or none of the assignments belong to the site
*/
protected List<Assignment> filterAssignmentsBySite(List<Assignment> assignments, String siteId)
{
List<Assignment> filtered = new ArrayList<Assignment>();
if (siteId == null)
{
return filtered;
}
try
{
SiteService.getSite(siteId);
}
catch (IdUnusedException e)
{
return filtered;
}
for (Assignment assignment : assignments)
{
if (assignment != null && siteId.equals(assignment.getContext()))
{
filtered.add(assignment);
}
}
return filtered;
}
/**
* Partition a list of assignments into those that are grouped and ungrouped.
*
* @param assignments the list of assignments to inspect and partition
* @return a two-element list containing List<Assignment> in both indexes;
* the first is the grouped assignments, the second is ungrouped;
* never null, always two elements, neither list is null;
* any null assignments will be omitted in the final lists
*/
protected List<List<Assignment>> partitionAssignments(List<Assignment> assignments)
{
List<Assignment> grouped = new ArrayList<Assignment>();
List<Assignment> ungrouped = new ArrayList<Assignment>();
for (Assignment assignment : assignments)
{
if (assignment != null && assignment.getAccess() == Assignment.AssignmentAccess.GROUPED)
{
grouped.add(assignment);
}
else
{
ungrouped.add(assignment);
}
}
List<List<Assignment>> partitioned = new ArrayList<List<Assignment>>();
partitioned.add(grouped);
partitioned.add(ungrouped);
return partitioned;
}
/**
* Filter a list of grouped assignments by permissions based on a given site. Note that
* this does not consider the assignment or submission state, only permissions.
*
* @param assignments the list of assignments to filter; should all be grouped and from the same site
* @param siteId the site to which all of the assignments belong
* @param userId the user for which group permissions should be checked
* @return a new list of assignments, containing those supplied that the user
* can access, based on permission to view the assignment in one or more of its
* groups, permission to add assignments in the site, or permission to
* view assignments in all of the site's groups; never null but may be empty
*
*/
protected List<Assignment> filterGroupedAssignmentsForAccess(List<Assignment> assignments, String siteId, String userId)
{
List<Assignment> filtered = new ArrayList<Assignment>();
// Short-circuit to save the group query if we can't make a reasonable check
if (assignments == null || assignments.isEmpty() || siteId == null || userId == null)
{
return filtered;
}
// Collect the groups where the user is permitted to view assignments
// and the groups covered by the assignments, then check the
// intersection to keep only visible assignments.
Collection<Group> allowedGroups = (Collection<Group>) getGroupsAllowGetAssignment(siteId, userId);
Set<String> allowedGroupRefs = new HashSet<String>();
for (Group group : allowedGroups)
{
allowedGroupRefs.add(group.getReference());
}
for (Assignment assignment : assignments)
{
for (String groupRef : (Collection<String>) assignment.getGroups())
{
if (allowedGroupRefs.contains(groupRef))
{
filtered.add(assignment);
break;
}
}
}
return filtered;
}
/**
* Filter a list of assignments based on visibility (open time, deletion, submission, etc.)
* for a specified user. Note that this only considers assignment and submission state and
* does not consider permissions so the assignments should have already been checked for
* permissions for the given user.
*
* @param assignments the list of assignments to filter
* @param userId the user for whom to check visibility; should be permitted to
* access all of the assignments
* @return a new list containing those supplied that the user may access, based
* on visibility; never null but may be empty
*/
protected List<Assignment> filterAssignmentsByVisibility(List<Assignment> assignments, String userId)
{
List<Assignment> visible = new ArrayList<Assignment>();
for (Assignment assignment : assignments)
{
if (assignment != null && isAvailableOrSubmitted(assignment, userId))
{
visible.add(assignment);
}
}
return visible;
}
/**
* See if the collection of group reference strings has at least one group that is in the collection of Group objects.
*
* @param groupRefs
* The collection (String) of group references.
* @param groups
* The collection (Group) of group objects.
* @return true if there is interesection, false if not.
*/
protected boolean isIntersectionGroupRefsToGroups(Collection groupRefs, Collection groups)
{
for (Iterator iRefs = groupRefs.iterator(); iRefs.hasNext();)
{
String findThisGroupRef = (String) iRefs.next();
for (Iterator iGroups = groups.iterator(); iGroups.hasNext();)
{
String thisGroupRef = ((Group) iGroups.next()).getReference();
if (thisGroupRef.equals(findThisGroupRef))
{
return true;
}
}
}
return false;
}
/**
* Get a locked assignment object for editing. Must commitEdit() to make official, or cancelEdit() when done!
*
* @param id
* The assignment id string.
* @return An AssignmentEdit object for editing.
* @exception IdUnusedException
* if not found, or if not an AssignmentEdit object
* @exception PermissionException
* if the current user does not have permission to edit this assignment.
* @exception InUseException
* if the assignment is being edited by another user.
*/
public AssignmentEdit editAssignment(String assignmentReference) throws IdUnusedException, PermissionException, InUseException
{
// check security (throws if not permitted)
unlock(SECURE_UPDATE_ASSIGNMENT, assignmentReference);
String assignmentId = assignmentId(assignmentReference);
// check for existance
if (!m_assignmentStorage.check(assignmentId))
{
throw new IdUnusedException(assignmentId);
}
// ignore the cache - get the assignment with a lock from the info store
AssignmentEdit assignmentEdit = m_assignmentStorage.edit(assignmentId);
if (assignmentEdit == null) throw new InUseException(assignmentId);
((BaseAssignmentEdit) assignmentEdit).setEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT);
return assignmentEdit;
} // editAssignment
/**
* Commit the changes made to an AssignmentEdit object, and release the lock.
*
* @param assignment
* The AssignmentEdit object to commit.
*/
public void commitEdit(AssignmentEdit assignment)
{
// check for closed edit
if (!assignment.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" commitEdit(): closed AssignmentEdit " + e.getMessage() + " assignment id=" + assignment.getId());
}
return;
}
// update the properties
addLiveUpdateProperties(assignment.getPropertiesEdit());
// complete the edit
m_assignmentStorage.commit(assignment);
//update peer assessment information:
if(!assignment.getDraft() && assignment.getAllowPeerAssessment()){
assignmentPeerAssessmentService.schedulePeerReview(assignment.getId());
}else{
assignmentPeerAssessmentService.removeScheduledPeerReview(assignment.getId());
}
// track it
EventTrackingService.post(EventTrackingService.newEvent(((BaseAssignmentEdit) assignment).getEvent(), assignment
.getReference(), true));
// close the edit object
((BaseAssignmentEdit) assignment).closeEdit();
} // commitEdit
/**
* Cancel the changes made to a AssignmentEdit object, and release the lock.
*
* @param assignment
* The AssignmentEdit object to commit.
*/
public void cancelEdit(AssignmentEdit assignment)
{
// check for closed edit
if (!assignment.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" cancelEdit(): closed AssignmentEdit " + e.getMessage() + " assignment id=" + assignment.getId());
}
return;
}
// release the edit lock
m_assignmentStorage.cancel(assignment);
// close the edit object
((BaseAssignmentEdit) assignment).closeEdit();
} // cancelEdit(Assignment)
/**
* {@inheritDoc}
*/
public void removeAssignment(AssignmentEdit assignment) throws PermissionException
{
if (assignment != null)
{
M_log.debug(this + " removeAssignment with id : " + assignment.getId());
if (!assignment.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" removeAssignment(): closed AssignmentEdit" + e.getMessage() + " assignment id=" + assignment.getId());
}
return;
}
// CHECK PERMISSION
unlock(SECURE_REMOVE_ASSIGNMENT, assignment.getReference());
// complete the edit
m_assignmentStorage.remove(assignment);
// track event
EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_REMOVE_ASSIGNMENT, assignment.getReference(), true));
// close the edit object
((BaseAssignmentEdit) assignment).closeEdit();
// remove any realm defined for this resource
try
{
AuthzGroupService.removeAuthzGroup(assignment.getReference());
}
catch (AuthzPermissionException e)
{
M_log.warn(" removeAssignment: removing realm for assignment reference=" + assignment.getReference() + " : " + e.getMessage());
}
}
}// removeAssignment
/**
* {@inheritDoc}
*/
public void removeAssignmentAndAllReferences(AssignmentEdit assignment) throws PermissionException
{
if (assignment != null)
{
M_log.debug(this + " removeAssignmentAndAllReferences with id : " + assignment.getId());
if (!assignment.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" removeAssignmentAndAllReferences(): closed AssignmentEdit" + e.getMessage() + " assignment id=" + assignment.getId());
}
return;
}
// CHECK PERMISSION
unlock(SECURE_REMOVE_ASSIGNMENT, assignment.getReference());
// we may need to remove associated calendar events and annc, so get the basic info here
ResourcePropertiesEdit pEdit = assignment.getPropertiesEdit();
String context = assignment.getContext();
// 1. remove associated calendar events, if exists
removeAssociatedCalendarItem(getCalendar(context), assignment, pEdit);
// 2. remove associated announcement, if exists
removeAssociatedAnnouncementItem(getAnnouncementChannel(context), assignment, pEdit);
// 3. remove Gradebook items, if linked
removeAssociatedGradebookItem(pEdit, context);
// 4. remove tags as necessary
removeAssociatedTaggingItem(assignment);
// 5. remove assignment submissions
List submissions = getSubmissions(assignment);
if (submissions != null)
{
for (Iterator sIterator=submissions.iterator(); sIterator.hasNext();)
{
AssignmentSubmission s = (AssignmentSubmission)sIterator.next();
String sReference = s.getReference();
try
{
removeSubmission(editSubmission(sReference));
}
catch (PermissionException e)
{
M_log.warn("removeAssignmentAndAllReference: User does not have permission to remove submission " + sReference + " for assignment: " + assignment.getId() + e.getMessage());
}
catch (InUseException e)
{
M_log.warn("removeAssignmentAndAllReference: submission " + sReference + " for assignment: " + assignment.getId() + " is in use. " + e.getMessage());
}catch (IdUnusedException e)
{
M_log.warn("removeAssignmentAndAllReference: submission " + sReference + " for assignment: " + assignment.getId() + " does not exist. " + e.getMessage());
}
}
}
// 6. remove associated content object
try
{
removeAssignmentContent(editAssignmentContent(assignment.getContent().getReference()));
}
catch (AssignmentContentNotEmptyException e)
{
M_log.warn(" removeAssignmentAndAllReferences(): cannot remove non-empty AssignmentContent object for assignment = " + assignment.getId() + ". " + e.getMessage());
}
catch (PermissionException e)
{
M_log.warn(" removeAssignmentAndAllReferences(): not allowed to remove AssignmentContent object for assignment = " + assignment.getId() + ". " + e.getMessage());
}
catch (InUseException e)
{
M_log.warn(" removeAssignmentAndAllReferences(): AssignmentContent object for assignment = " + assignment.getId() + " is in used. " + e.getMessage());
}
catch (IdUnusedException e)
{
M_log.warn(" removeAssignmentAndAllReferences(): cannot find AssignmentContent object for assignment = " + assignment.getId() + ". " + e.getMessage());
}
// 7. remove assignment
m_assignmentStorage.remove(assignment);
// close the edit object
((BaseAssignmentEdit) assignment).closeEdit();
// 8. remove any realm defined for this resource
try
{
AuthzGroupService.removeAuthzGroup(assignment.getReference());
}
catch (AuthzPermissionException e)
{
M_log.warn(" removeAssignment: removing realm for assignment reference=" + assignment.getReference() + " : " + e.getMessage());
}
// track event
EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_REMOVE_ASSIGNMENT, assignment.getReference(), true));
}
}// removeAssignment
/**
* remove the associated tagging items
* @param assignment
*/
private void removeAssociatedTaggingItem(AssignmentEdit assignment) {
try
{
if (m_taggingManager.isTaggable()) {
for (TaggingProvider provider : m_taggingManager.getProviders()) {
provider.removeTags(m_assignmentActivityProducer.getActivity(assignment));
}
}
}
catch (PermissionException pe)
{
M_log.warn("removeAssociatedTaggingItem: User does not have permission to remove tags for assignment: " + assignment.getId() + " via transferCopyEntities");
}
}
/**
* remove the linked Gradebook item related with the assignment
* @param pEdit
* @param context
*/
private void removeAssociatedGradebookItem(ResourcePropertiesEdit pEdit, String context) {
String associatedGradebookAssignment = pEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
if (associatedGradebookAssignment != null) {
boolean isExternalAssignmentDefined = m_gradebookExternalAssessmentService.isExternalAssignmentDefined(context, associatedGradebookAssignment);
if (isExternalAssignmentDefined)
{
m_gradebookExternalAssessmentService.removeExternalAssessment(context, associatedGradebookAssignment);
}
}
}
private Calendar getCalendar(String contextId)
{
Calendar calendar = null;
String calendarId = m_serverConfigurationService.getString("calendar", null);
if (calendarId == null)
{
calendarId = m_calendarService.calendarReference(contextId, SiteService.MAIN_CONTAINER);
try
{
calendar = m_calendarService.getCalendar(calendarId);
}
catch (IdUnusedException e)
{
M_log.warn("getCalendar: No calendar found for site: " + contextId);
calendar = null;
}
catch (PermissionException e)
{
M_log.warn("getCalendar: The current user does not have permission to access " +
"the calendar for context: " + contextId, e);
}
catch (Exception ex)
{
M_log.warn("getCalendar: Unknown exception occurred retrieving calendar for site: " + contextId, ex);
calendar = null;
}
}
return calendar;
}
/**
* Will determine if there is a calendar event associated with this assignment and
* remove it, if found.
* @param calendar Calendar
* @param aEdit AssignmentEdit
* @param pEdit ResourcePropertiesEdit
*/
private void removeAssociatedCalendarItem(Calendar calendar, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit)
{
String isThereEvent = pEdit.getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
if (isThereEvent != null && isThereEvent.equals(Boolean.TRUE.toString()))
{
// remove the associated calendar event
if (calendar != null)
{
// already has calendar object
// get the old event
CalendarEvent event = null;
String oldEventId = pEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
if (oldEventId != null)
{
try
{
event = calendar.getEvent(oldEventId);
}
catch (IdUnusedException ee)
{
// no action needed for this condition
M_log.warn(":removeCalendarEvent " + ee.getMessage());
}
catch (PermissionException ee)
{
M_log.warn(":removeCalendarEvent " + ee.getMessage());
}
}
// remove the event if it exists
if (event != null)
{
try
{
calendar.removeEvent(calendar.getEditEvent(event.getId(), CalendarService.EVENT_REMOVE_CALENDAR));
pEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
pEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
}
catch (PermissionException ee)
{
M_log.warn(":removeCalendarEvent not allowed to remove calendar event for assignment = " + aEdit.getTitle() + ". ");
}
catch (InUseException ee)
{
M_log.warn(":removeCalendarEvent someone else is editing calendar event for assignment = " + aEdit.getTitle() + ". ");
}
catch (IdUnusedException ee)
{
M_log.warn(":removeCalendarEvent calendar event are in use for assignment = " + aEdit.getTitle() + " and event =" + event.getId());
}
}
}
}
}
private AnnouncementChannel getAnnouncementChannel(String contextId)
{
AnnouncementService aService = org.sakaiproject.announcement.cover.AnnouncementService.getInstance();
AnnouncementChannel channel = null;
String channelId = m_serverConfigurationService.getString(m_announcementService.ANNOUNCEMENT_CHANNEL_PROPERTY, null);
if (channelId == null)
{
channelId = m_announcementService.channelReference(contextId, SiteService.MAIN_CONTAINER);
try
{
channel = aService.getAnnouncementChannel(channelId);
}
catch (IdUnusedException e)
{
M_log.warn("getAnnouncement:No announcement channel found");
channel = null;
}
catch (PermissionException e)
{
M_log.warn("getAnnouncement:Current user not authorized to deleted annc associated " +
"with assignment. " + e.getMessage());
channel = null;
}
}
return channel;
}
/**
* Will determine if there is an announcement associated
* with this assignment and removes it, if found.
* @param channel AnnouncementChannel
* @param aEdit AssignmentEdit
* @param pEdit ResourcePropertiesEdit
*/
private void removeAssociatedAnnouncementItem(AnnouncementChannel channel, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit)
{
if (channel != null)
{
String openDateAnnounced = StringUtils.trimToNull(pEdit.getProperty("new_assignment_open_date_announced"));
String openDateAnnouncementId = StringUtils.trimToNull(pEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID));
if (openDateAnnounced != null && openDateAnnouncementId != null)
{
try
{
channel.removeMessage(openDateAnnouncementId);
}
catch (PermissionException e)
{
M_log.warn(":removeAnnouncement " + e.getMessage());
}
}
}
}
/**
* Creates and adds a new AssignmentContent to the service.
*
* @param context -
* Describes the portlet context - generated with DefaultId.getChannel().
* @return AssignmentContent The new AssignmentContent object.
* @throws PermissionException
* if current User does not have permission to do this.
*/
public AssignmentContentEdit addAssignmentContent(String context) throws PermissionException
{
M_log.debug(this + " ENTERING ADD ASSIGNMENT CONTENT");
String contentId = null;
boolean badId = false;
do
{
badId = !Validator.checkResourceId(contentId);
contentId = IdManager.createUuid();
if (m_contentStorage.check(contentId)) badId = true;
}
while (badId);
// security check
if (!allowAddAssignmentContent(context))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), SECURE_ADD_ASSIGNMENT_CONTENT, contentId);
}
AssignmentContentEdit content = m_contentStorage.put(contentId, context);
M_log.debug(this + " LEAVING ADD ASSIGNMENT CONTENT : ID : " + content.getId());
// event for tracking
((BaseAssignmentContentEdit) content).setEvent(AssignmentConstants.EVENT_ADD_ASSIGNMENT_CONTENT);
return content;
}// addAssignmentContent
/**
* Add a new AssignmentContent to the directory, from a definition in XML. Must commitEdit() to make official, or cancelEdit() when done!
*
* @param el
* The XML DOM Element defining the AssignmentContent.
* @return A locked AssignmentContentEdit object (reserving the id).
* @exception IdInvalidException
* if the AssignmentContent id is invalid.
* @exception IdUsedException
* if the AssignmentContent id is already used.
* @exception PermissionException
* if the current user does not have permission to add an AssignnmentContent.
*/
public AssignmentContentEdit mergeAssignmentContent(Element el) throws IdInvalidException, IdUsedException, PermissionException
{
// construct from the XML
AssignmentContent contentFromXml = new BaseAssignmentContent(el);
// check for a valid assignment name
if (!Validator.checkResourceId(contentFromXml.getId())) throw new IdInvalidException(contentFromXml.getId());
// check security (throws if not permitted)
unlock(SECURE_ADD_ASSIGNMENT_CONTENT, contentFromXml.getReference());
// reserve a content with this id from the info store - if it's in use, this will return null
AssignmentContentEdit content = m_contentStorage.put(contentFromXml.getId(), contentFromXml.getContext());
if (content == null)
{
throw new IdUsedException(contentFromXml.getId());
}
// transfer from the XML read content object to the AssignmentContentEdit
((BaseAssignmentContentEdit) content).set(contentFromXml);
((BaseAssignmentContentEdit) content).setEvent(AssignmentConstants.EVENT_ADD_ASSIGNMENT_CONTENT);
return content;
}
/**
* Creates and adds a new AssignmentContent to the service which is a copy of an existing AssignmentContent.
*
* @param context -
* From DefaultId.getChannel(RunData)
* @param contentReference -
* The id of the AssignmentContent to be duplicated.
* @return AssignmentContentEdit The new AssignmentContentEdit object, or null if the original does not exist.
* @throws PermissionException
* if current User does not have permission to do this.
*/
public AssignmentContentEdit addDuplicateAssignmentContent(String context, String contentReference) throws PermissionException,
IdInvalidException, IdUnusedException
{
M_log.debug(this + " ENTERING ADD DUPLICATE ASSIGNMENT CONTENT : " + contentReference);
AssignmentContentEdit retVal = null;
AssignmentContent existingContent = null;
List tempVector = null;
Reference tempRef = null;
Reference newRef = null;
if (contentReference != null)
{
String contentId = contentId(contentReference);
if (!m_contentStorage.check(contentId))
throw new IdUnusedException(contentId);
else
{
M_log.debug(this + " ADD DUPL. CONTENT : found match - will copy");
existingContent = getAssignmentContent(contentReference);
retVal = addAssignmentContent(context);
retVal.setTitle(existingContent.getTitle() + " - " + rb.getString("assignment.copy"));
retVal.setInstructions(existingContent.getInstructions());
retVal.setHonorPledge(existingContent.getHonorPledge());
retVal.setHideDueDate(existingContent.getHideDueDate());
retVal.setTypeOfSubmission(existingContent.getTypeOfSubmission());
retVal.setTypeOfGrade(existingContent.getTypeOfGrade());
retVal.setMaxGradePoint(existingContent.getMaxGradePoint());
retVal.setGroupProject(existingContent.getGroupProject());
retVal.setIndividuallyGraded(existingContent.individuallyGraded());
retVal.setReleaseGrades(existingContent.releaseGrades());
retVal.setAllowAttachments(existingContent.getAllowAttachments());
// for ContentReview service
retVal.setAllowReviewService(existingContent.getAllowReviewService());
tempVector = existingContent.getAttachments();
if (tempVector != null)
{
for (int z = 0; z < tempVector.size(); z++)
{
tempRef = (Reference) tempVector.get(z);
if (tempRef != null)
{
String tempRefId = tempRef.getId();
String tempRefCollectionId = m_contentHostingService.getContainingCollectionId(tempRefId);
try
{
// get the original attachment display name
ResourceProperties p = m_contentHostingService.getProperties(tempRefId);
String displayName = p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
// add another attachment instance
String newItemId = m_contentHostingService.copyIntoFolder(tempRefId, tempRefCollectionId);
ContentResourceEdit copy = m_contentHostingService.editResource(newItemId);
// with the same display name
ResourcePropertiesEdit pedit = copy.getPropertiesEdit();
pedit.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName);
m_contentHostingService.commitResource(copy, NotificationService.NOTI_NONE);
newRef = m_entityManager.newReference(copy.getReference());
retVal.addAttachment(newRef);
}
catch (Exception e)
{
M_log.warn(" LEAVING ADD DUPLICATE CONTENT : " + e.toString());
}
}
}
}
ResourcePropertiesEdit pEdit = (BaseResourcePropertiesEdit) retVal.getPropertiesEdit();
pEdit.addAll(existingContent.getProperties());
addLiveProperties(pEdit);
}
}
M_log.debug(this + " LEAVING ADD DUPLICATE CONTENT WITH ID : " + retVal != null ? retVal.getId() : "");
return retVal;
}
/**
* Access the AssignmentContent with the specified reference.
*
* @param contentReference -
* The reference of the AssignmentContent.
* @return The AssignmentContent corresponding to the reference, or null if it does not exist.
* @throws IdUnusedException
* if there is no object with this reference.
* @throws PermissionException
* if the current user is not allowed to access this.
*/
public AssignmentContent getAssignmentContent(String contentReference) throws IdUnusedException, PermissionException
{
M_log.debug(this + " GET CONTENT : ID : " + contentReference);
// check security on the assignment content
unlockCheck(SECURE_ACCESS_ASSIGNMENT_CONTENT, contentReference);
AssignmentContent content = null;
// if we have it in the cache, use it
String contentId = contentId(contentReference);
if (contentId != null) {
content = m_contentStorage.get(contentId);
}
if (content == null) throw new IdUnusedException(contentId);
M_log.debug(this + " GOT ASSIGNMENT CONTENT : ID : " + content.getId());
// track event
// EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT_CONTENT, content.getReference(), false));
return content;
}// getAssignmentContent
/**
* Access all AssignmentContent objects - known to us (not from external providers).
*
* @return A list of AssignmentContent objects.
*/
protected List getAssignmentContents(String context)
{
List contents = m_contentStorage.getAll(context);
return contents;
} // getAssignmentContents
/**
* Get a locked AssignmentContent object for editing. Must commitEdit() to make official, or cancelEdit() when done!
*
* @param id
* The content id string.
* @return An AssignmentContentEdit object for editing.
* @exception IdUnusedException
* if not found, or if not an AssignmentContentEdit object
* @exception PermissionException
* if the current user does not have permission to edit this content.
* @exception InUseException
* if the assignment is being edited by another user.
*/
public AssignmentContentEdit editAssignmentContent(String contentReference) throws IdUnusedException, PermissionException,
InUseException
{
// check security (throws if not permitted)
unlock(SECURE_UPDATE_ASSIGNMENT_CONTENT, contentReference);
String contentId = contentId(contentReference);
// check for existance
if (!m_contentStorage.check(contentId))
{
throw new IdUnusedException(contentId);
}
// ignore the cache - get the AssignmentContent with a lock from the info store
AssignmentContentEdit content = m_contentStorage.edit(contentId);
if (content == null) throw new InUseException(contentId);
((BaseAssignmentContentEdit) content).setEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_CONTENT);
return content;
} // editAssignmentContent
/**
* Commit the changes made to an AssignmentContentEdit object, and release the lock.
*
* @param content
* The AssignmentContentEdit object to commit.
*/
public void commitEdit(AssignmentContentEdit content)
{
// check for closed edit
if (!content.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" commitEdit(): closed AssignmentContentEdit " + e + " content id=" + content.getId());
}
return;
}
// update the properties
addLiveUpdateProperties(content.getPropertiesEdit());
// complete the edit
m_contentStorage.commit(content);
// track it
EventTrackingService.post(EventTrackingService.newEvent(((BaseAssignmentContentEdit) content).getEvent(), content
.getReference(), true));
// close the edit object
((BaseAssignmentContentEdit) content).closeEdit();
} // commitEdit(AssignmentContent)
/**
* Cancel the changes made to a AssignmentContentEdit object, and release the lock.
*
* @param content
* The AssignmentContentEdit object to commit.
*/
public void cancelEdit(AssignmentContentEdit content)
{
// check for closed edit
if (!content.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" cancelEdit(): closed AssignmentContentEdit " + e.getMessage() + " assignment content id=" + content.getId());
}
return;
}
// release the edit lock
m_contentStorage.cancel(content);
// close the edit object
((BaseAssignmentContentEdit) content).closeEdit();
} // cancelEdit(Content)
/**
* Removes an AssignmentContent
*
* @param content -
* the AssignmentContent to remove.
* @throws an
* AssignmentContentNotEmptyException if this content still has related Assignments.
* @throws PermissionException
* if current User does not have permission to do this.
*/
public void removeAssignmentContent(AssignmentContentEdit content) throws AssignmentContentNotEmptyException,
PermissionException
{
if (content != null)
{
if (!content.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" removeAssignmentContent(): closed AssignmentContentEdit " + e.getMessage() + " assignment content id=" + content.getId());
}
return;
}
// CHECK SECURITY
unlock(SECURE_REMOVE_ASSIGNMENT_CONTENT, content.getReference());
// complete the edit
m_contentStorage.remove(content);
// track event
EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_REMOVE_ASSIGNMENT_CONTENT, content.getReference(),
true));
// close the edit object
((BaseAssignmentContentEdit) content).closeEdit();
}
}
/**
* {@inheritDoc}
*/
public AssignmentSubmissionEdit addSubmission(String context, String assignmentId, String submitterId) throws PermissionException
{
M_log.debug(this + " ENTERING ADD SUBMISSION");
String submissionId = null;
boolean badId = false;
do
{
badId = !Validator.checkResourceId(submissionId);
submissionId = IdManager.createUuid();
if (m_submissionStorage.check(submissionId)) badId = true;
}
while (badId);
String key = submissionReference(context, submissionId, assignmentId);
M_log.debug(this + " ADD SUBMISSION : SUB REF : " + key);
Assignment assignment = null;
try
{
assignment = getAssignment(assignmentId);
}
catch(IdUnusedException iue)
{
// A bit terminal, this.
}
// SAK-21525
if(!unlockCheckWithGroups(SECURE_ADD_ASSIGNMENT_SUBMISSION, key,assignment))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), SECURE_ADD_ASSIGNMENT_SUBMISSION, key);
}
M_log.debug(this + " ADD SUBMISSION : UNLOCKED");
// storage
M_log.debug(this + " SUBMITTER ID " + submitterId);
AssignmentSubmissionEdit submission = m_submissionStorage.put(submissionId, assignmentId, submitterId, null, null, null);
if (submission != null)
{
submission.setContext(context);
// event for tracking
((BaseAssignmentSubmissionEdit) submission).setEvent(AssignmentConstants.EVENT_ADD_ASSIGNMENT_SUBMISSION);
M_log.debug(this + " LEAVING ADD SUBMISSION : REF : " + submission.getReference());
}
else
{
M_log.warn(this + " ADD SUBMISSION: cannot add submission object with submission id=" + submissionId + ", assignment id=" + assignmentId + ", and submitter id=" + submitterId);
}
return submission;
}
/**
* Add a new AssignmentSubmission to the directory, from a definition in XML. Must commitEdit() to make official, or cancelEdit() when done!
*
* @param el
* The XML DOM Element defining the submission.
* @return A locked AssignmentSubmissionEdit object (reserving the id).
* @exception IdInvalidException
* if the submission id is invalid.
* @exception IdUsedException
* if the submission id is already used.
* @exception PermissionException
* if the current user does not have permission to add a submission.
*/
public AssignmentSubmissionEdit mergeSubmission(Element el) throws IdInvalidException, IdUsedException, PermissionException
{
// construct from the XML
BaseAssignmentSubmission submissionFromXml = new BaseAssignmentSubmission(el);
// check for a valid submission name
if (!Validator.checkResourceId(submissionFromXml.getId())) throw new IdInvalidException(submissionFromXml.getId());
// check security (throws if not permitted)
unlock(SECURE_ADD_ASSIGNMENT_SUBMISSION, submissionFromXml.getReference());
// reserve a submission with this id from the info store - if it's in use, this will return null
AssignmentSubmissionEdit submission = m_submissionStorage.put( submissionFromXml.getId(),
submissionFromXml.getAssignmentId(),
submissionFromXml.getSubmitterIdString(),
(submissionFromXml.getTimeSubmitted() != null)?String.valueOf(submissionFromXml.getTimeSubmitted().getTime()):null,
Boolean.valueOf(submissionFromXml.getSubmitted()).toString(),
Boolean.valueOf(submissionFromXml.getGraded()).toString());
if (submission == null)
{
throw new IdUsedException(submissionFromXml.getId());
}
// transfer from the XML read submission object to the SubmissionEdit
((BaseAssignmentSubmissionEdit) submission).set(submissionFromXml);
((BaseAssignmentSubmissionEdit) submission).setEvent(AssignmentConstants.EVENT_ADD_ASSIGNMENT_SUBMISSION);
return submission;
}
/**
* Get a locked AssignmentSubmission object for editing. Must commitEdit() to make official, or cancelEdit() when done!
*
* @param submissionrReference -
* the reference for the submission.
* @return An AssignmentSubmissionEdit object for editing.
* @exception IdUnusedException
* if not found, or if not an AssignmentSubmissionEdit object
* @exception PermissionException
* if the current user does not have permission to edit this submission.
* @exception InUseException
* if the assignment is being edited by another user.
*/
public AssignmentSubmissionEdit editSubmission(String submissionReference) throws IdUnusedException, PermissionException,
InUseException
{
String submissionId = submissionId(submissionReference);
// ignore the cache - get the AssignmentSubmission with a lock from the info store
AssignmentSubmissionEdit submission = m_submissionStorage.edit(submissionId);
if (submission == null) throw new InUseException(submissionId);
// pass if with grade or update assignment right
if (!unlockCheck(SECURE_GRADE_ASSIGNMENT_SUBMISSION, submissionReference) && !unlockCheck(SECURE_UPDATE_ASSIGNMENT, submissionReference))
{
boolean notAllowed = true;
// normal user(not a grader) can only edit his/her own submission
User currentUser = UserDirectoryService.getCurrentUser();
if (unlockCheck(SECURE_UPDATE_ASSIGNMENT_SUBMISSION, submissionReference))
{
Assignment a = submission.getAssignment();
if (a.isGroup()) {
String context = a.getContext();
Site st = SiteService.getSite(context);
try {
notAllowed =
st.getGroup(submission.getSubmitterId()).getMember(currentUser.getId()) == null;
} catch (Throwable _sss) { }
} else {
if ( submission.getSubmitterId() != null && submission.getSubmitterId().equals(currentUser.getId()) ) {
// is editing one's own submission
// then test against extra criteria depend on the status of submission
try
{
if (canSubmit(a.getContext(), a))
{
notAllowed = false;
}
}
catch (Exception e)
{
M_log.warn(" editSubmission(): cannot get assignment for submission " + submissionReference + e.getMessage());
}
}
}
}
if (notAllowed)
{
// throw PermissionException
throw new PermissionException(currentUser.getId(), SECURE_UPDATE_ASSIGNMENT, submissionReference);
}
}
// check for existance
if (!m_submissionStorage.check(submissionId))
{
throw new IdUnusedException(submissionId);
}
((BaseAssignmentSubmissionEdit) submission).setEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_SUBMISSION);
return submission;
} // editSubmission
/**
* Commit the changes made to an AssignmentSubmissionEdit object, and release the lock.
*
* @param submission
* The AssignmentSubmissionEdit object to commit.
*/
public void commitEdit(AssignmentSubmissionEdit submission)
{
String submissionRef = submission.getReference();
// check for closed edit
if (!submission.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" commitEdit(): closed AssignmentSubmissionEdit assignment submission id=" + submission.getId() + e.getMessage());
}
return;
}
// update the properties
addLiveUpdateProperties(submission.getPropertiesEdit());
submission.setTimeLastModified(TimeService.newTime());
// complete the edit
m_submissionStorage.commit(submission);
// close the edit object
((BaseAssignmentSubmissionEdit) submission).closeEdit();
try
{
AssignmentSubmission s = getSubmission(submissionRef);
Assignment a = s.getAssignment();
Time returnedTime = s.getTimeReturned();
Time submittedTime = s.getTimeSubmitted();
String resubmitNumber = s.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
// track it
if (!s.getSubmitted())
{
// saving a submission
EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_SAVE_ASSIGNMENT_SUBMISSION, submissionRef, true));
}
else if (returnedTime == null && !s.getReturned() && (submittedTime == null /*grading non-submissions*/
|| (submittedTime != null && (s.getTimeLastModified().getTime() - submittedTime.getTime()) > 1000*60 /*make sure the last modified time is at least one minute after the submit time*/)))
{
if (StringUtils.trimToNull(s.getSubmittedText()) == null && s.getSubmittedAttachments().isEmpty()
&& StringUtils.trimToNull(s.getGrade()) == null && StringUtils.trimToNull(s.getFeedbackText()) == null && StringUtils.trimToNull(s.getFeedbackComment()) == null && s.getFeedbackAttachments().isEmpty() )
{
// auto add submission for those not submitted
//EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_ADD_ASSIGNMENT_SUBMISSION, submissionRef, true));
}
else
{
// graded and saved before releasing it
Event event = EventTrackingService.newEvent(AssignmentConstants.EVENT_GRADE_ASSIGNMENT_SUBMISSION, submissionRef, true);
EventTrackingService.post(event);
LearningResourceStoreService lrss = (LearningResourceStoreService) ComponentManager
.get("org.sakaiproject.event.api.LearningResourceStoreService");
if (null != lrss && StringUtils.isNotEmpty(s.getGrade())) {
for (User user : s.getSubmitters()) {
lrss.registerStatement(getStatementForAssignmentGraded(lrss.getEventActor(event), event, a, s, user), "assignment");
}
}
}
}
else if (returnedTime != null && s.getGraded() && (submittedTime == null/*returning non-submissions*/
|| (submittedTime != null && returnedTime.after(submittedTime))/*returning normal submissions*/
|| (submittedTime != null && submittedTime.after(returnedTime) && s.getTimeLastModified().after(submittedTime))/*grading the resubmitted assignment*/))
{
// releasing a submitted assignment or releasing grade to an unsubmitted assignment
Event event = EventTrackingService.newEvent(AssignmentConstants.EVENT_GRADE_ASSIGNMENT_SUBMISSION, submissionRef, true);
EventTrackingService.post(event);
LearningResourceStoreService lrss = (LearningResourceStoreService) ComponentManager
.get("org.sakaiproject.event.api.LearningResourceStoreService");
if (null != lrss && StringUtils.isNotEmpty(s.getGrade())) {
for (User user : s.getSubmitters()) {
lrss.registerStatement(getStatementForAssignmentGraded(lrss.getEventActor(event), event, a, s, user), "assignment");
}
}
// if this is releasing grade, depending on the release grade notification setting, send email notification to student
sendGradeReleaseNotification(s.getGradeReleased(), a.getProperties().getProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE), s.getSubmitters(), s);
if(resubmitNumber!=null)
sendGradeReleaseNotification(s.getGradeReleased(), a.getProperties().getProperty(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE), s.getSubmitters(), s);
}
else if (submittedTime == null) /*grading non-submission*/
{
// releasing a submitted assignment or releasing grade to an unsubmitted assignment
Event event = EventTrackingService.newEvent(AssignmentConstants.EVENT_GRADE_ASSIGNMENT_SUBMISSION, submissionRef, true);
EventTrackingService.post(event);
LearningResourceStoreService lrss = (LearningResourceStoreService) ComponentManager
.get("org.sakaiproject.event.api.LearningResourceStoreService");
if (null != lrss) {
for (User user : s.getSubmitters()) {
lrss.registerStatement(getStatementForUnsubmittedAssignmentGraded(lrss.getEventActor(event), event, a, s, user),
"sakai.assignment");
}
}
}
else
{
// submitting a submission
EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_SUBMIT_ASSIGNMENT_SUBMISSION, submissionRef, true));
// only doing the notification for real online submissions
if (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
// instructor notification
notificationToInstructors(s, a);
// student notification, whether the student gets email notification once he submits an assignment
notificationToStudent(s);
}
}
}
catch (IdUnusedException e)
{
M_log.warn(" commitEdit(), submissionId=" + submissionRef, e);
}
catch (PermissionException e)
{
M_log.warn(" commitEdit(), submissionId=" + submissionRef, e);
}
} // commitEdit(Submission)
protected void sendGradeReleaseNotification(boolean released, String notificationSetting, User[] allSubmitters, AssignmentSubmission s)
{
if (allSubmitters == null) return;
// SAK-19916 need to filter submitters against list of valid users still in site
Set<User> filteredSubmitters = new HashSet<User>();
try {
String siteId = s.getAssignment().getContext();
Set<String> siteUsers = SiteService.getSite(siteId).getUsers();
for (int x = 0; x < allSubmitters.length; x++)
{
User u = (User) allSubmitters[x];
String userId = u.getId();
if (siteUsers.contains(userId)) {
filteredSubmitters.add(u);
}
}
} catch (IdUnusedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
User[] submitters = new User[filteredSubmitters.size()];
filteredSubmitters.toArray(submitters);
if (released && notificationSetting != null && notificationSetting.equals(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_EACH))
{
// send email to every submitters
if (submitters != null)
{
// send the message immidiately
EmailService.sendToUsers(new ArrayList(Arrays.asList(submitters)), getHeaders(null, "releasegrade"), getNotificationMessage(s, "releasegrade"));
}
}
if (notificationSetting != null && notificationSetting.equals(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_EACH)){
// send email to every submitters
if (submitters != null){
// send the message immidiately
EmailService.sendToUsers(new ArrayList(Arrays.asList(submitters)), getHeaders(null, "releaseresumbission"), getNotificationMessage(s, "releaseresumbission"));
}
}
}
/**
* send notification to instructor type of users if necessary
* @param s
* @param a
*/
private void notificationToInstructors(AssignmentSubmission s, Assignment a)
{
String notiOption = a.getProperties().getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE);
if (notiOption != null && !notiOption.equals(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE))
{
// need to send notification email
String context = s.getContext();
// compare the list of users with the receive.notifications and list of users who can actually grade this assignment
List receivers = allowReceiveSubmissionNotificationUsers(context);
List allowGradeAssignmentUsers = allowGradeAssignmentUsers(a.getReference());
receivers.retainAll(allowGradeAssignmentUsers);
String messageBody = getNotificationMessage(s, "submission");
if (notiOption.equals(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_EACH))
{
// send the message immediately
EmailService.sendToUsers(receivers, getHeaders(null, "submission"), messageBody);
}
else if (notiOption.equals(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DIGEST))
{
// just send plain/text version for now
String digestMsgBody = getPlainTextNotificationMessage(s, "submission");
// digest the message to each user
for (Iterator iReceivers = receivers.iterator(); iReceivers.hasNext();)
{
User user = (User) iReceivers.next();
DigestService.digest(user.getId(), getSubject("submission"), digestMsgBody);
}
}
}
}
/**
* get only the plain text of notification message
* @param s
* @return
*/
protected String getPlainTextNotificationMessage(AssignmentSubmission s, String submissionOrReleaseGrade)
{
StringBuilder message = new StringBuilder();
message.append(plainTextContent(s, submissionOrReleaseGrade));
return message.toString();
}
/**
* send notification to student/students if necessary
* @param s
*/
private void notificationToStudent(AssignmentSubmission s)
{
if (m_serverConfigurationService.getBoolean("assignment.submission.confirmation.email", true))
{
//send notification
User[] users = s.getSubmitters();
List receivers = new ArrayList();
for (int i=0; users != null && i<users.length; i++){
if (StringUtils.trimToNull(users[i].getEmail()) != null){
receivers.add(users[i]);
}
}
EmailService.sendToUsers(receivers, getHeaders(null, "submission"), getNotificationMessage(s, "submission"));
}
}
protected List<String> getHeaders(String receiverEmail, String submissionOrReleaseGrade)
{
List<String> rv = new ArrayList<String>();
rv.add("MIME-Version: 1.0");
rv.add("Content-Type: multipart/alternative; boundary=\""+MULTIPART_BOUNDARY+"\"");
// set the subject
rv.add(getSubject(submissionOrReleaseGrade));
// from
rv.add(getFrom());
// to
if (StringUtils.trimToNull(receiverEmail) != null)
{
rv.add("To: " + receiverEmail);
}
return rv;
}
protected List<String> getReleaseGradeHeaders(String receiverEmail)
{
List<String> rv = new ArrayList<String>();
rv.add("MIME-Version: 1.0");
rv.add("Content-Type: multipart/alternative; boundary=\""+MULTIPART_BOUNDARY+"\"");
// set the subject
rv.add(getSubject("releasegrade"));
// from
rv.add(getFrom());
// to
if (StringUtils.trimToNull(receiverEmail) != null)
{
rv.add("To: " + receiverEmail);
}
return rv;
}
protected String getSubject(String submissionOrReleaseGrade)
{
String subject = "";
if("submission".equals(submissionOrReleaseGrade))
subject = rb.getString("noti.subject.content");
else if ("releasegrade".equals(submissionOrReleaseGrade))
subject = rb.getString("noti.releasegrade.subject.content");
else
subject = rb.getString("noti.releaseresubmission.subject.content");
return "Subject: " + subject ;
}
protected String getFrom()
{
return "From: " + "\"" + m_serverConfigurationService.getString("ui.service", "Sakai") + "\"<no-reply@"+ m_serverConfigurationService.getServerName() + ">";
}
private final String MULTIPART_BOUNDARY = "======sakai-multi-part-boundary======";
private final String BOUNDARY_LINE = "\n\n--"+MULTIPART_BOUNDARY+"\n";
private final String TERMINATION_LINE = "\n\n--"+MULTIPART_BOUNDARY+"--\n\n";
private final String MIME_ADVISORY = "This message is for MIME-compliant mail readers.";
/**
* Get the message for the email.
*
* @param event
* The event that matched criteria to cause the notification.
* @return the message for the email.
*/
protected String getNotificationMessage(AssignmentSubmission s, String submissionOrReleaseGrade)
{
StringBuilder message = new StringBuilder();
message.append(MIME_ADVISORY);
message.append(BOUNDARY_LINE);
message.append(plainTextHeaders());
message.append(plainTextContent(s, submissionOrReleaseGrade));
message.append(BOUNDARY_LINE);
message.append(htmlHeaders());
message.append(htmlPreamble(submissionOrReleaseGrade));
if("submission".equals(submissionOrReleaseGrade))
message.append(htmlContent(s));
else if ("releasegrade".equals(submissionOrReleaseGrade))
message.append(htmlContentReleaseGrade(s));
else
message.append(htmlContentReleaseResubmission(s));
message.append(htmlEnd());
message.append(TERMINATION_LINE);
return message.toString();
}
protected String plainTextHeaders() {
return "Content-Type: text/plain\n\n";
}
protected String plainTextContent(AssignmentSubmission s, String submissionOrReleaseGrade) {
if("submission".equals(submissionOrReleaseGrade))
return FormattedText.convertFormattedTextToPlaintext(htmlContent(s));
else if ("releasegrade".equals(submissionOrReleaseGrade))
return FormattedText.convertFormattedTextToPlaintext(htmlContentReleaseGrade(s));
else
return FormattedText.convertFormattedTextToPlaintext(htmlContentReleaseResubmission(s));
}
protected String htmlHeaders() {
return "Content-Type: text/html\n\n";
}
protected String htmlPreamble(String submissionOrReleaseGrade) {
StringBuilder buf = new StringBuilder();
buf.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n");
buf.append(" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
buf.append("<html>\n");
buf.append(" <head><title>");
buf.append(getSubject(submissionOrReleaseGrade));
buf.append("</title></head>\n");
buf.append(" <body>\n");
return buf.toString();
}
protected String htmlEnd() {
return "\n </body>\n</html>\n";
}
private String htmlContent(AssignmentSubmission s)
{
Assignment a = s.getAssignment();
String context = s.getContext();
String siteTitle = "";
String siteId = "";
try
{
Site site = SiteService.getSite(context);
siteTitle = site.getTitle();
siteId = site.getId();
}
catch (Exception ee)
{
M_log.warn(" htmlContent(), site id =" + context + " " + ee.getMessage());
}
StringBuilder buffer = new StringBuilder();
// site title and id
buffer.append(rb.getString("noti.site.title") + " " + siteTitle + newline);
buffer.append(rb.getString("noti.site.id") + " " + siteId +newline + newline);
// assignment title and due date
buffer.append(rb.getString("assignment.title") + " " + a.getTitle()+newline);
buffer.append(rb.getString("noti.assignment.duedate") + " " + a.getDueTime().toStringLocalFull()+newline + newline);
// submitter name and id
User[] submitters = s.getSubmitters();
String submitterNames = "";
String submitterIds = "";
for (int i = 0; i<submitters.length; i++)
{
User u = (User) submitters[i];
if (i>0)
{
submitterNames = submitterNames.concat("; ");
submitterIds = submitterIds.concat("; ");
}
submitterNames = submitterNames.concat(u.getDisplayName());
submitterIds = submitterIds.concat(u.getDisplayId());
}
buffer.append(rb.getString("noti.student") + " " + submitterNames);
if (submitterIds.length() != 0)
{
buffer.append("( " + submitterIds + " )");
}
buffer.append(newline + newline);
// submit time
buffer.append(rb.getString("submission.id") + " " + s.getId() + newline);
// submit time
buffer.append(rb.getString("noti.submit.time") + " " + s.getTimeSubmitted().toStringLocalFull() + newline + newline);
// submit text
String text = StringUtils.trimToNull(s.getSubmittedText());
if ( text != null)
{
buffer.append(rb.getString("gen.submittedtext") + newline + newline + Validator.escapeHtmlFormattedText(text) + newline + newline);
}
// attachment if any
List attachments = s.getSubmittedAttachments();
if (attachments != null && attachments.size() >0)
{
if (a.getContent().getTypeOfSubmission() == Assignment.SINGLE_ATTACHMENT_SUBMISSION)
{
buffer.append(rb.getString("gen.att.single"));
}
else
{
buffer.append(rb.getString("gen.att"));
}
buffer.append(newline).append(newline);
for (int j = 0; j<attachments.size(); j++)
{
Reference r = (Reference) attachments.get(j);
buffer.append(r.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME) + " (" + r.getProperties().getPropertyFormatted(ResourceProperties.PROP_CONTENT_LENGTH)+ ")\n");
//if this is a archive (zip etc) append the list of files in it
if (isArchiveFile(r)) {
buffer.append(getArchiveManifest(r));
}
}
}
return buffer.toString();
}
/**
* get a list of the files in the archive
* @param r
* @return
*/
private Object getArchiveManifest(Reference r) {
String extension = getFileExtension(r);
StringBuilder builder = new StringBuilder();
if (".zip".equals(extension)) {
ZipContentUtil zipUtil = new ZipContentUtil();
Map<String, Long> manifest = zipUtil.getZipManifest(r);
Set<Entry<String, Long>> set = manifest.entrySet();
Iterator<Entry<String, Long>> it = set.iterator();
while (it.hasNext()) {
Entry<String, Long> entry = it.next();
builder.append(entry.getKey() + " (" + formatFileSize(entry.getValue()) + ")" + newline);
}
}
return builder.toString();
}
private String formatFileSize(Long bytes) {
long len = bytes;
String[] byteString = { "KB", "KB", "MB", "GB" };
int count = 0;
long newLen = 0;
long lenBytesExtra = len;
while (len > 1024)
{
newLen = len / 1024;
lenBytesExtra = len - (newLen * 1024);
len = newLen;
count++;
}
if ((lenBytesExtra >= 512) || ((lenBytesExtra > 0) && (newLen == 0)))
{
newLen++;
}
return Long.toString(newLen) + " " + byteString[count];
}
/**
* is this an archive type for which we can get a manifest
* @param r
* @return
*/
private boolean isArchiveFile(Reference r) {
String extension = getFileExtension(r);
if (".zip".equals(extension)) {
return true;
}
return false;
}
private String getFileExtension(Reference r) {
ResourceProperties resourceProperties = r.getProperties();
String fileName = resourceProperties.getProperty(resourceProperties.getNamePropDisplayName());
if (fileName.indexOf(".")>0) {
String extension = fileName.substring(fileName.lastIndexOf("."));
return extension;
}
return null;
}
private String htmlContentReleaseGrade(AssignmentSubmission s)
{
String newline = "<br />\n";
Assignment a = s.getAssignment();
String context = s.getContext();
String siteTitle = "";
String siteId = "";
try
{
Site site = SiteService.getSite(context);
siteTitle = site.getTitle();
siteId = site.getId();
}
catch (Exception ee)
{
M_log.warn(" htmlContentReleaseGrade(), site id =" + context + " " + ee.getMessage());
}
StringBuilder buffer = new StringBuilder();
// site title and id
buffer.append(rb.getString("noti.site.title") + " " + siteTitle + newline);
buffer.append(rb.getString("noti.site.id") + " " + siteId +newline + newline);
// notification text
buffer.append(rb.getFormattedMessage("noti.releasegrade.text", new String[]{a.getTitle(), siteTitle}));
return buffer.toString();
}
private String htmlContentReleaseResubmission(AssignmentSubmission s){
String newline = "<br />\n";
Assignment a = s.getAssignment();
String context = s.getContext();
String siteTitle = "";
String siteId = "";
try {
Site site = SiteService.getSite(context);
siteTitle = site.getTitle();
siteId = site.getId();
}catch (Exception ee){
M_log.warn(this + " htmlContentReleaseResubmission(), site id =" + context + " " + ee.getMessage());
}
StringBuilder buffer = new StringBuilder();
// site title and id
buffer.append(rb.getString("noti.site.title") + " " + siteTitle + newline);
buffer.append(rb.getString("noti.site.id") + " " + siteId +newline + newline);
// notification text
buffer.append(rb.getFormattedMessage("noti.releaseresubmission.text", new String[]{a.getTitle(), siteTitle}));
return buffer.toString();
}
/**
* Cancel the changes made to a AssignmentSubmissionEdit object, and release the lock.
*
* @param submission
* The AssignmentSubmissionEdit object to commit.
*/
public void cancelEdit(AssignmentSubmissionEdit submission)
{
// check for closed edit
if (!submission.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" cancelEdit(): closed AssignmentSubmissionEdit assignment submission id=" + submission.getId() + " " + e.getMessage());
}
return;
}
// release the edit lock
m_submissionStorage.cancel(submission);
// close the edit object
((BaseAssignmentSubmissionEdit) submission).closeEdit();
} // cancelEdit(Submission)
/**
* Removes an AssignmentSubmission and all references to it
*
* @param submission -
* the AssignmentSubmission to remove.
* @throws PermissionException
* if current User does not have permission to do this.
*/
public void removeSubmission(AssignmentSubmissionEdit submission) throws PermissionException
{
if (submission != null)
{
if (!submission.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn(" removeSubmission(): closed AssignmentSubmissionEdit id=" + submission.getId() + " " + e.getMessage());
}
return;
}
// check security
unlock(SECURE_REMOVE_ASSIGNMENT_SUBMISSION, submission.getReference());
// complete the edit
m_submissionStorage.remove(submission);
// track event
EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_REMOVE_ASSIGNMENT_SUBMISSION, submission.getReference(),
true));
// close the edit object
((BaseAssignmentSubmissionEdit) submission).closeEdit();
// remove any realm defined for this resource
try
{
AuthzGroupService.removeAuthzGroup(AuthzGroupService.getAuthzGroup(submission.getReference()));
}
catch (AuthzPermissionException e)
{
M_log.warn(" removeSubmission: removing realm for : " + submission.getReference() + " : " + e.getMessage());
}
catch (GroupNotDefinedException e)
{
M_log.warn(" removeSubmission: cannot find group for submission " + submission.getReference() + " : " + e.getMessage());
}
}
}// removeSubmission
/**
*@inheritDoc
*/
public int getSubmissionsSize(String context)
{
int size = 0;
List submissions = getSubmissions(context);
if (submissions != null)
{
size = submissions.size();
}
return size;
}
/**
* Access all AssignmentSubmission objects - known to us (not from external providers).
*
* @return A list of AssignmentSubmission objects.
*/
protected List getSubmissions(String context)
{
List<AssignmentSubmission> submissions = m_submissionStorage.getAll(context);
//get all the review scores
if (contentReviewService != null) {
try {
List<ContentReviewItem> reports = contentReviewService.getReportList(null, context);
if (reports != null && reports.size() > 0) {
updateSubmissionList(submissions, reports);
}
} catch (QueueException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SubmissionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ReportException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return submissions;
} // getAssignmentSubmissions
private void updateSubmissionList(List<AssignmentSubmission> submissions, List<ContentReviewItem> reports) {
//lets build a map to avoid multiple searches through the list of reports
Map<String, ContentReviewItem> reportsMap = new HashMap<String, ContentReviewItem> ();
for (int i = 0; i < reports.size(); i++) {
ContentReviewItem item = reports.get(i);
reportsMap.put(item.getUserId(), item);
}
for (int i = 0; i < submissions.size(); i++) {
AssignmentSubmission sub = submissions.get(i);
String submitterid = sub.getSubmitterId();
if (reportsMap.containsKey(submitterid)) {
ContentReviewItem report = reportsMap.get(submitterid);
AssignmentSubmissionEdit edit;
try {
edit = this.editSubmission(sub.getReference());
edit.setReviewScore(report.getReviewScore());
edit.setReviewIconUrl(report.getIconUrl());
edit.setSubmitterId(sub.getSubmitterId());
edit.setReviewError(report.getLastError());
this.commitEdit(edit);
} catch (IdUnusedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (PermissionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InUseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* Access list of all AssignmentContents created by the User.
*
* @param owner -
* The User who's AssignmentContents are requested.
* @return Iterator over all AssignmentContents owned by this User.
*/
public Iterator getAssignmentContents(User owner)
{
List retVal = new ArrayList();
AssignmentContent aContent = null;
List allContents = getAssignmentContents(owner.getId());
for (int x = 0; x < allContents.size(); x++)
{
aContent = (AssignmentContent) allContents.get(x);
if (aContent.getCreator().equals(owner.getId()))
{
retVal.add(aContent);
}
}
if (retVal.isEmpty())
return new EmptyIterator();
else
return retVal.iterator();
}// getAssignmentContents(User)
/**
* Access all the Assignments which have the specified AssignmentContent.
*
* @param content -
* The particular AssignmentContent.
* @return Iterator over all the Assignments with the specified AssignmentContent.
*/
public Iterator getAssignments(AssignmentContent content)
{
List retVal = new ArrayList();
String contentReference = null;
String tempContentReference = null;
if (content != null)
{
contentReference = content.getReference();
List allAssignments = getAssignments(content.getContext());
Assignment tempAssignment = null;
for (int y = 0; y < allAssignments.size(); y++)
{
tempAssignment = (Assignment) allAssignments.get(y);
tempContentReference = tempAssignment.getContentReference();
if (tempContentReference != null)
{
if (tempContentReference.equals(contentReference))
{
retVal.add(tempAssignment);
}
}
}
}
if (retVal.isEmpty())
return new EmptyIterator();
else
return retVal.iterator();
}
/**
* Access all the Assignemnts associated with the context
*
* @param context -
* Describes the portlet context - generated with DefaultId.getChannel().
* @return Iterator over all the Assignments associated with the context and the user.
*/
public Iterator getAssignmentsForContext(String context)
{
M_log.debug(this + " GET ASSIGNMENTS FOR CONTEXT : CONTEXT : " + context);
return assignmentsForContextAndUser(context, null);
}
/**
* Access all the Assignemnts associated with the context and the user
*
* @param context -
* Describes the portlet context - generated with DefaultId.getChannel()
* @return Iterator over all the Assignments associated with the context and the user
*/
public Iterator getAssignmentsForContext(String context, String userId)
{
M_log.debug(this + " GET ASSIGNMENTS FOR CONTEXT : CONTEXT : " + context);
return assignmentsForContextAndUser(context, userId);
}
/**
* @inheritDoc
*/
public Map<Assignment, List<String>> getSubmittableAssignmentsForContext(String context)
{
Map<Assignment, List<String>> submittable = new HashMap<Assignment, List<String>>();
if (!allowGetAssignment(context))
{
// no permission to read assignment in context
return submittable;
}
Site site = null;
try {
site = SiteService.getSite(context);
} catch (IdUnusedException e) {
if (M_log.isDebugEnabled()) {
M_log.debug("Could not retrieve submittable assignments for nonexistent site: " + context);
}
}
if (site == null)
{
return submittable;
}
Set<String> siteSubmitterIds = AuthzGroupService.getUsersIsAllowed(
SECURE_ADD_ASSIGNMENT_SUBMISSION, Arrays.asList(site.getReference()));
Map<String, Set<String>> groupIdUserIds = new HashMap<String, Set<String>>();
for (Group group : site.getGroups()) {
String groupRef = group.getReference();
for (Member member : group.getMembers()) {
if (member.getRole().isAllowed(SECURE_ADD_ASSIGNMENT_SUBMISSION)) {
if (!groupIdUserIds.containsKey(groupRef)) {
groupIdUserIds.put(groupRef, new HashSet<String>());
}
groupIdUserIds.get(groupRef).add(member.getUserId());
}
}
}
List<Assignment> assignments = (List<Assignment>) getAssignments(context);
for (Assignment assignment : assignments) {
Set<String> userIds = new HashSet<String>();
if (assignment.getAccess() == Assignment.AssignmentAccess.GROUPED) {
for (String groupRef : (Collection<String>) assignment.getGroups()) {
if (groupIdUserIds.containsKey(groupRef)) {
userIds.addAll(groupIdUserIds.get(groupRef));
}
}
} else {
userIds.addAll(siteSubmitterIds);
}
submittable.put(assignment, new ArrayList(userIds));
}
return submittable;
}
/**
* get proper assignments for specified context and user
* @param context
* @param user
* @return
*/
private Iterator assignmentsForContextAndUser(String context, String userId)
{
Assignment tempAssignment = null;
List retVal = new ArrayList();
List allAssignments = null;
if (context != null)
{
allAssignments = getAssignments(context, userId);
for (int x = 0; x < allAssignments.size(); x++)
{
tempAssignment = (Assignment) allAssignments.get(x);
if ((context.equals(tempAssignment.getContext()))
|| (context.equals(getGroupNameFromContext(tempAssignment.getContext()))))
{
retVal.add(tempAssignment);
}
}
}
if (retVal.isEmpty())
return new EmptyIterator();
else
return retVal.iterator();
}
/**
* @inheritDoc
*/
public List getListAssignmentsForContext(String context)
{
M_log.debug(this + " getListAssignmetsForContext : CONTEXT : " + context);
Assignment tempAssignment = null;
List retVal = new ArrayList();
if (context != null)
{
List allAssignments = getAssignments(context);
for (int x = 0; x < allAssignments.size(); x++)
{
tempAssignment = (Assignment) allAssignments.get(x);
if ((context.equals(tempAssignment.getContext()))
|| (context.equals(getGroupNameFromContext(tempAssignment.getContext()))))
{
String deleted = tempAssignment.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED);
if (deleted == null || "".equals(deleted))
{
// not deleted, show it
if (tempAssignment.getDraft())
{
// who can see the draft assigment
if (isDraftAssignmentVisible(tempAssignment, context))
{
retVal.add(tempAssignment);
}
}
else
{
retVal.add(tempAssignment);
}
}
}
}
}
return retVal;
}
/**
* who can see the draft assignment
* @param assignment
* @param context
* @return
*/
private boolean isDraftAssignmentVisible(Assignment assignment, String context)
{
return securityService.isSuperUser() // super user can always see it
|| assignment.getCreator().equals(UserDirectoryService.getCurrentUser().getId()) // the creator can see it
|| (unlockCheck(SECURE_SHARE_DRAFTS, SiteService.siteReference(context))); // any role user with share draft permission
}
/**
* Access a User's AssignmentSubmission to a particular Assignment.
*
* @param assignmentReference
* The reference of the assignment.
* @param person -
* The User who's Submission you would like.
* @return AssignmentSubmission The user's submission for that Assignment.
* @throws IdUnusedException
* if there is no object with this id.
* @throws PermissionException
* if the current user is not allowed to access this.
*/
public AssignmentSubmission getSubmission(String assignmentReference, User person)
{
AssignmentSubmission submission = null;
String assignmentId = assignmentId(assignmentReference);
if ((assignmentReference != null) && (person != null))
{
try {
Assignment a = getAssignment(assignmentReference);
if (a.isGroup()) {
Site _site = SiteService.getSite( a.getContext() );
Collection groups = _site.getGroupsWithMember(person.getId());
if (groups != null) {
Iterator<Group> itgroup = groups.iterator();
while (submission == null && itgroup.hasNext()) {
Group _g = itgroup.next();
submission = getSubmission(assignmentReference, _g.getId());
}
}
} else {
M_log.debug(" BaseAssignmentContent : Getting submission ");
submission = m_submissionStorage.get(assignmentId, person.getId());
}
} catch (IdUnusedException iue) { } catch (PermissionException pme) { }
}
if (submission != null)
{
try
{
unlock2(SECURE_ACCESS_ASSIGNMENT_SUBMISSION, SECURE_ACCESS_ASSIGNMENT, submission.getReference());
}
catch (PermissionException e)
{
return null;
}
}
return submission;
}
/**
*
* Access a Group or User's AssignmentSubmission to a particular Assignment.
*
* @param assignmentReference
* The reference of the assignment.
* @param submitter -
* The User or Group who's Submission you would like.
* @return AssignmentSubmission The user's submission for that Assignment.
* @throws IdUnusedException
* if there is no object with this id.
* @throws PermissionException
* if the current user is not allowed to access this.
*/
public AssignmentSubmission getSubmission(String assignmentReference, String submitter)
{
AssignmentSubmission submission = null;
String assignmentId = assignmentId(assignmentReference);
if ((assignmentReference != null) && (submitter != null))
{
submission = m_submissionStorage.get(assignmentId, submitter);
}
if (submission != null)
{
try
{
unlock2(SECURE_ACCESS_ASSIGNMENT_SUBMISSION, SECURE_ACCESS_ASSIGNMENT, submission.getReference());
}
catch (PermissionException e)
{
return null;
}
}
return submission;
}
/**
* @inheritDoc
*/
public AssignmentSubmission getSubmission(List submissions, User person)
{
AssignmentSubmission retVal = null;
for (int z = 0; z < submissions.size(); z++)
{
AssignmentSubmission sub = (AssignmentSubmission) submissions.get(z);
if (sub != null)
{
List submitters = sub.getSubmitterIds();
for (int a = 0; a < submitters.size(); a++)
{
String aUserId = (String) submitters.get(a);
M_log.debug(this + " getSubmission(List, User) comparing aUser id : " + aUserId + " and chosen user id : "
+ person.getId());
if (aUserId.equals(person.getId()))
{
M_log.debug(this + " getSubmission(List, User) found a match : return value is " + sub.getId());
retVal = sub;
}
}
}
}
return retVal;
}
/**
* Get the submissions for an assignment.
*
* @param assignment -
* the Assignment who's submissions you would like.
* @return Iterator over all the submissions for an Assignment.
*/
public List getSubmissions(Assignment assignment)
{
List retVal = new ArrayList();
if (assignment != null)
{
retVal = getSubmissions(assignment.getId());
}
return retVal;
}
/**
* {@inheritDoc}
*/
public int getSubmittedSubmissionsCount(String assignmentRef)
{
return m_submissionStorage.getSubmittedSubmissionsCount(assignmentRef);
}
/**
* {@inheritDoc}
*/
public int getUngradedSubmissionsCount(String assignmentRef)
{
return m_submissionStorage.getUngradedSubmissionsCount(assignmentRef);
}
/**
* Access the AssignmentSubmission with the specified id.
*
* @param submissionReference -
* The reference of the AssignmentSubmission.
* @return The AssignmentSubmission corresponding to the id, or null if it does not exist.
* @throws IdUnusedException
* if there is no object with this id.
* @throws PermissionException
* if the current user is not allowed to access this.
*/
public AssignmentSubmission getSubmission(String submissionReference) throws IdUnusedException, PermissionException
{
M_log.debug(this + " GET SUBMISSION : REF : " + submissionReference);
// check permission
unlock2(SECURE_ACCESS_ASSIGNMENT_SUBMISSION, SECURE_ACCESS_ASSIGNMENT, submissionReference);
AssignmentSubmission submission = null;
String submissionId = submissionId(submissionReference);
submission = m_submissionStorage.get(submissionId);
if (submission == null) throw new IdUnusedException(submissionId);
// double check the submission submitter information:
// if current user is not the original submitter and if he doesn't have grading permission, he should not have access to other people's submission.
String assignmentRef = assignmentReference(submission.getContext(), submission.getAssignmentId());
if (!allowGradeSubmission(assignmentRef))
{
List submitterIds = submission.getSubmitterIds();
if (submitterIds != null && !submitterIds.contains(SessionManager.getCurrentSessionUserId()))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), SECURE_ACCESS_ASSIGNMENT_SUBMISSION, submissionId);
}
}
// track event
// EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT_SUBMISSION, submission.getReference(), false));
return submission;
}// getAssignmentSubmission
/**
* Return the reference root for use in resource references and urls.
*
* @return The reference root for use in resource references and urls.
*/
protected String getReferenceRoot()
{
return REFERENCE_ROOT;
}
/**
* Update the live properties for an object when modified.
*/
protected void addLiveUpdateProperties(ResourcePropertiesEdit props)
{
props.addProperty(ResourceProperties.PROP_MODIFIED_BY, SessionManager.getCurrentSessionUserId());
props.addProperty(ResourceProperties.PROP_MODIFIED_DATE, TimeService.newTime().toString());
} // addLiveUpdateProperties
/**
* Create the live properties for the object.
*/
protected void addLiveProperties(ResourcePropertiesEdit props)
{
String current = SessionManager.getCurrentSessionUserId();
props.addProperty(ResourceProperties.PROP_CREATOR, current);
props.addProperty(ResourceProperties.PROP_MODIFIED_BY, current);
String now = TimeService.newTime().toString();
props.addProperty(ResourceProperties.PROP_CREATION_DATE, now);
props.addProperty(ResourceProperties.PROP_MODIFIED_DATE, now);
} // addLiveProperties
/**
* check permissions for addAssignment().
*
* @param context -
* Describes the portlet context - generated with DefaultId.getChannel()
* @return true if the user is allowed to addAssignment(...), false if not.
*/
public boolean allowAddGroupAssignment(String context)
{
// base the check for SECURE_ADD on the site, any of the site's groups, and the channel
// if the user can SECURE_ADD anywhere in that mix, they can add an assignment
// this stack is not the normal azg set for channels, so use a special refernce to get this behavior
String resourceString = getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_ASSIGNMENT_GROUPS + Entity.SEPARATOR + "a"
+ Entity.SEPARATOR + context + Entity.SEPARATOR;
{
M_log.debug(this + " allowAddGroupAssignment with resource string : " + resourceString);
M_log.debug(" context string : " + context);
}
// check security on the channel (throws if not permitted)
return unlockCheck(SECURE_ADD_ASSIGNMENT, resourceString);
} // allowAddGroupAssignment
/**
* @inheritDoc
*/
public boolean allowReceiveSubmissionNotification(String context)
{
String resourceString = getContextReference(context);
{
M_log.debug(this + " allowReceiveSubmissionNotification with resource string : " + resourceString);
}
// checking allow at the site level
if (unlockCheck(SECURE_ASSIGNMENT_RECEIVE_NOTIFICATIONS, resourceString)) return true;
return false;
}
/**
* @inheritDoc
*/
public List allowReceiveSubmissionNotificationUsers(String context)
{
String resourceString = getContextReference(context);
{
M_log.debug(this + " allowReceiveSubmissionNotificationUsers with resource string : " + resourceString);
M_log.debug(" context string : " + context);
}
return securityService.unlockUsers(SECURE_ASSIGNMENT_RECEIVE_NOTIFICATIONS, resourceString);
} // allowAddAssignmentUsers
/**
* @inheritDoc
*/
public boolean allowAddAssignment(String context)
{
String resourceString = getContextReference(context);
// base the check for SECURE_ADD_ASSIGNMENT on the site and any of the site's groups
// if the user can SECURE_ADD_ASSIGNMENT anywhere in that mix, they can add an assignment
// this stack is not the normal azg set for site, so use a special refernce to get this behavior
{
M_log.debug(this + " allowAddAssignment with resource string : " + resourceString);
}
// checking allow at the site level
if (unlockCheck(SECURE_ADD_ASSIGNMENT, resourceString)) return true;
// if not, see if the user has any groups to which adds are allowed
return (!getGroupsAllowAddAssignment(context).isEmpty());
}
/**
* @inheritDoc
*/
public boolean allowAddSiteAssignment(String context)
{
// check for assignments that will be site-wide:
String resourceString = getContextReference(context);
{
M_log.debug(this + " allowAddSiteAssignment with resource string : " + resourceString);
}
// check security on the channel (throws if not permitted)
return unlockCheck(SECURE_ADD_ASSIGNMENT, resourceString);
}
/**
* @inheritDoc
*/
public boolean allowAllGroups(String context)
{
String resourceString = getContextReference(context);
{
M_log.debug(this + " allowAllGroups with resource string : " + resourceString);
}
// checking all.groups
if (unlockCheck(SECURE_ALL_GROUPS, resourceString)) return true;
// if not
return false;
}
/**
* @inheritDoc
*/
public Collection getGroupsAllowAddAssignment(String context)
{
return getGroupsAllowFunction(SECURE_ADD_ASSIGNMENT, context, null);
}
/**
* @inheritDoc
*/
public Collection getGroupsAllowGradeAssignment(String context, String assignmentReference)
{
Collection rv = new ArrayList();
if (allowGradeSubmission(assignmentReference))
{
// only if the user is allowed to group at all
Collection allAllowedGroups = getGroupsAllowFunction(SECURE_GRADE_ASSIGNMENT_SUBMISSION, context, null);
try
{
Assignment a = getAssignment(assignmentReference);
if (a.getAccess() == Assignment.AssignmentAccess.SITE)
{
// for site-scope assignment, return all groups
rv = allAllowedGroups;
}
else
{
Collection aGroups = a.getGroups();
// for grouped assignment, return only those also allowed for grading
for (Iterator i = allAllowedGroups.iterator(); i.hasNext();)
{
Group g = (Group) i.next();
if (aGroups.contains(g.getReference()))
{
rv.add(g);
}
}
}
}
catch (Exception e)
{
M_log.info(this + " getGroupsAllowGradeAssignment " + e.getMessage() + assignmentReference);
}
}
return rv;
}
/**
* @inherit
*/
public boolean allowGetAssignment(String context)
{
String resourceString = getContextReference(context);
{
M_log.debug(this + " allowGetAssignment with resource string : " + resourceString);
}
return unlockCheck(SECURE_ACCESS_ASSIGNMENT, resourceString);
}
/**
* @inheritDoc
*/
public Collection getGroupsAllowGetAssignment(String context)
{
return getGroupsAllowFunction(SECURE_ACCESS_ASSIGNMENT, context, null);
}
// for specified user
private Collection getGroupsAllowGetAssignment(String context, String userId)
{
return getGroupsAllowFunction(SECURE_ACCESS_ASSIGNMENT, context, userId);
}
/**
* Check permissions for updateing an Assignment.
*
* @param assignmentReference -
* The Assignment's reference.
* @return True if the current User is allowed to update the Assignment, false if not.
*/
public boolean allowUpdateAssignment(String assignmentReference)
{
M_log.debug(this + " allowUpdateAssignment with resource string : " + assignmentReference);
return unlockCheck(SECURE_UPDATE_ASSIGNMENT, assignmentReference);
}
/**
* Check permissions for removing an Assignment.
*
* @return True if the current User is allowed to remove the Assignment, false if not.
*/
public boolean allowRemoveAssignment(String assignmentReference)
{
M_log.debug(this + " allowRemoveAssignment " + assignmentReference);
// check security (throws if not permitted)
return unlockCheck(SECURE_REMOVE_ASSIGNMENT, assignmentReference);
}
/**
* @inheritDoc
*/
public Collection getGroupsAllowRemoveAssignment(String context)
{
return getGroupsAllowFunction(SECURE_REMOVE_ASSIGNMENT, context, null);
}
/**
* Get the groups of this channel's contex-site that the end user has permission to "function" in.
*
* @param function
* The function to check
*/
protected Collection getGroupsAllowFunction(String function, String context, String userId)
{
Collection rv = new ArrayList();
try
{
// get the site groups
Site site = SiteService.getSite(context);
Collection groups = site.getGroups();
if (securityService.isSuperUser())
{
// for super user, return all groups
return groups;
}
else if (userId == null)
{
// for current session user
userId = SessionManager.getCurrentSessionUserId();
}
// if the user has SECURE_ALL_GROUPS in the context (site), select all site groups
if (securityService.unlock(userId, SECURE_ALL_GROUPS, SiteService.siteReference(context)) && unlockCheck(function, SiteService.siteReference(context)))
{
return groups;
}
// otherwise, check the groups for function
// get a list of the group refs, which are authzGroup ids
Collection groupRefs = new ArrayList();
for (Iterator i = groups.iterator(); i.hasNext();)
{
Group group = (Group) i.next();
groupRefs.add(group.getReference());
}
// ask the authzGroup service to filter them down based on function
groupRefs = AuthzGroupService.getAuthzGroupsIsAllowed(userId,
function, groupRefs);
// pick the Group objects from the site's groups to return, those that are in the groupRefs list
for (Iterator i = groups.iterator(); i.hasNext();)
{
Group group = (Group) i.next();
if (groupRefs.contains(group.getReference()))
{
rv.add(group);
}
}
}
catch (IdUnusedException e)
{
M_log.debug(this + " getGroupsAllowFunction idunused :" + context + " : " + e.getMessage());
}
return rv;
}
/** ***********************************************check permissions for AssignmentContent object ******************************************* */
/**
* Check permissions for get AssignmentContent
*
* @param contentReference -
* The AssignmentContent reference.
* @return True if the current User is allowed to access the AssignmentContent, false if not.
*/
public boolean allowGetAssignmentContent(String context)
{
String resourceString = getAccessPoint(true) + Entity.SEPARATOR + "c" + Entity.SEPARATOR + context + Entity.SEPARATOR;
{
M_log.debug(this + " allowGetAssignmentContent with resource string : " + resourceString);
}
// check security (throws if not permitted)
return unlockCheck(SECURE_ACCESS_ASSIGNMENT_CONTENT, resourceString);
}
/**
* Check permissions for updating AssignmentContent
*
* @param contentReference -
* The AssignmentContent reference.
* @return True if the current User is allowed to update the AssignmentContent, false if not.
*/
public boolean allowUpdateAssignmentContent(String contentReference)
{
M_log.debug(this + " allowUpdateAssignmentContent with resource string : " + contentReference);
// check security (throws if not permitted)
return unlockCheck(SECURE_UPDATE_ASSIGNMENT_CONTENT, contentReference);
}
/**
* Check permissions for adding an AssignmentContent.
*
* @param context -
* Describes the portlet context - generated with DefaultId.getChannel().
* @return True if the current User is allowed to add an AssignmentContent, false if not.
*/
public boolean allowAddAssignmentContent(String context)
{
String resourceString = getAccessPoint(true) + Entity.SEPARATOR + "c" + Entity.SEPARATOR + context + Entity.SEPARATOR;
M_log.debug(this + "allowAddAssignmentContent with resource string : " + resourceString);
// check security (throws if not permitted)
if (unlockCheck(SECURE_ADD_ASSIGNMENT_CONTENT, resourceString)) return true;
// if not, see if the user has any groups to which adds are allowed
return (!getGroupsAllowAddAssignment(context).isEmpty());
}
/**
* Check permissions for remove the AssignmentContent
*
* @param contentReference -
* The AssignmentContent reference.
* @return True if the current User is allowed to remove the AssignmentContent, false if not.
*/
public boolean allowRemoveAssignmentContent(String contentReference)
{
M_log.debug(this + " allowRemoveAssignmentContent with referece string : " + contentReference);
// check security (throws if not permitted)
return unlockCheck(SECURE_REMOVE_ASSIGNMENT_CONTENT, contentReference);
}
/**
* Check permissions for add AssignmentSubmission
*
* @param context -
* Describes the portlet context - generated with DefaultId.getChannel().
* @return True if the current User is allowed to add an AssignmentSubmission, false if not.
*/
public boolean allowAddSubmission(String context)
{
// check security (throws if not permitted)
String resourceString = getAccessPoint(true) + Entity.SEPARATOR + "s" + Entity.SEPARATOR + context + Entity.SEPARATOR;
M_log.debug(this + " allowAddSubmission with resource string : " + resourceString);
return unlockCheck(SECURE_ADD_ASSIGNMENT_SUBMISSION, resourceString);
}
/**
* SAK-21525
*
* @param context
* @param assignment - An Assignment object. Needed for the groups to be checked.
* @return
*/
public boolean allowAddSubmissionCheckGroups(String context, Assignment assignment)
{
// check security (throws if not permitted)
String resourceString = getAccessPoint(true) + Entity.SEPARATOR + "s" + Entity.SEPARATOR + context + Entity.SEPARATOR;
M_log.debug(this + " allowAddSubmission with resource string : " + resourceString);
return unlockCheckWithGroups(SECURE_ADD_ASSIGNMENT_SUBMISSION, resourceString, assignment);
}
/**
* Get the List of Users who can addSubmission() for this assignment.
*
* @param assignmentReference -
* a reference to an assignment
* @return the List (User) of users who can addSubmission() for this assignment.
*/
public List allowAddSubmissionUsers(String assignmentReference)
{
return securityService.unlockUsers(SECURE_ADD_ASSIGNMENT_SUBMISSION, assignmentReference);
} // allowAddSubmissionUsers
/**
* Get the List of Users who can grade submission for this assignment.
*
* @param assignmentReference -
* a reference to an assignment
* @return the List (User) of users who can grade submission for this assignment.
*/
public List allowGradeAssignmentUsers(String assignmentReference)
{
List users = securityService.unlockUsers(SECURE_GRADE_ASSIGNMENT_SUBMISSION, assignmentReference);
if (users == null)
{
users = new ArrayList();
}
try
{
Assignment a = getAssignment(assignmentReference);
if (a.getAccess() == Assignment.AssignmentAccess.GROUPED)
{
// for grouped assignment, need to include those users that with "all.groups" and "grade assignment" permissions on the site level
AuthzGroup group = AuthzGroupService.getAuthzGroup(SiteService.siteReference(a.getContext()));
if (group != null)
{
// get the roles which are allowed for submission but not for all_site control
Set rolesAllowAllSite = group.getRolesIsAllowed(SECURE_ALL_GROUPS);
Set rolesAllowGradeAssignment = group.getRolesIsAllowed(SECURE_GRADE_ASSIGNMENT_SUBMISSION);
// save all the roles with both "all.groups" and "grade assignment" permissions
if (rolesAllowAllSite != null)
rolesAllowAllSite.retainAll(rolesAllowGradeAssignment);
if (rolesAllowAllSite != null && rolesAllowAllSite.size() > 0)
{
for (Iterator iRoles = rolesAllowAllSite.iterator(); iRoles.hasNext(); )
{
Set<String> userIds = group.getUsersHasRole((String) iRoles.next());
if (userIds != null)
{
for (Iterator<String> iUserIds = userIds.iterator(); iUserIds.hasNext(); )
{
String userId = iUserIds.next();
try
{
User u = UserDirectoryService.getUser(userId);
if (!users.contains(u))
{
users.add(u);
}
}
catch (Exception ee)
{
M_log.warn(" allowGradeAssignmentUsers " + ee.getMessage() + " problem with getting user =" + userId);
}
}
}
}
}
}
}
}
catch (Exception e)
{
M_log.warn(" allowGradeAssignmentUsers " + e.getMessage() + " assignmentReference=" + assignmentReference);
}
return users;
} // allowGradeAssignmentUsers
/**
* @inheritDoc
* @param context
* @return
*/
public List allowAddAnySubmissionUsers(String context)
{
List<String> rv = new Vector();
try
{
AuthzGroup group = AuthzGroupService.getAuthzGroup(SiteService.siteReference(context));
// get the roles which are allowed for submission but not for all_site control
Set rolesAllowSubmission = group.getRolesIsAllowed(SECURE_ADD_ASSIGNMENT_SUBMISSION);
Set rolesAllowAllSite = group.getRolesIsAllowed(SECURE_ALL_GROUPS);
rolesAllowSubmission.removeAll(rolesAllowAllSite);
for (Iterator iRoles = rolesAllowSubmission.iterator(); iRoles.hasNext(); )
{
rv.addAll(group.getUsersHasRole((String) iRoles.next()));
}
}
catch (Exception e)
{
M_log.warn(" allowAddAnySubmissionUsers " + e.getMessage() + " context=" + context);
}
return rv;
}
/**
* Get the List of Users who can add assignment
*
* @param assignmentReference -
* a reference to an assignment
* @return the List (User) of users who can addSubmission() for this assignment.
*/
public List allowAddAssignmentUsers(String context)
{
String resourceString = getContextReference(context);
{
M_log.debug(this + " allowAddAssignmentUsers with resource string : " + resourceString);
M_log.debug(" context string : " + context);
}
return securityService.unlockUsers(SECURE_ADD_ASSIGNMENT, resourceString);
} // allowAddAssignmentUsers
/**
* Check permissions for accessing a Submission.
*
* @param submissionReference -
* The Submission's reference.
* @return True if the current User is allowed to get the AssignmentSubmission, false if not.
*/
public boolean allowGetSubmission(String submissionReference)
{
M_log.debug(this + " allowGetSubmission with resource string : " + submissionReference);
return unlockCheck2(SECURE_ACCESS_ASSIGNMENT_SUBMISSION, SECURE_ACCESS_ASSIGNMENT, submissionReference);
}
/**
* Check permissions for updating Submission.
*
* @param submissionReference -
* The Submission's reference.
* @return True if the current User is allowed to update the AssignmentSubmission, false if not.
*/
public boolean allowUpdateSubmission(String submissionReference)
{
M_log.debug(this + " allowUpdateSubmission with resource string : " + submissionReference);
return unlockCheck2(SECURE_UPDATE_ASSIGNMENT_SUBMISSION, SECURE_UPDATE_ASSIGNMENT, submissionReference);
}
/**
* Check permissions for remove Submission
*
* @param submissionReference -
* The Submission's reference.
* @return True if the current User is allowed to remove the AssignmentSubmission, false if not.
*/
public boolean allowRemoveSubmission(String submissionReference)
{
M_log.debug(this + " allowRemoveSubmission with resource string : " + submissionReference);
// check security (throws if not permitted)
return unlockCheck(SECURE_REMOVE_ASSIGNMENT_SUBMISSION, submissionReference);
}
public boolean allowGradeSubmission(String assignmentReference)
{
{
M_log.debug(this + " allowGradeSubmission with resource string : " + assignmentReference);
}
return unlockCheck(SECURE_GRADE_ASSIGNMENT_SUBMISSION, assignmentReference);
}
/**
* Access the grades spreadsheet for the reference, either for an assignment or all assignments in a context.
*
* @param ref
* The reference, either to a specific assignment, or just to an assignment context.
* @return The grades spreadsheet bytes.
* @throws IdUnusedException
* if there is no object with this id.
* @throws PermissionException
* if the current user is not allowed to access this.
*/
public byte[] getGradesSpreadsheet(String ref) throws IdUnusedException, PermissionException
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (getGradesSpreadsheet(out, ref)) {
return out.toByteArray();
}
return null;
}
/**
* Access and output the grades spreadsheet for the reference, either for an assignment or all assignments in a context.
*
* @param out
* The outputStream to stream the grades spreadsheet into.
* @param ref
* The reference, either to a specific assignment, or just to an assignment context.
* @return Whether the grades spreadsheet is successfully output.
* @throws IdUnusedException
* if there is no object with this id.
* @throws PermissionException
* if the current user is not allowed to access this.
*/
public boolean getGradesSpreadsheet(final OutputStream out, final String ref)
throws IdUnusedException, PermissionException {
boolean retVal = false;
String typeGradesString = REF_TYPE_GRADES + Entity.SEPARATOR;
String context = ref.substring(ref.indexOf(typeGradesString) + typeGradesString.length());
// get site title for display purpose
String siteTitle = "";
try
{
Site s = SiteService.getSite(context);
siteTitle = s.getTitle();
}
catch (Exception e)
{
// ignore exception
M_log.debug(this + ":getGradesSpreadsheet cannot get site context=" + context + e.getMessage());
}
// does current user allowed to grade any assignment?
boolean allowGradeAny = false;
List assignmentsList = getListAssignmentsForContext(context);
for (int iAssignment = 0; !allowGradeAny && iAssignment<assignmentsList.size(); iAssignment++)
{
if (allowGradeSubmission(((Assignment) assignmentsList.get(iAssignment)).getReference()))
{
allowGradeAny = true;
}
}
if (!allowGradeAny)
{
// not permitted to download the spreadsheet
return false;
}
else
{
short rowNum = 0;
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(WorkbookUtil.createSafeSheetName(siteTitle));
// Create a row and put some cells in it. Rows are 0 based.
HSSFRow row = sheet.createRow(rowNum++);
row.createCell((short) 0).setCellValue(rb.getString("download.spreadsheet.title"));
// empty line
row = sheet.createRow(rowNum++);
row.createCell((short) 0).setCellValue("");
// site title
row = sheet.createRow(rowNum++);
row.createCell((short) 0).setCellValue(rb.getString("download.spreadsheet.site") + siteTitle);
// download time
row = sheet.createRow(rowNum++);
row.createCell((short) 0).setCellValue(
rb.getString("download.spreadsheet.date") + TimeService.newTime().toStringLocalFull());
// empty line
row = sheet.createRow(rowNum++);
row.createCell((short) 0).setCellValue("");
HSSFCellStyle style = wb.createCellStyle();
// this is the header row number
short headerRowNumber = rowNum;
// set up the header cells
row = sheet.createRow(rowNum++);
short cellNum = 0;
// user enterprise id column
HSSFCell cell = row.createCell(cellNum++);
cell.setCellStyle(style);
cell.setCellValue(rb.getString("download.spreadsheet.column.name"));
// user name column
cell = row.createCell(cellNum++);
cell.setCellStyle(style);
cell.setCellValue(rb.getString("download.spreadsheet.column.userid"));
// starting from this row, going to input user data
Iterator assignments = new SortedIterator(assignmentsList.iterator(), new AssignmentComparator("duedate", "true"));
// site members excluding those who can add assignments
List members = new ArrayList();
// hashmap which stores the Excel row number for particular user
HashMap user_row = new HashMap();
List allowAddAnySubmissionUsers = allowAddAnySubmissionUsers(context);
for (Iterator iUserIds = new SortedIterator(allowAddAnySubmissionUsers.iterator(), new AssignmentComparator("sortname", "true")); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
try
{
User u = UserDirectoryService.getUser(userId);
members.add(u);
// create the column for user first
row = sheet.createRow(rowNum);
// update user_row Hashtable
user_row.put(u.getId(), Integer.valueOf(rowNum));
// increase row
rowNum++;
// put user displayid and sortname in the first two cells
cellNum = 0;
row.createCell(cellNum++).setCellValue(u.getSortName());
row.createCell(cellNum).setCellValue(u.getDisplayId());
}
catch (Exception e)
{
M_log.warn(" getGradesSpreadSheet " + e.getMessage() + " userId = " + userId);
}
}
int index = 0;
// the grade data portion starts from the third column, since the first two are used for user's display id and sort name
while (assignments.hasNext())
{
Assignment a = (Assignment) assignments.next();
int assignmentType = a.getContent().getTypeOfGrade();
// for column header, check allow grade permission based on each assignment
if(!a.getDraft() && allowGradeSubmission(a.getReference()))
{
// put in assignment title as the column header
rowNum = headerRowNumber;
row = sheet.getRow(rowNum++);
cellNum = (short) (index + 2);
cell = row.createCell(cellNum); // since the first two column is taken by student id and name
cell.setCellStyle(style);
cell.setCellValue(a.getTitle());
for (int loopNum = 0; loopNum < members.size(); loopNum++)
{
// prepopulate the column with the "no submission" string
row = sheet.getRow(rowNum++);
cell = row.createCell(cellNum);
cell.setCellType(1);
cell.setCellValue(rb.getString("listsub.nosub"));
}
// begin to populate the column for this assignment, iterating through student list
for (Iterator sIterator=getSubmissions(a).iterator(); sIterator.hasNext();)
{
AssignmentSubmission submission = (AssignmentSubmission) sIterator.next();
String userId = submission.getSubmitterId();
if (a.isGroup()) {
User[] _users = submission.getSubmitters();
for (int i=0; _users != null && i < _users.length; i++) {
userId = _users[i].getId();
if (user_row.containsKey(userId))
{
// find right row
row = sheet.getRow(((Integer)user_row.get(userId)).intValue());
if (submission.getGraded() && submission.getGrade() != null)
{
// graded and released
if (assignmentType == 3)
{
try
{
// numeric cell type?
String grade = submission.getGradeForUser(userId) == null ? submission.getGradeDisplay():
submission.getGradeForUser(userId);
//We get float number no matter the locale it was managed with.
NumberFormat nbFormat = NumberFormat.getNumberInstance(rb.getLocale());
nbFormat.setMaximumFractionDigits(1);
nbFormat.setMinimumFractionDigits(1);
float f = nbFormat.parse(grade).floatValue();
// remove the String-based cell first
cell = row.getCell(cellNum);
row.removeCell(cell);
// add number based cell
cell=row.createCell(cellNum);
cell.setCellType(0);
cell.setCellValue(f);
style = wb.createCellStyle();
style.setDataFormat(wb.createDataFormat().getFormat("#,##0.0"));
cell.setCellStyle(style);
}
catch (Exception e)
{
// if the grade is not numeric, let's make it as String type
// No need to remove the cell and create a new one, as the existing one is String type.
cell = row.getCell(cellNum);
cell.setCellType(1);
cell.setCellValue(submission.getGradeForUser(userId) == null ? submission.getGradeDisplay():
submission.getGradeForUser(userId));
}
}
else
{
// String cell type
cell = row.getCell(cellNum);
cell.setCellValue(submission.getGradeForUser(userId) == null ? submission.getGradeDisplay():
submission.getGradeForUser(userId));
}
}
else if (submission.getSubmitted() && submission.getTimeSubmitted() != null)
{
// submitted, but no grade available yet
cell = row.getCell(cellNum);
cell.setCellValue(rb.getString("gen.nograd"));
}
} // if
}
}
else
{
if (user_row.containsKey(userId))
{
// find right row
row = sheet.getRow(((Integer)user_row.get(userId)).intValue());
if (submission.getGraded() && submission.getGrade() != null)
{
// graded and released
if (assignmentType == 3)
{
try
{
// numeric cell type?
String grade = submission.getGradeDisplay();
//We get float number no matter the locale it was managed with.
NumberFormat nbFormat = NumberFormat.getNumberInstance(rb.getLocale());
nbFormat.setMaximumFractionDigits(1);
nbFormat.setMinimumFractionDigits(1);
float f = nbFormat.parse(grade).floatValue();
// remove the String-based cell first
cell = row.getCell(cellNum);
row.removeCell(cell);
// add number based cell
cell=row.createCell(cellNum);
cell.setCellType(0);
cell.setCellValue(f);
style = wb.createCellStyle();
style.setDataFormat(wb.createDataFormat().getFormat("#,##0.0"));
cell.setCellStyle(style);
}
catch (Exception e)
{
// if the grade is not numeric, let's make it as String type
// No need to remove the cell and create a new one, as the existing one is String type.
cell = row.getCell(cellNum);
cell.setCellType(1);
// Setting grade display instead grade.
cell.setCellValue(submission.getGradeDisplay());
}
}
else
{
// String cell type
cell = row.getCell(cellNum);
cell.setCellValue(submission.getGradeDisplay());
}
}
else if (submission.getSubmitted() && submission.getTimeSubmitted() != null)
{
// submitted, but no grade available yet
cell = row.getCell(cellNum);
cell.setCellValue(rb.getString("gen.nograd"));
}
} // if
}
}
}
index++;
}
// output
try
{
wb.write(out);
retVal = true;
}
catch (IOException e)
{
M_log.warn(" getGradesSpreadsheet Can not output the grade spread sheet for reference= " + ref);
}
return retVal;
}
} // getGradesSpreadsheet
@SuppressWarnings("deprecation")
public Collection<Group> getSubmitterGroupList(String searchFilterOnly, String allOrOneGroup, String searchString, String aRef, String contextString) {
Collection<Group> rv = new ArrayList<Group>();
allOrOneGroup = StringUtil.trimToNull(allOrOneGroup);
searchString = StringUtil.trimToNull(searchString);
boolean bSearchFilterOnly = "true".equalsIgnoreCase(searchFilterOnly);
try
{
Assignment a = getAssignment(aRef);
if (a != null)
{
Site st = SiteService.getSite(contextString);
if (a.getAccess().equals(Assignment.AssignmentAccess.SITE))
{
Collection<Group> groupRefs = st.getGroups();
for (Iterator gIterator = groupRefs.iterator(); gIterator.hasNext();)
{
Group _gg = (Group)gIterator.next();
//if (_gg.getProperties().get(GROUP_SECTION_PROPERTY) == null) { // NO SECTIONS (this might not be valid test for manually created sections)
rv.add(_gg);
//}
}
}
else
{
Collection<String> groupRefs = a.getGroups();
for (Iterator gIterator = groupRefs.iterator(); gIterator.hasNext();)
{
Group _gg = st.getGroup((String)gIterator.next()); // NO SECTIONS (this might not be valid test for manually created sections)
if (_gg != null) {// && _gg.getProperties().get(GROUP_SECTION_PROPERTY) == null) {
rv.add(_gg);
}
}
}
for (Iterator uIterator = rv.iterator(); uIterator.hasNext();)
{
Group g = (Group) uIterator.next();
AssignmentSubmission uSubmission = getSubmission(aRef, g.getId());
if (uSubmission == null)
{
if (allowGradeSubmission(a.getReference()))
{
if (a.isGroup()) {
// temporarily allow the user to read and write from assignments (asn.revise permission)
SecurityAdvisor securityAdvisor = new MySecurityAdvisor(
SessionManager.getCurrentSessionUserId(),
new ArrayList<String>(Arrays.asList(SECURE_ADD_ASSIGNMENT_SUBMISSION, SECURE_UPDATE_ASSIGNMENT_SUBMISSION)),
""/* no submission id yet, pass the empty string to advisor*/);
try {
securityService.pushAdvisor(securityAdvisor);
M_log.debug(this + " getSubmitterGroupList context " + contextString + " for assignment " + a.getId() + " for group " + g.getId());
AssignmentSubmissionEdit s =
addSubmission(contextString, a.getId(), g.getId());
s.setSubmitted(false);
s.setAssignment(a);
// set the resubmission properties
// get the assignment setting for resubmitting
ResourceProperties assignmentProperties = a.getProperties();
String assignmentAllowResubmitNumber = assignmentProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
if (assignmentAllowResubmitNumber != null)
{
s.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, assignmentAllowResubmitNumber);
String assignmentAllowResubmitCloseDate = assignmentProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
// if assignment's setting of resubmit close time is null, use assignment close time as the close time for resubmit
s.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, assignmentAllowResubmitCloseDate != null?assignmentAllowResubmitCloseDate:String.valueOf(a.getCloseTime().getTime()));
}
commitEdit(s);
// clear the permission
} finally {
securityService.popAdvisor(securityAdvisor);
}
}
}
}
}
}
}
catch (IdUnusedException aIdException)
{
M_log.warn(":getSubmitterGroupList: Assignme id not used: " + aRef + " " + aIdException.getMessage());
}
catch (PermissionException aPerException)
{
M_log.warn(":getSubmitterGroupList: Not allowed to get assignment " + aRef + " " + aPerException.getMessage());
}
return rv;
}
/**
* {@inheritDoc}}
*/
public List<String> getSubmitterIdList(String searchFilterOnly, String allOrOneGroup, String searchString, String aRef, String contextString) {
List<String> rv = new ArrayList<String>();
List<User> rvUsers = new ArrayList<User>();
allOrOneGroup = StringUtils.trimToNull(allOrOneGroup);
searchString = StringUtils.trimToNull(searchString);
boolean bSearchFilterOnly = "true".equalsIgnoreCase(searchFilterOnly);
try
{
Assignment a = getAssignment(aRef);
if (a != null)
{
if (bSearchFilterOnly)
{
if (allOrOneGroup == null && searchString == null)
{
// if the option is set to "Only show user submissions according to Group Filter and Search result"
// if no group filter and no search string is specified, no user will be shown first by default;
return rv;
}
else
{
List allowAddSubmissionUsers = allowAddSubmissionUsers(aRef);
if (allOrOneGroup == null && searchString != null)
{
// search is done for all submitters
rvUsers = getSearchedUsers(searchString, allowAddSubmissionUsers, false);
}
else
{
// group filter first
rvUsers = getSelectedGroupUsers(allOrOneGroup, contextString, a, allowAddSubmissionUsers);
if (searchString != null)
{
// then search
rvUsers = getSearchedUsers(searchString, rvUsers, true);
}
}
}
}
else
{
List allowAddSubmissionUsers = allowAddSubmissionUsers(aRef);
List allowAddAssignmentUsers = allowAddAssignmentUsers(contextString);
// SAK-25555 need to take away those users who can add assignment
allowAddSubmissionUsers.removeAll(allowAddAssignmentUsers);
// Step 1: get group if any that is selected
rvUsers = getSelectedGroupUsers(allOrOneGroup, contextString, a, allowAddSubmissionUsers);
// Step 2: get all student that meets the search criteria based on previous group users. If search is null or empty string, return all users.
rvUsers = getSearchedUsers(searchString, rvUsers, true);
}
if (!rvUsers.isEmpty())
{
List<String> groupRefs = new ArrayList<String>();
for (Iterator uIterator = rvUsers.iterator(); uIterator.hasNext();)
{
User u = (User) uIterator.next();
AssignmentSubmission uSubmission = getSubmission(aRef, u);
if (uSubmission != null)
{
rv.add(u.getId());
}
// add those users who haven't made any submissions and with submission rights
else
{
//only initiate the group list once
if (groupRefs.isEmpty())
{
if (a.getAccess() == Assignment.AssignmentAccess.SITE)
{
// for site range assignment, add the site reference first
groupRefs.add(SiteService.siteReference(contextString));
}
// add all groups inside the site
Collection groups = getGroupsAllowGradeAssignment(contextString, a.getReference());
for(Object g : groups)
{
if (g instanceof Group)
{
groupRefs.add(((Group) g).getReference());
}
}
}
// construct fake submissions for grading purpose if the user has right for grading
if (allowGradeSubmission(a.getReference()))
{
SecurityAdvisor securityAdvisor = new MySecurityAdvisor(
SessionManager.getCurrentSessionUserId(),
new ArrayList<String>(Arrays.asList(SECURE_ADD_ASSIGNMENT_SUBMISSION, SECURE_UPDATE_ASSIGNMENT_SUBMISSION)),
groupRefs/* no submission id yet, pass the empty string to advisor*/);
try
{
// temporarily allow the user to read and write from assignments (asn.revise permission)
securityService.pushAdvisor(securityAdvisor);
AssignmentSubmissionEdit s = addSubmission(contextString, a.getId(), u.getId());
if (s != null)
{
s.setSubmitted(false);
s.setAssignment(a);
// set the resubmission properties
// get the assignment setting for resubmitting
ResourceProperties assignmentProperties = a.getProperties();
String assignmentAllowResubmitNumber = assignmentProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
if (assignmentAllowResubmitNumber != null)
{
s.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, assignmentAllowResubmitNumber);
String assignmentAllowResubmitCloseDate = assignmentProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
// if assignment's setting of resubmit close time is null, use assignment close time as the close time for resubmit
s.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, assignmentAllowResubmitCloseDate != null?assignmentAllowResubmitCloseDate:String.valueOf(a.getCloseTime().getTime()));
}
commitEdit(s);
rv.add(u.getId());
}
}
finally
{
// clear the permission
securityService.popAdvisor(securityAdvisor);
}
}
}
}
}
}
}
catch (IdUnusedException aIdException)
{
M_log.warn(":getSubmitterIdList: Assignme id not used: " + aRef + " " + aIdException.getMessage());
}
catch (PermissionException aPerException)
{
M_log.warn(":getSubmitterIdList: Not allowed to get assignment " + aRef + " " + aPerException.getMessage());
}
return rv;
}
private List<User> getSelectedGroupUsers(String allOrOneGroup, String contextString, Assignment a, List allowAddSubmissionUsers) {
Collection groups = new ArrayList();
List<User> selectedGroupUsers = new ArrayList<User>();
if (allOrOneGroup != null && allOrOneGroup.length() > 0)
{
// now are we view all sections/groups or just specific one?
if (allOrOneGroup.equals(AssignmentConstants.ALL))
{
if (allowAllGroups(contextString))
{
// site range
try {
groups.add(SiteService.getSite(contextString));
} catch (IdUnusedException e) {
M_log.warn(":getSelectedGroupUsers cannot find site " + " " + contextString + e.getMessage());
}
}
else
{
// get all those groups that user is allowed to grade
groups = getGroupsAllowGradeAssignment(contextString, a.getReference());
}
}
else
{
// filter out only those submissions from the selected-group members
try
{
Group group = SiteService.getSite(contextString).getGroup(allOrOneGroup);
groups.add(group);
}
catch (Exception e)
{
M_log.warn(":getSelectedGroupUsers " + e.getMessage() + " groupId=" + allOrOneGroup);
}
}
for (Iterator iGroup=groups.iterator(); iGroup.hasNext();)
{
Object nGroup = iGroup.next();
String authzGroupRef = (nGroup instanceof Group)? ((Group) nGroup).getReference():((nGroup instanceof Site))?((Site) nGroup).getReference():null;
if (authzGroupRef != null)
{
try
{
AuthzGroup group = AuthzGroupService.getAuthzGroup(authzGroupRef);
Set grants = group.getUsers();
for (Iterator iUserIds = grants.iterator(); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
// don't show user multiple times
try
{
User u = UserDirectoryService.getUser(userId);
if (u != null && allowAddSubmissionUsers.contains(u))
{
if (!selectedGroupUsers.contains(u))
{
selectedGroupUsers.add(u);
}
}
}
catch (UserNotDefinedException uException)
{
M_log.warn(":getSelectedGroupUsers " + uException.getMessage() + " userId =" + userId);
}
}
}
catch (GroupNotDefinedException gException)
{
M_log.warn(":getSelectedGroupUsers " + gException.getMessage() + " authGroupId=" + authzGroupRef);
}
}
}
}
return selectedGroupUsers;
}
/**
* keep the users that match search string in sortname, eid, email field
* @param searchString
* @param userList
* @param retain If true, the original list will be kept if there is no search string specified
* @return
*/
private List getSearchedUsers(String searchString, List userList, boolean retain) {
List rv = new ArrayList();
if (searchString != null && searchString.length() > 0)
{
searchString = searchString.toLowerCase();
for(Iterator iUserList = userList.iterator(); iUserList.hasNext();)
{
User u = (User) iUserList.next();
// search on user sortname, eid, email
String[] fields = {u.getSortName(), u.getEid(), u.getEmail()};
List<String> l = new ArrayList(Arrays.asList(fields));
for (String s : l)
{
s = s.toLowerCase();
if (s != null && s.indexOf(searchString) != -1)
{
rv.add(u);
break;
}
}
}
}
else if (retain)
{
// retain the original list
rv = userList;
}
return rv;
}
/**
* {@inheritDoc}
*/
public void getSubmissionsZip(OutputStream outputStream, String ref) throws IdUnusedException, PermissionException
{
M_log.debug(this + ": getSubmissionsZip reference=" + ref);
getSubmissionsZip(outputStream, ref, null);
}
/**
* depends on the query string from ui, determine what to include inside the submission zip
* @param outputStream
* @param ref
* @param queryString
* @throws IdUnusedException
* @throws PermissionException
*/
protected void getSubmissionsZip(OutputStream out, String ref, String queryString) throws IdUnusedException, PermissionException
{
M_log.debug(this + ": getSubmissionsZip 2 reference=" + ref);
boolean withStudentSubmissionText = false;
boolean withStudentSubmissionAttachment = false;
boolean withGradeFile = false;
boolean withFeedbackText = false;
boolean withFeedbackComment = false;
boolean withFeedbackAttachment = false;
boolean withoutFolders = false;
String viewString = "";
String contextString = "";
String searchString = "";
String searchFilterOnly = "";
if (queryString != null)
{
StringTokenizer queryTokens = new StringTokenizer(queryString, "&");
// Parsing the range list
while (queryTokens.hasMoreTokens()) {
String token = queryTokens.nextToken().trim();
// check against the content elements selection
if (token.contains("studentSubmissionText"))
{
// should contain student submission text information
withStudentSubmissionText = true;
}
else if (token.contains("studentSubmissionAttachment"))
{
// should contain student submission attachment information
withStudentSubmissionAttachment = true;
}
else if (token.contains("gradeFile"))
{
// should contain grade file
withGradeFile = true;
}
else if (token.contains("feedbackTexts"))
{
// inline text
withFeedbackText = true;
}
else if (token.contains("feedbackComments"))
{
// comments should be available
withFeedbackComment = true;
}
else if (token.contains("feedbackAttachments"))
{
// feedback attachment
withFeedbackAttachment = true;
}
else if (token.contains("withoutFolders"))
{
// feedback attachment
withoutFolders = true;
}
else if (token.contains("contextString"))
{
// context
contextString = token.indexOf("=") != -1 ? token.substring(token.indexOf("=") + 1) : "";
}
else if (token.contains("viewString"))
{
// view
viewString = token.indexOf("=") != -1 ? token.substring(token.indexOf("=") + 1) : "";
}
else if (token.contains("searchString"))
{
// search
searchString = token.indexOf("=") != -1 ? token.substring(token.indexOf("=") + 1) : "";
}
else if (token.contains("searchFilterOnly"))
{
// search and group filter only
searchFilterOnly = token.indexOf("=") != -1 ? token.substring(token.indexOf("=") + 1) : "";
}
}
}
byte[] rv = null;
try
{
String aRef = assignmentReferenceFromSubmissionsZipReference(ref);
Assignment a = getAssignment(aRef);
if (a.isGroup()) {
Collection<Group> submitterGroups = getSubmitterGroupList(searchFilterOnly, viewString.length() == 0 ? AssignmentConstants.ALL:viewString, searchString, aRef, contextString == null ? a.getContext(): contextString);
if (submitterGroups != null && !submitterGroups.isEmpty())
{
List<GroupSubmission> submissions = new ArrayList<GroupSubmission>();
for (Iterator<Group> iSubmitterGroupsIterator = submitterGroups.iterator(); iSubmitterGroupsIterator.hasNext();)
{
Group g = iSubmitterGroupsIterator.next();
M_log.debug(this + " ZIP GROUP " + g.getTitle() );
AssignmentSubmission sub = getSubmission(aRef, g.getId());
M_log.debug(this + " ZIP GROUP " + g.getTitle() + " SUB " + (sub == null ? "null": sub.getId() ));
if (g != null) {
GroupSubmission gs = new GroupSubmission(g, sub);
submissions.add(gs);
}
}
StringBuilder exceptionMessage = new StringBuilder();
if (allowGradeSubmission(aRef))
{
zipGroupSubmissions(aRef, a.getTitle(), a.getContent().getTypeOfGradeString(a.getContent().getTypeOfGrade()), a.getContent().getTypeOfSubmission(),
new SortedIterator(submissions.iterator(), new AssignmentComparator("submitterName", "true")), out, exceptionMessage, withStudentSubmissionText, withStudentSubmissionAttachment, withGradeFile, withFeedbackText, withFeedbackComment, withFeedbackAttachment);
if (exceptionMessage.length() > 0)
{
// log any error messages
M_log.warn(" getSubmissionsZip ref=" + ref + exceptionMessage.toString());
}
}
}
}
else
{
List<String> submitterIds = getSubmitterIdList(searchFilterOnly, viewString.length() == 0 ? AssignmentConstants.ALL:viewString, searchString, aRef, contextString == null? a.getContext():contextString);
if (submitterIds != null && !submitterIds.isEmpty())
{
List<AssignmentSubmission> submissions = new ArrayList<AssignmentSubmission>();
for (Iterator<String> iSubmitterIdsIterator = submitterIds.iterator(); iSubmitterIdsIterator.hasNext();)
{
String uId = iSubmitterIdsIterator.next();
try
{
User u = UserDirectoryService.getUser(uId);
AssignmentSubmission sub = getSubmission(aRef, u);
if (sub != null)
submissions.add(sub);
}
catch (UserNotDefinedException e)
{
M_log.warn(":getSubmissionsZip cannot find user id=" + uId + e.getMessage() + "");
}
}
StringBuilder exceptionMessage = new StringBuilder();
if (allowGradeSubmission(aRef))
{
zipSubmissions(aRef, a.getTitle(), a.getContent().getTypeOfGradeString(a.getContent().getTypeOfGrade()), a.getContent().getTypeOfSubmission(),
new SortedIterator(submissions.iterator(), new AssignmentComparator("submitterName", "true")), out, exceptionMessage, withStudentSubmissionText, withStudentSubmissionAttachment, withGradeFile, withFeedbackText, withFeedbackComment, withFeedbackAttachment, withoutFolders);
if (exceptionMessage.length() > 0)
{
// log any error messages
M_log.warn(" getSubmissionsZip ref=" + ref + exceptionMessage.toString());
}
}
}
}
}
catch (IdUnusedException e)
{
M_log.debug(this + "getSubmissionsZip -IdUnusedException Unable to get assignment " + ref);
throw new IdUnusedException(ref);
}
catch (PermissionException e)
{
M_log.warn(" getSubmissionsZip -PermissionException Not permitted to get assignment " + ref);
throw new PermissionException(SessionManager.getCurrentSessionUserId(), SECURE_ACCESS_ASSIGNMENT, ref);
}
} // getSubmissionsZip
public String escapeInvalidCharsEntry(String accentedString) {
String decomposed = Normalizer.normalize(accentedString, Normalizer.Form.NFD);
String cleanString = decomposed.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
return cleanString;
}
protected void zipGroupSubmissions(String assignmentReference, String assignmentTitle, String gradeTypeString, int typeOfSubmission, Iterator submissions, OutputStream outputStream, StringBuilder exceptionMessage, boolean withStudentSubmissionText, boolean withStudentSubmissionAttachment, boolean withGradeFile, boolean withFeedbackText, boolean withFeedbackComment, boolean withFeedbackAttachment)
{
ZipOutputStream out = null;
try {
out = new ZipOutputStream(outputStream);
// create the folder structure - named after the assignment's title
String root = Validator.escapeZipEntry(assignmentTitle) + Entity.SEPARATOR;
String submittedText = "";
if (!submissions.hasNext())
{
exceptionMessage.append("There is no submission yet. ");
}
// the buffer used to store grade information
StringBuilder gradesBuffer = new StringBuilder(assignmentTitle + "," + gradeTypeString + "\n\n");
gradesBuffer.append("Group" + "," + rb.getString("grades.eid") + "," + "Users" + "," + rb.getString("grades.grade") + "\n");
// allow add assignment members
List allowAddSubmissionUsers = allowAddSubmissionUsers(assignmentReference);
// Create the ZIP file
String submittersName = "";
int count = 1;
String caughtException = null;
while (submissions.hasNext())
{
GroupSubmission gs = (GroupSubmission) submissions.next();
AssignmentSubmission s = gs.getSubmission();
M_log.debug( this + " ZIPGROUP " + ( s == null ? "null": s.getId() ));
if (s.getSubmitted())
{
try
{
count = 1;
submittersName = root;
User[] submitters = s.getSubmitters();
String submitterString = gs.getGroup().getTitle() + " (" + gs.getGroup().getId() + ")";
String submittersString = "";
String submitters2String = "";
for (int i = 0; i < submitters.length; i++)
{
if (i > 0)
{
submittersString = submittersString.concat("; ");
submitters2String = submitters2String.concat("; ");
}
String fullName = submitters[i].getSortName();
// in case the user doesn't have first name or last name
if (fullName.indexOf(",") == -1)
{
fullName=fullName.concat(",");
}
submittersString = submittersString.concat(fullName);
submitters2String = submitters2String.concat(submitters[i].getDisplayName());
// add the eid to the end of it to guarantee folder name uniqness
submittersString = submittersString + "(" + submitters[i].getEid() + ")";
}
gradesBuffer.append( gs.getGroup().getTitle() + "," + gs.getGroup().getId() + "," + submitters2String + "," + s.getGradeDisplay() + "\n");
if (StringUtil.trimToNull(submitterString) != null)
{
submittersName = submittersName.concat(StringUtil.trimToNull(submitterString));
submittedText = s.getSubmittedText();
submittersName = submittersName.concat("/");
// record submission timestamp
if (s.getSubmitted() && s.getTimeSubmitted() != null)
{
ZipEntry textEntry = new ZipEntry(submittersName + "timestamp.txt");
out.putNextEntry(textEntry);
byte[] b = (s.getTimeSubmitted().toString()).getBytes();
out.write(b);
textEntry.setSize(b.length);
out.closeEntry();
}
// create the folder structure - named after the submitter's name
if (typeOfSubmission != Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION && typeOfSubmission != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
// include student submission text
if (withStudentSubmissionText)
{
// create the text file only when a text submission is allowed
ZipEntry textEntry = new ZipEntry(submittersName + submitterString + "_submissionText" + ZIP_SUBMITTED_TEXT_FILE_TYPE);
out.putNextEntry(textEntry);
byte[] text = submittedText.getBytes();
out.write(text);
textEntry.setSize(text.length);
out.closeEntry();
}
// include student submission feedback text
if (withFeedbackText)
{
// create a feedbackText file into zip
ZipEntry fTextEntry = new ZipEntry(submittersName + "feedbackText.html");
out.putNextEntry(fTextEntry);
byte[] fText = s.getFeedbackText().getBytes();
out.write(fText);
fTextEntry.setSize(fText.length);
out.closeEntry();
}
}
if (typeOfSubmission != Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION && typeOfSubmission != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
// include student submission attachment
if (withStudentSubmissionAttachment)
{
// create a attachment folder for the submission attachments
String sSubAttachmentFolder = submittersName + rb.getString("stuviewsubm.submissatt") + "/";
ZipEntry sSubAttachmentFolderEntry = new ZipEntry(sSubAttachmentFolder);
out.putNextEntry(sSubAttachmentFolderEntry);
// add all submission attachment into the submission attachment folder
zipAttachments(out, submittersName, sSubAttachmentFolder, s.getSubmittedAttachments());
out.closeEntry();
}
}
if (withFeedbackComment)
{
// the comments.txt file to show instructor's comments
ZipEntry textEntry = new ZipEntry(submittersName + "comments" + ZIP_COMMENT_FILE_TYPE);
out.putNextEntry(textEntry);
byte[] b = FormattedText.encodeUnicode(s.getFeedbackComment()).getBytes();
out.write(b);
textEntry.setSize(b.length);
out.closeEntry();
}
if (withFeedbackAttachment)
{
// create an attachment folder for the feedback attachments
String feedbackSubAttachmentFolder = submittersName + rb.getString("download.feedback.attachment") + "/";
ZipEntry feedbackSubAttachmentFolderEntry = new ZipEntry(feedbackSubAttachmentFolder);
out.putNextEntry(feedbackSubAttachmentFolderEntry);
// add all feedback attachment folder
zipAttachments(out, submittersName, feedbackSubAttachmentFolder, s.getFeedbackAttachments());
out.closeEntry();
}
if (submittersString.trim().length() > 0) {
// the comments.txt file to show instructor's comments
ZipEntry textEntry = new ZipEntry(submittersName + "members" + ZIP_COMMENT_FILE_TYPE);
out.putNextEntry(textEntry);
byte[] b = FormattedText.encodeUnicode(submittersString).getBytes();
out.write(b);
textEntry.setSize(b.length);
out.closeEntry();
}
} // if
}
catch (Exception e)
{
caughtException = e.toString();
break;
}
} // if the user is still in site
} // while -- there is submission
if (caughtException == null)
{
// continue
if (withGradeFile)
{
// create a grades.csv file into zip
ZipEntry gradesCSVEntry = new ZipEntry(root + "grades.csv");
out.putNextEntry(gradesCSVEntry);
byte[] grades = gradesBuffer.toString().getBytes();
out.write(grades);
gradesCSVEntry.setSize(grades.length);
out.closeEntry();
}
}
else
{
// log the error
exceptionMessage.append(" Exception " + caughtException + " for creating submission zip file for assignment " + "\"" + assignmentTitle + "\"\n");
}
}
catch (IOException e)
{
exceptionMessage.append("IOException for creating submission zip file for assignment " + "\"" + assignmentTitle + "\" exception: " + e + "\n");
} finally {
// Complete the ZIP file
if (out != null) {
try {
out.finish();
out.flush();
} catch (IOException e) {
// tried
}
try {
out.close();
} catch (IOException e) {
// tried
}
}
}
}
protected void zipSubmissions(String assignmentReference, String assignmentTitle, String gradeTypeString, int typeOfSubmission, Iterator submissions, OutputStream outputStream, StringBuilder exceptionMessage, boolean withStudentSubmissionText, boolean withStudentSubmissionAttachment, boolean withGradeFile, boolean withFeedbackText, boolean withFeedbackComment, boolean withFeedbackAttachment, boolean withoutFolders)
{
ZipOutputStream out = null;
try {
out = new ZipOutputStream(outputStream);
// create the folder structure - named after the assignment's title
String root = escapeInvalidCharsEntry(Validator.escapeZipEntry(assignmentTitle)) + Entity.SEPARATOR;
String submittedText = "";
if (!submissions.hasNext())
{
exceptionMessage.append("There is no submission yet. ");
}
// the buffer used to store grade information
ByteArrayOutputStream gradesBAOS = new ByteArrayOutputStream();
CSVWriter gradesBuffer = new CSVWriter(new OutputStreamWriter(gradesBAOS));
String [] values = {assignmentTitle,gradeTypeString};
gradesBuffer.writeNext(values);
//Blank line was in original gradefile
values = new String[] {""};
gradesBuffer.writeNext(values);
values = new String[] {rb.getString("grades.id"),rb.getString("grades.eid"),rb.getString("grades.lastname"),rb.getString("grades.firstname"),rb.getString("grades.grade")};
gradesBuffer.writeNext(values);
// allow add assignment members
List allowAddSubmissionUsers = allowAddSubmissionUsers(assignmentReference);
// Create the ZIP file
String submittersName = "";
int count = 1;
String caughtException = null;
while (submissions.hasNext())
{
AssignmentSubmission s = (AssignmentSubmission) submissions.next();
if (s.getSubmitted())
{
// get the submission user id and see if the user is still in site
String userId = s.getSubmitterId();
try
{
User u = UserDirectoryService.getUser(userId);
if (allowAddSubmissionUsers.contains(u))
{
count = 1;
submittersName = root;
User[] submitters = s.getSubmitters();
String submittersString = "";
for (int i = 0; i < submitters.length; i++)
{
if (i > 0)
{
submittersString = submittersString.concat("; ");
}
String fullName = submitters[i].getSortName();
// in case the user doesn't have first name or last name
if (fullName.indexOf(",") == -1)
{
fullName=fullName.concat(",");
}
submittersString = submittersString.concat(fullName);
// add the eid to the end of it to guarantee folder name uniqness
// if user Eid contains non ascii characters, the user internal id will be used
String userEid = submitters[i].getEid();
String candidateEid = escapeInvalidCharsEntry(userEid);
if (candidateEid.equals(userEid)){
submittersString = submittersString + "(" + candidateEid + ")";
} else{
submittersString = submittersString + "(" + submitters[i].getId() + ")";
}
submittersString = escapeInvalidCharsEntry(submittersString);
// in grades file, Eid is used
values = new String [] {submitters[i].getDisplayId(), submitters[i].getEid(), submitters[i].getLastName(), submitters[i].getFirstName(), s.getGradeDisplay()};
gradesBuffer.writeNext(values);
}
if (StringUtils.trimToNull(submittersString) != null)
{
submittersName = submittersName.concat(StringUtils.trimToNull(submittersString));
submittedText = s.getSubmittedText();
if (!withoutFolders)
{
submittersName = submittersName.concat("/");
}
else
{
submittersName = submittersName.concat("_");
}
// record submission timestamp
if (!withoutFolders)
{
if (s.getSubmitted() && s.getTimeSubmitted() != null)
{
ZipEntry textEntry = new ZipEntry(submittersName + "timestamp.txt");
out.putNextEntry(textEntry);
byte[] b = (s.getTimeSubmitted().toString()).getBytes();
out.write(b);
textEntry.setSize(b.length);
out.closeEntry();
}
}
// create the folder structure - named after the submitter's name
if (typeOfSubmission != Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION && typeOfSubmission != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
// include student submission text
if (withStudentSubmissionText)
{
// create the text file only when a text submission is allowed
String submittersNameString = submittersName + submittersString;
//remove folder name if Download All is without user folders
if (withoutFolders)
{
submittersNameString = submittersName;
}
ZipEntry textEntry = new ZipEntry(submittersNameString + "_submissionText" + ZIP_SUBMITTED_TEXT_FILE_TYPE);
out.putNextEntry(textEntry);
byte[] text = submittedText.getBytes();
out.write(text);
textEntry.setSize(text.length);
out.closeEntry();
}
// include student submission feedback text
if (withFeedbackText)
{
// create a feedbackText file into zip
ZipEntry fTextEntry = new ZipEntry(submittersName + "feedbackText.html");
out.putNextEntry(fTextEntry);
byte[] fText = s.getFeedbackText().getBytes();
out.write(fText);
fTextEntry.setSize(fText.length);
out.closeEntry();
}
}
if (typeOfSubmission != Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION && typeOfSubmission != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
// include student submission attachment
if (withStudentSubmissionAttachment)
{
//remove "/" that creates a folder if Download All is without user folders
String sSubAttachmentFolder = submittersName + rb.getString("stuviewsubm.submissatt");//jh + "/";
if (!withoutFolders)
{
// create a attachment folder for the submission attachments
sSubAttachmentFolder = submittersName + rb.getString("stuviewsubm.submissatt") + "/";
sSubAttachmentFolder = escapeInvalidCharsEntry(sSubAttachmentFolder);
ZipEntry sSubAttachmentFolderEntry = new ZipEntry(sSubAttachmentFolder);
out.putNextEntry(sSubAttachmentFolderEntry);
}
else
{
sSubAttachmentFolder = sSubAttachmentFolder + "_";
//submittersName = submittersName.concat("_");
}
// add all submission attachment into the submission attachment folder
zipAttachments(out, submittersName, sSubAttachmentFolder, s.getSubmittedAttachments());
out.closeEntry();
}
}
if (withFeedbackComment)
{
// the comments.txt file to show instructor's comments
ZipEntry textEntry = new ZipEntry(submittersName + "comments" + ZIP_COMMENT_FILE_TYPE);
out.putNextEntry(textEntry);
byte[] b = FormattedText.encodeUnicode(s.getFeedbackComment()).getBytes();
out.write(b);
textEntry.setSize(b.length);
out.closeEntry();
}
if (withFeedbackAttachment)
{
// create an attachment folder for the feedback attachments
String feedbackSubAttachmentFolder = submittersName + rb.getString("download.feedback.attachment");
if (!withoutFolders)
{
feedbackSubAttachmentFolder = feedbackSubAttachmentFolder + "/";
ZipEntry feedbackSubAttachmentFolderEntry = new ZipEntry(feedbackSubAttachmentFolder);
out.putNextEntry(feedbackSubAttachmentFolderEntry);
}
else
{
submittersName = submittersName.concat("_");
}
// add all feedback attachment folder
zipAttachments(out, submittersName, feedbackSubAttachmentFolder, s.getFeedbackAttachments());
out.closeEntry();
}
} // if
}
}
catch (Exception e)
{
caughtException = e.toString();
break;
}
} // if the user is still in site
} // while -- there is submission
if (caughtException == null)
{
// continue
if (withGradeFile)
{
// create a grades.csv file into zip
ZipEntry gradesCSVEntry = new ZipEntry(root + "grades.csv");
out.putNextEntry(gradesCSVEntry);
gradesBuffer.close();
out.write(gradesBAOS.toByteArray());
gradesCSVEntry.setSize(gradesBAOS.size());
out.closeEntry();
}
}
else
{
// log the error
exceptionMessage.append(" Exception " + caughtException + " for creating submission zip file for assignment " + "\"" + assignmentTitle + "\"\n");
}
}
catch (IOException e)
{
exceptionMessage.append("IOException for creating submission zip file for assignment " + "\"" + assignmentTitle + "\" exception: " + e + "\n");
} finally {
// Complete the ZIP file
if (out != null) {
try {
out.finish();
out.flush();
} catch (IOException e) {
// tried
}
try {
out.close();
} catch (IOException e) {
// tried
}
}
}
}
private void zipAttachments(ZipOutputStream out, String submittersName, String sSubAttachmentFolder, List attachments) {
int attachedUrlCount = 0;
InputStream content = null;
HashMap<String, Integer> done = new HashMap<String, Integer> ();
for (int j = 0; j < attachments.size(); j++)
{
Reference r = (Reference) attachments.get(j);
try
{
ContentResource resource = m_contentHostingService.getResource(r.getId());
String contentType = resource.getContentType();
ResourceProperties props = r.getProperties();
String displayName = props.getPropertyFormatted(props.getNamePropDisplayName());
displayName = escapeInvalidCharsEntry(displayName);
// for URL content type, encode a redirect to the body URL
if (contentType.equalsIgnoreCase(ResourceProperties.TYPE_URL))
{
displayName = "attached_URL_" + attachedUrlCount;
attachedUrlCount++;
}
// buffered stream input
content = resource.streamContent();
byte data[] = new byte[1024 * 10];
BufferedInputStream bContent = null;
try
{
bContent = new BufferedInputStream(content, data.length);
String candidateName = sSubAttachmentFolder + displayName;
String realName = null;
Integer already = done.get(candidateName);
if (already == null) {
realName = candidateName;
done.put(candidateName, 1);
} else {
realName = candidateName + "+" + already;
done.put(candidateName, already + 1);
}
ZipEntry attachmentEntry = new ZipEntry(realName);
out.putNextEntry(attachmentEntry);
int bCount = -1;
while ((bCount = bContent.read(data, 0, data.length)) != -1)
{
out.write(data, 0, bCount);
}
try
{
out.closeEntry(); // The zip entry need to be closed
}
catch (IOException ioException)
{
M_log.warn(":zipAttachments: problem closing zip entry " + ioException);
}
}
catch (IllegalArgumentException iException)
{
M_log.warn(":zipAttachments: problem creating BufferedInputStream with content and length " + data.length + iException);
}
finally
{
if (bContent != null)
{
try
{
bContent.close(); // The BufferedInputStream needs to be closed
}
catch (IOException ioException)
{
M_log.warn(":zipAttachments: problem closing FileChannel " + ioException);
}
}
}
}
catch (PermissionException e)
{
M_log.warn(" zipAttachments--PermissionException submittersName="
+ submittersName + " attachment reference=" + r);
}
catch (IdUnusedException e)
{
M_log.warn(" zipAttachments--IdUnusedException submittersName="
+ submittersName + " attachment reference=" + r);
}
catch (TypeException e)
{
M_log.warn(" zipAttachments--TypeException: submittersName="
+ submittersName + " attachment reference=" + r);
}
catch (IOException e)
{
M_log.warn(" zipAttachments--IOException: Problem in creating the attachment file: submittersName="
+ submittersName + " attachment reference=" + r + " error " + e);
}
catch (ServerOverloadException e)
{
M_log.warn(" zipAttachments--ServerOverloadException: submittersName="
+ submittersName + " attachment reference=" + r);
}
finally
{
if (content != null)
{
try
{
content.close(); // The input stream needs to be closed
}
catch (IOException ioException)
{
M_log.warn(":zipAttachments: problem closing Inputstream content " + ioException);
}
}
}
} // for
}
/**
* Get the string to form an assignment grade spreadsheet
*
* @param context
* The assignment context String
* @param assignmentId
* The id for the assignment object; when null, indicates all assignment in that context
*/
public String gradesSpreadsheetReference(String context, String assignmentId)
{
// based on all assignment in that context
String s = REFERENCE_ROOT + Entity.SEPARATOR + REF_TYPE_GRADES + Entity.SEPARATOR + context;
if (assignmentId != null)
{
// based on the specified assignment only
s = s.concat(Entity.SEPARATOR + assignmentId);
}
return s;
} // gradesSpreadsheetReference
/**
* Get the string to form an assignment submissions zip file
*
* @param context
* The assignment context String
* @param assignmentReference
* The reference for the assignment object;
*/
public String submissionsZipReference(String context, String assignmentReference)
{
// based on the specified assignment
return REFERENCE_ROOT + Entity.SEPARATOR + REF_TYPE_SUBMISSIONS + Entity.SEPARATOR + context + Entity.SEPARATOR
+ assignmentReference;
} // submissionsZipReference
/**
* Decode the submissionsZipReference string to get the assignment reference String
*
* @param sReference
* The submissionZipReference String
* @return The assignment reference String
*/
private String assignmentReferenceFromSubmissionsZipReference(String sReference)
{
// remove the String part relating to submissions zip reference
if (sReference.indexOf(Entity.SEPARATOR +"site") == -1)
{
return sReference.substring(sReference.lastIndexOf(Entity.SEPARATOR + "assignment"));
}
else
{
return sReference.substring(sReference.lastIndexOf(Entity.SEPARATOR + "assignment"), sReference.indexOf(Entity.SEPARATOR +"site"));
}
} // assignmentReferenceFromSubmissionsZipReference
/**
* Decode the submissionsZipReference string to get the group reference String
*
* @param sReference
* The submissionZipReference String
* @return The group reference String
*/
private String groupReferenceFromSubmissionsZipReference(String sReference)
{
// remove the String part relating to submissions zip reference
if (sReference.indexOf(Entity.SEPARATOR +"site") != -1)
{
return sReference.substring(sReference.lastIndexOf(Entity.SEPARATOR + "site"));
}
else
{
return null;
}
} // assignmentReferenceFromSubmissionsZipReference
/**********************************************************************************************************************************************************************************************************************************************************
* ResourceService implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* {@inheritDoc}
*/
public String getLabel()
{
return "assignment";
}
/**
* {@inheritDoc}
*/
public boolean willArchiveMerge()
{
return true;
}
/**
* {@inheritDoc}
*/
public HttpAccess getHttpAccess()
{
return new HttpAccess()
{
public void handleAccess(HttpServletRequest req, HttpServletResponse res, Reference ref,
Collection copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException,
EntityAccessOverloadException, EntityCopyrightException
{
if (SessionManager.getCurrentSessionUserId() == null)
{
// fail the request, user not logged in yet.
}
else
{
try
{
if (REF_TYPE_SUBMISSIONS.equals(ref.getSubType()))
{
String queryString = req.getQueryString();
res.setContentType("application/zip");
res.setHeader("Content-Disposition", "attachment; filename = bulk_download.zip");
OutputStream out = null;
try
{
out = res.getOutputStream();
// get the submissions zip blob
getSubmissionsZip(out, ref.getReference(), queryString);
}
catch (Throwable ignore)
{
M_log.error(this + " getHttpAccess handleAccess " + ignore.getMessage() + " ref=" + ref.getReference());
}
finally
{
if (out != null)
{
try
{
out.flush();
out.close();
}
catch (Throwable ignore)
{
M_log.warn(": handleAccess 1 " + ignore.getMessage());
}
}
}
}
else if (REF_TYPE_GRADES.equals(ref.getSubType()))
{
res.setContentType("application/vnd.ms-excel");
res.setHeader("Content-Disposition", "attachment; filename = export_grades_file.xls");
OutputStream out = null;
try
{
out = res.getOutputStream();
getGradesSpreadsheet(out, ref.getReference());
out.flush();
out.close();
}
catch (Throwable ignore)
{
M_log.warn(": handleAccess 2 " + ignore.getMessage());
}
finally
{
if (out != null)
{
try
{
out.close();
}
catch (Throwable ignore)
{
M_log.warn(": handleAccess 3 " + ignore.getMessage());
}
}
}
}
else
{
M_log.warn("handleAccess: throw IdUnusedException " + ref.getReference());
throw new IdUnusedException(ref.getReference());
}
}
catch (Throwable t)
{
M_log.warn(" HandleAccess: caught exception " + t.toString() + " and rethrow it!");
throw new EntityNotDefinedException(ref.getReference());
}
}
}
};
}
/**
* {@inheritDoc}
*/
public boolean parseEntityReference(String reference, Reference ref)
{
if (reference.startsWith(REFERENCE_ROOT))
{
String id = null;
String subType = null;
String container = null;
String context = null;
// Note: StringUtils.split would not produce the following first null part
// Still use StringUtil here.
String[] parts = StringUtil.split(reference, Entity.SEPARATOR);
// we will get null, assignment, [a|c|s|grades|submissions], context, [auid], id
if (parts.length > 2)
{
subType = parts[2];
if (parts.length > 3)
{
// context is the container
context = parts[3];
// submissions have the assignment unique id as a container
if ("s".equals(subType))
{
if (parts.length > 5)
{
container = parts[4];
id = parts[5];
}
}
// others don't
else
{
if (parts.length > 4)
{
id = parts[4];
}
}
}
}
ref.set(APPLICATION_ID, subType, id, container, context);
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
public Entity getEntity(Reference ref)
{
Entity rv = null;
try
{
// is it an AssignmentContent object
if (REF_TYPE_CONTENT.equals(ref.getSubType()))
{
rv = getAssignmentContent(ref.getReference());
}
// is it an Assignment object
else if (REF_TYPE_ASSIGNMENT.equals(ref.getSubType()))
{
rv = getAssignment(ref.getReference());
}
// is it an AssignmentSubmission object
else if (REF_TYPE_SUBMISSION.equals(ref.getSubType()))
{
rv = getSubmission(ref.getReference());
}
else
M_log.warn("getEntity(): unknown message ref subtype: " + ref.getSubType() + " in ref: " + ref.getReference());
}
catch (PermissionException e)
{
M_log.warn("getEntity(): " + e + " ref=" + ref.getReference());
}
catch (IdUnusedException e)
{
M_log.warn("getEntity(): " + e + " ref=" + ref.getReference());
}
catch (NullPointerException e)
{
M_log.warn("getEntity(): " + e + " ref=" + ref.getReference());
}
return rv;
}
/**
* {@inheritDoc}
*/
public Collection getEntityAuthzGroups(Reference ref, String userId)
{
Collection rv = new ArrayList();
// for AssignmentService assignments:
// if access set to SITE, use the assignment and site authzGroups.
// if access set to GROUPED, use the assignment, and the groups, but not the site authzGroups.
// if the user has SECURE_ALL_GROUPS in the context, ignore GROUPED access and treat as if SITE
try
{
// for assignment
if (REF_TYPE_ASSIGNMENT.equals(ref.getSubType()))
{
// assignment
rv.add(ref.getReference());
boolean grouped = false;
Collection groups = null;
// check SECURE_ALL_GROUPS - if not, check if the assignment has groups or not
// TODO: the last param needs to be a ContextService.getRef(ref.getContext())... or a ref.getContextAuthzGroup() -ggolden
if ((userId == null) || ((!securityService.isSuperUser(userId)) && (!securityService.unlock(userId, SECURE_ALL_GROUPS, SiteService.siteReference(ref.getContext())))))
{
// get the channel to get the message to get group information
// TODO: check for efficiency, cache and thread local caching usage -ggolden
if (ref.getId() != null)
{
Assignment a = findAssignment(ref.getReference());
if (a != null)
{
grouped = Assignment.AssignmentAccess.GROUPED == a.getAccess();
groups = a.getGroups();
}
}
}
if (grouped)
{
// groups
rv.addAll(groups);
}
// not grouped
else
{
// site
ref.addSiteContextAuthzGroup(rv);
}
}
else
{
rv.add(ref.getReference());
// for content and submission, use site security setting
ref.addSiteContextAuthzGroup(rv);
}
}
catch (Throwable e)
{
M_log.warn(" getEntityAuthzGroups(): " + e.getMessage() + " ref=" + ref.getReference());
}
return rv;
}
/**
* {@inheritDoc}
*/
public String getEntityUrl(Reference ref)
{
String rv = null;
try
{
// is it an AssignmentContent object
if (REF_TYPE_CONTENT.equals(ref.getSubType()))
{
AssignmentContent c = getAssignmentContent(ref.getReference());
rv = c.getUrl();
}
// is it an Assignment object
else if (REF_TYPE_ASSIGNMENT.equals(ref.getSubType()))
{
Assignment a = getAssignment(ref.getReference());
rv = a.getUrl();
}
// is it an AssignmentSubmission object
else if (REF_TYPE_SUBMISSION.equals(ref.getSubType()))
{
AssignmentSubmission s = getSubmission(ref.getReference());
rv = s.getUrl();
}
else
M_log.warn(" getEntityUrl(): unknown message ref subtype: " + ref.getSubType() + " in ref: " + ref.getReference());
}
catch (PermissionException e)
{
M_log.warn("getEntityUrl(): " + e + " ref=" + ref.getReference());
}
catch (IdUnusedException e)
{
M_log.warn("getEntityUrl(): " + e + " ref=" + ref.getReference());
}
catch (NullPointerException e)
{
M_log.warn("getEntityUrl(): " + e + " ref=" + ref.getReference());
}
return rv;
}
/**
* {@inheritDoc}
*/
public String archive(String siteId, Document doc, Stack stack, String archivePath, List attachments)
{
// prepare the buffer for the results log
StringBuilder results = new StringBuilder();
// String assignRef = assignmentReference(siteId, SiteService.MAIN_CONTAINER);
results.append("archiving " + getLabel() + " context " + Entity.SEPARATOR + siteId + Entity.SEPARATOR
+ SiteService.MAIN_CONTAINER + ".\n");
// start with an element with our very own (service) name
Element element = doc.createElement(AssignmentService.class.getName());
((Element) stack.peek()).appendChild(element);
stack.push(element);
Iterator assignmentsIterator = getAssignmentsForContext(siteId);
while (assignmentsIterator.hasNext())
{
Assignment assignment = (Assignment) assignmentsIterator.next();
// archive this assignment
Element el = assignment.toXml(doc, stack);
element.appendChild(el);
// in order to make the assignment.xml have a better structure
// the content id attribute removed from the assignment node
// the content will be a child of assignment node
el.removeAttribute("assignmentcontent");
// then archive the related content
AssignmentContent content = (AssignmentContent) assignment.getContent();
if (content != null)
{
Element contentEl = content.toXml(doc, stack);
// assignment node has already kept the context info
contentEl.removeAttribute("context");
// collect attachments
List atts = content.getAttachments();
for (int i = 0; i < atts.size(); i++)
{
Reference ref = (Reference) atts.get(i);
// if it's in the attachment area, and not already in the list
if ((ref.getReference().startsWith("/content/attachment/")) && (!attachments.contains(ref)))
{
attachments.add(ref);
}
// in order to make assignment.xml has the consistent format with the other xml files
// move the attachments to be the children of the content, instead of the attributes
String attributeString = "attachment" + i;
String attRelUrl = contentEl.getAttribute(attributeString);
contentEl.removeAttribute(attributeString);
Element attNode = doc.createElement("attachment");
attNode.setAttribute("relative-url", attRelUrl);
contentEl.appendChild(attNode);
} // for
// make the content a childnode of the assignment node
el.appendChild(contentEl);
Iterator submissionsIterator = getSubmissions(assignment).iterator();
while (submissionsIterator.hasNext())
{
AssignmentSubmission submission = (AssignmentSubmission) submissionsIterator.next();
// archive this assignment
Element submissionEl = submission.toXml(doc, stack);
el.appendChild(submissionEl);
}
} // if
} // while
stack.pop();
return results.toString();
} // archive
/**
* Replace the WT user id with the new qualified id
*
* @param el
* The XML element holding the perproties
* @param useIdTrans
* The HashMap to track old WT id to new CTools id
*/
protected void WTUserIdTrans(Element el, Map userIdTrans)
{
NodeList children4 = el.getChildNodes();
int length4 = children4.getLength();
for (int i4 = 0; i4 < length4; i4++)
{
Node child4 = children4.item(i4);
if (child4.getNodeType() == Node.ELEMENT_NODE)
{
Element element4 = (Element) child4;
if (element4.getTagName().equals("property"))
{
String creatorId = "";
String modifierId = "";
if (element4.hasAttribute("CHEF:creator"))
{
if ("BASE64".equalsIgnoreCase(element4.getAttribute("enc")))
{
creatorId = Xml.decodeAttribute(element4, "CHEF:creator");
}
else
{
creatorId = element4.getAttribute("CHEF:creator");
}
String newCreatorId = (String) userIdTrans.get(creatorId);
if (newCreatorId != null)
{
Xml.encodeAttribute(element4, "CHEF:creator", newCreatorId);
element4.setAttribute("enc", "BASE64");
}
}
else if (element4.hasAttribute("CHEF:modifiedby"))
{
if ("BASE64".equalsIgnoreCase(element4.getAttribute("enc")))
{
modifierId = Xml.decodeAttribute(element4, "CHEF:modifiedby");
}
else
{
modifierId = element4.getAttribute("CHEF:modifiedby");
}
String newModifierId = (String) userIdTrans.get(modifierId);
if (newModifierId != null)
{
Xml.encodeAttribute(element4, "CHEF:creator", newModifierId);
element4.setAttribute("enc", "BASE64");
}
}
}
}
}
} // WTUserIdTrans
/**
* {@inheritDoc}
*/
public String merge(String siteId, Element root, String archivePath, String fromSiteId, Map attachmentNames, Map userIdTrans,
Set userListAllowImport)
{
// prepare the buffer for the results log
StringBuilder results = new StringBuilder();
int count = 0;
try
{
// pass the DOM to get new assignment ids, and adjust attachments
NodeList children2 = root.getChildNodes();
int length2 = children2.getLength();
for (int i2 = 0; i2 < length2; i2++)
{
Node child2 = children2.item(i2);
if (child2.getNodeType() == Node.ELEMENT_NODE)
{
Element element2 = (Element) child2;
if (element2.getTagName().equals("assignment"))
{
// a flag showing if continuing merging the assignment
boolean goAhead = true;
AssignmentContentEdit contentEdit = null;
// element2 now - assignment node
// adjust the id of this assignment
// String newId = IdManager.createUuid();
element2.setAttribute("id", IdManager.createUuid());
element2.setAttribute("context", siteId);
// cloneNode(false) - no children cloned
Element el2clone = (Element) element2.cloneNode(false);
// traverse this assignment node first to check if the person who last modified, has the right role.
// if no right role, mark the flag goAhead to be false.
NodeList children3 = element2.getChildNodes();
int length3 = children3.getLength();
for (int i3 = 0; i3 < length3; i3++)
{
Node child3 = children3.item(i3);
if (child3.getNodeType() == Node.ELEMENT_NODE)
{
Element element3 = (Element) child3;
// add the properties childnode to the clone of assignment node
if (element3.getTagName().equals("properties"))
{
NodeList children6 = element3.getChildNodes();
int length6 = children6.getLength();
for (int i6 = 0; i6 < length6; i6++)
{
Node child6 = children6.item(i6);
if (child6.getNodeType() == Node.ELEMENT_NODE)
{
Element element6 = (Element) child6;
if (element6.getTagName().equals("property"))
{
if (element6.getAttribute("name").equalsIgnoreCase("CHEF:modifiedby"))
{
if ("BASE64".equalsIgnoreCase(element6.getAttribute("enc")))
{
String creatorId = Xml.decodeAttribute(element6, "value");
if (!userListAllowImport.contains(creatorId)) goAhead = false;
}
else
{
String creatorId = element6.getAttribute("value");
if (!userListAllowImport.contains(creatorId)) goAhead = false;
}
}
}
}
}
}
}
} // for
// then, go ahead to merge the content and assignment
if (goAhead)
{
for (int i3 = 0; i3 < length3; i3++)
{
Node child3 = children3.item(i3);
if (child3.getNodeType() == Node.ELEMENT_NODE)
{
Element element3 = (Element) child3;
// add the properties childnode to the clone of assignment node
if (element3.getTagName().equals("properties"))
{
// add the properties childnode to the clone of assignment node
el2clone.appendChild(element3.cloneNode(true));
}
else if (element3.getTagName().equals("content"))
{
// element3 now- content node
// adjust the id of this content
String newContentId = IdManager.createUuid();
element3.setAttribute("id", newContentId);
element3.setAttribute("context", siteId);
// clone the content node without the children of <properties>
Element el3clone = (Element) element3.cloneNode(false);
// update the assignmentcontent id in assignment node
String assignContentId = "/assignment/c/" + siteId + "/" + newContentId;
el2clone.setAttribute("assignmentcontent", assignContentId);
// for content node, process the attachment or properties kids
NodeList children5 = element3.getChildNodes();
int length5 = children5.getLength();
int attCount = 0;
for (int i5 = 0; i5 < length5; i5++)
{
Node child5 = children5.item(i5);
if (child5.getNodeType() == Node.ELEMENT_NODE)
{
Element element5 = (Element) child5;
// for the node of "properties"
if (element5.getTagName().equals("properties"))
{
// for the file from WT, preform userId translation when needed
if (!userIdTrans.isEmpty())
{
WTUserIdTrans(element3, userIdTrans);
}
} // for the node of properties
el3clone.appendChild(element5.cloneNode(true));
// for "attachment" children
if (element5.getTagName().equals("attachment"))
{
// map the attachment area folder name
// filter out the invalid characters in the attachment id
// map the attachment area folder name
String oldUrl = element5.getAttribute("relative-url");
if (oldUrl.startsWith("/content/attachment/" + fromSiteId + "/"))
{
String newUrl = "/content/attachment/" + siteId + oldUrl.substring(("/content/attachment" + fromSiteId).length());
element5.setAttribute("relative-url", Validator.escapeQuestionMark(newUrl));
// transfer attachment, replace the context string and add new attachment if necessary
newUrl = transferAttachment(fromSiteId, siteId, null, oldUrl.substring("/content".length()));
element5.setAttribute("relative-url", Validator.escapeQuestionMark(newUrl));
newUrl = (String) attachmentNames.get(oldUrl);
if (newUrl != null)
{
if (newUrl.startsWith("/attachment/"))
newUrl = "/content".concat(newUrl);
element5.setAttribute("relative-url", Validator
.escapeQuestionMark(newUrl));
}
}
// map any references to this site to the new site id
else if (oldUrl.startsWith("/content/group/" + fromSiteId + "/"))
{
String newUrl = "/content/group/" + siteId
+ oldUrl.substring(("/content/group/" + fromSiteId).length());
element5.setAttribute("relative-url", Validator.escapeQuestionMark(newUrl));
}
// put the attachment back to the attribute field of content
// to satisfy the input need of mergeAssignmentContent
String attachmentString = "attachment" + attCount;
el3clone.setAttribute(attachmentString, element5.getAttribute("relative-url"));
attCount++;
} // if
} // if
} // for
// create a newassignment content
contentEdit = mergeAssignmentContent(el3clone);
commitEdit(contentEdit);
}
}
} // for
// when importing, refer to property to determine draft status
if ("false".equalsIgnoreCase(m_serverConfigurationService.getString("import.importAsDraft")))
{
String draftAttribute = el2clone.getAttribute("draft");
if (draftAttribute.equalsIgnoreCase("true") || draftAttribute.equalsIgnoreCase("false"))
el2clone.setAttribute("draft", draftAttribute);
else
el2clone.setAttribute("draft", "true");
}
else
{
el2clone.setAttribute("draft", "true");
}
// merge in this assignment
AssignmentEdit edit = mergeAssignment(el2clone);
edit.setContent(contentEdit);
commitEdit(edit);
count++;
} // if goAhead
} // if
} // if
} // for
}
catch (Exception any)
{
M_log.warn(" merge(): exception: " + any.getMessage() + " siteId=" + siteId + " from site id=" + fromSiteId);
}
results.append("merging assignment " + siteId + " (" + count + ") assignments.\n");
return results.toString();
} // merge
/**
* {@inheritDoc}
*/
public String[] myToolIds()
{
String[] toolIds = { "sakai.assignment", "sakai.assignment.grades" };
return toolIds;
}
/**
* {@inheritDoc}
*/
public void transferCopyEntities(String fromContext, String toContext, List resourceIds){
transferCopyEntitiesRefMigrator(fromContext, toContext, resourceIds);
}
public Map<String, String> transferCopyEntitiesRefMigrator(String fromContext, String toContext, List resourceIds)
{
Map<String, String> transversalMap = new HashMap<String, String>();
// import Assignment objects
Iterator oAssignments = getAssignmentsForContext(fromContext);
while (oAssignments.hasNext())
{
Assignment oAssignment = (Assignment) oAssignments.next();
String oAssignmentId = oAssignment.getId();
boolean toBeImported = true;
if (resourceIds != null && resourceIds.size() > 0)
{
// if there is a list for import assignments, only import those assignments and relative submissions
toBeImported = false;
for (int m = 0; m < resourceIds.size() && !toBeImported; m++)
{
if (((String) resourceIds.get(m)).equals(oAssignmentId))
{
toBeImported = true;
}
}
}
if (toBeImported)
{
AssignmentEdit nAssignment = null;
AssignmentContentEdit nContent = null;
if (!m_assignmentStorage.check(oAssignmentId))
{
}
else
{
try
{
// add new Assignment content
String oContentReference = oAssignment.getContentReference();
String oContentId = contentId(oContentReference);
if (!m_contentStorage.check(oContentId))
throw new IdUnusedException(oContentId);
else
{
AssignmentContent oContent = getAssignmentContent(oContentReference);
nContent = addAssignmentContent(toContext);
// attributes
nContent.setAllowAttachments(oContent.getAllowAttachments());
nContent.setContext(toContext);
nContent.setGroupProject(oContent.getGroupProject());
nContent.setHonorPledge(oContent.getHonorPledge());
nContent.setHideDueDate(oContent.getHideDueDate());
nContent.setIndividuallyGraded(oContent.individuallyGraded());
// replace all occurrence of old context with new context inside instruction text
String instructions = oContent.getInstructions();
if (instructions.indexOf(fromContext) != -1)
{
instructions = instructions.replaceAll(fromContext, toContext);
}
nContent.setInstructions(instructions);
nContent.setMaxGradePoint(oContent.getMaxGradePoint());
nContent.setReleaseGrades(oContent.releaseGrades());
nContent.setTimeLastModified(oContent.getTimeLastModified());
nContent.setTitle(oContent.getTitle());
nContent.setTypeOfGrade(oContent.getTypeOfGrade());
nContent.setTypeOfSubmission(oContent.getTypeOfSubmission());
// review service
nContent.setAllowReviewService(oContent.getAllowReviewService());
// properties
ResourcePropertiesEdit p = nContent.getPropertiesEdit();
p.clear();
p.addAll(oContent.getProperties());
// update live properties
addLiveProperties(p);
// attachment
List oAttachments = oContent.getAttachments();
List nAttachments = m_entityManager.newReferenceList();
for (int n = 0; n < oAttachments.size(); n++)
{
Reference oAttachmentRef = (Reference) oAttachments.get(n);
String oAttachmentId = ((Reference) oAttachments.get(n)).getId();
if (oAttachmentId.indexOf(fromContext) != -1)
{
// transfer attachment, replace the context string and add new attachment if necessary
transferAttachment(fromContext, toContext, nAttachments, oAttachmentId);
}
else
{
nAttachments.add(oAttachmentRef);
}
}
nContent.replaceAttachments(nAttachments);
// complete the edit
m_contentStorage.commit(nContent);
((BaseAssignmentContentEdit) nContent).closeEdit();
}
}
catch (Exception e)
{
if (M_log.isWarnEnabled()) M_log.warn(" transferCopyEntities " + e.toString() + " oAssignmentId=" + oAssignmentId);
}
if (nContent != null)
{
try
{
// add new assignment
nAssignment = addAssignment(toContext);
// attribute
nAssignment.setCloseTime(oAssignment.getCloseTime());
nAssignment.setContentReference(nContent.getReference());
nAssignment.setContext(toContext);
// when importing, refer to property to determine draft status
if ("false".equalsIgnoreCase(m_serverConfigurationService.getString("import.importAsDraft")))
{
nAssignment.setDraft(oAssignment.getDraft());
}
else
{
nAssignment.setDraft(true);
}
nAssignment.setGroup(oAssignment.isGroup());
nAssignment.setDropDeadTime(oAssignment.getDropDeadTime());
nAssignment.setDueTime(oAssignment.getDueTime());
nAssignment.setOpenTime(oAssignment.getOpenTime());
nAssignment.setSection(oAssignment.getSection());
nAssignment.setTitle(oAssignment.getTitle());
nAssignment.setPosition_order(oAssignment.getPosition_order());
// properties
ResourcePropertiesEdit p = nAssignment.getPropertiesEdit();
p.clear();
p.addAll(oAssignment.getProperties());
// one more touch on the gradebook-integration link
String associatedGradebookAssignment = StringUtils.trimToNull(p.getProperty(PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
if (associatedGradebookAssignment != null) {
// see if the old assignment's associated gradebook item is an internal gradebook entry or externally defined
boolean isExternalAssignmentDefined = m_gradebookExternalAssessmentService.isExternalAssignmentDefined(oAssignment.getContent().getContext(), associatedGradebookAssignment);
if (isExternalAssignmentDefined)
{
// if this is an external defined (came from assignment)
// mark the link as "add to gradebook" for the new imported assignment, since the assignment is still of draft state
//later when user posts the assignment, the corresponding assignment will be created in gradebook.
p.removeProperty(PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
p.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, GRADEBOOK_INTEGRATION_ADD);
}
}
// remove the link btw assignment and announcement item. One can announce the open date afterwards
p.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE);
p.removeProperty("new_assignment_open_date_announced");
p.removeProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID);
// remove the link btw assignment and calendar item. One can add the due date to calendar afterwards
p.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
p.removeProperty("new_assignment_due_date_scheduled");
p.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
// update live properties
addLiveProperties(p);
// complete the edit
m_assignmentStorage.commit(nAssignment);
((BaseAssignmentEdit) nAssignment).closeEdit();
transversalMap.put("assignment/" + oAssignment.getId(), "assignment/" + nAssignment.getId());
M_log.info("old assignment id:"+oAssignment.getId()+" - new assignment id:"+nAssignment.getId());
try {
if (m_taggingManager.isTaggable()) {
for (TaggingProvider provider : m_taggingManager
.getProviders()) {
provider
.transferCopyTags(
m_assignmentActivityProducer
.getActivity(oAssignment),
m_assignmentActivityProducer
.getActivity(nAssignment));
}
}
} catch (PermissionException pe) {
M_log.error(this + " transferCopyEntities " + pe.toString() + " oAssignmentId=" + oAssignment.getId() + " nAssignmentId=" + nAssignment.getId());
}
}
catch (Exception ee)
{
M_log.error(this + " transferCopyEntities " + ee.toString() + " oAssignmentId=" + oAssignment.getId() + " nAssignmentId=" + nAssignment.getId());
}
}
} // if-else
} // if
} // for
return transversalMap;
} // importResources
/**
* manipulate the transfered attachment
* @param fromContext
* @param toContext
* @param nAttachments
* @param oAttachmentId
* @return the new reference
*/
private String transferAttachment(String fromContext, String toContext,
List nAttachments, String oAttachmentId)
{
String rv = "";
// replace old site id with new site id in attachments
String nAttachmentId = oAttachmentId.replaceAll(fromContext, toContext);
try
{
ContentResource attachment = m_contentHostingService.getResource(nAttachmentId);
if (nAttachments != null)
{
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
rv = attachment.getReference();
}
catch (IdUnusedException e)
{
try
{
ContentResource oAttachment = m_contentHostingService.getResource(oAttachmentId);
try
{
if (m_contentHostingService.isAttachmentResource(nAttachmentId))
{
// add the new resource into attachment collection area
ContentResource attachment = m_contentHostingService.addAttachmentResource(
Validator.escapeResourceName(oAttachment.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME)),
toContext,
ToolManager.getTool("sakai.assignment.grades").getTitle(),
oAttachment.getContentType(),
oAttachment.getContent(),
oAttachment.getProperties());
rv = attachment.getReference();
// add to attachment list
if (nAttachments != null)
{
nAttachments.add(m_entityManager.newReference(rv));
}
}
else
{
// add the new resource into resource area
ContentResource attachment = m_contentHostingService.addResource(
Validator.escapeResourceName(oAttachment.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME)),
toContext,
1,
oAttachment.getContentType(),
oAttachment.getContent(),
oAttachment.getProperties(),
NotificationService.NOTI_NONE);
rv = attachment.getReference();
// add to attachment list
if (nAttachments != null)
{
nAttachments.add(m_entityManager.newReference(rv));
}
}
}
catch (Exception eeAny)
{
// if the new resource cannot be added
M_log.warn(" transferCopyEntities: cannot add new attachment with id=" + nAttachmentId + " " + eeAny.getMessage());
}
}
catch (Exception eAny)
{
// if cannot find the original attachment, do nothing.
M_log.warn(" transferCopyEntities: cannot find the original attachment with id=" + oAttachmentId + " " + eAny.getMessage());
}
}
catch (Exception any)
{
M_log.warn(" transferCopyEntities" + any.getMessage() + " oAttachmentId=" + oAttachmentId + " nAttachmentId=" + nAttachmentId);
}
return rv;
}
/**
* {@inheritDoc}
*/
public String getEntityDescription(Reference ref)
{
String rv = "Assignment: " + ref.getReference();
try
{
// is it an AssignmentContent object
if (REF_TYPE_CONTENT.equals(ref.getSubType()))
{
AssignmentContent c = getAssignmentContent(ref.getReference());
rv = "AssignmentContent: " + c.getId() + " (" + c.getContext() + ")";
}
// is it an Assignment object
else if (REF_TYPE_ASSIGNMENT.equals(ref.getSubType()))
{
Assignment a = getAssignment(ref.getReference());
rv = "Assignment: " + a.getId() + " (" + a.getContext() + ")";
}
// is it an AssignmentSubmission object
else if (REF_TYPE_SUBMISSION.equals(ref.getSubType()))
{
AssignmentSubmission s = getSubmission(ref.getReference());
rv = "AssignmentSubmission: " + s.getId() + " (" + s.getContext() + ")";
}
else
M_log.warn(" getEntityDescription(): unknown message ref subtype: " + ref.getSubType() + " in ref: " + ref.getReference());
}
catch (PermissionException e)
{
M_log.warn(" getEntityDescription(): " + e.getMessage() + " ref=" + ref.getReference());
}
catch (IdUnusedException e)
{
M_log.warn(" getEntityDescription(): " + e.getMessage() + " ref=" + ref.getReference());
}
catch (NullPointerException e)
{
M_log.warn(" getEntityDescription(): " + e.getMessage() + " ref=" + ref.getReference());
}
return rv;
}
/**
* {@inheritDoc}
*/
public ResourceProperties getEntityResourceProperties(Reference ref)
{
ResourceProperties rv = null;
try
{
// is it an AssignmentContent object
if (REF_TYPE_CONTENT.equals(ref.getSubType()))
{
AssignmentContent c = getAssignmentContent(ref.getReference());
rv = c.getProperties();
}
// is it an Assignment object
else if (REF_TYPE_ASSIGNMENT.equals(ref.getSubType()))
{
Assignment a = getAssignment(ref.getReference());
rv = a.getProperties();
}
// is it an AssignmentSubmission object
else if (REF_TYPE_SUBMISSION.equals(ref.getSubType()))
{
AssignmentSubmission s = getSubmission(ref.getReference());
rv = s.getProperties();
}
else
M_log.warn(" getEntityResourceProperties: unknown message ref subtype: " + ref.getSubType() + " in ref: " + ref.getReference());
}
catch (PermissionException e)
{
M_log.warn(" getEntityResourceProperties(): " + e.getMessage() + " ref=" + ref.getReference());
}
catch (IdUnusedException e)
{
M_log.warn(" getEntityResourceProperties(): " + e.getMessage() + " ref=" + ref.getReference());
}
catch (NullPointerException e)
{
M_log.warn(" getEntityResourceProperties(): " + e.getMessage() + " ref=" + ref.getReference());
}
return rv;
}
/**
* {@inheritDoc}
*/
public boolean canSubmit(String context, Assignment a)
{
// return false if not allowed to submit at all
if (!allowAddSubmissionCheckGroups(context, a) && !allowAddAssignment(context) /*SAK-25555 return true if user is allowed to add assignment*/) return false;
String userId = SessionManager.getCurrentSessionUserId();
// if user can submit to this assignment
List visibleAssignments = assignments(context, userId);
if (visibleAssignments == null || !visibleAssignments.contains(a)) return false;
try
{
// get user
User u = UserDirectoryService.getUser(userId);
Time currentTime = TimeService.newTime();
// return false if the assignment is draft or is not open yet
Time openTime = a.getOpenTime();
if (a.getDraft() || (openTime != null && openTime.after(currentTime)))
{
return false;
}
// return false if the current time has passed the assignment close time
Time closeTime = a.getCloseTime();
// get user's submission
AssignmentSubmission submission = null;
submission = getSubmission(a.getReference(), u);
// check for allow resubmission or not first
// return true if resubmission is allowed and current time is before resubmission close time
// get the resubmit settings from submission object first
String allowResubmitNumString = submission != null?submission.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):null;
if (allowResubmitNumString != null && submission.getTimeSubmitted() != null)
{
try
{
int allowResubmitNumber = Integer.parseInt(allowResubmitNumString);
String allowResubmitCloseTime = submission != null ? (String) submission.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME):null;
Time resubmitCloseTime = null;
if (allowResubmitCloseTime != null)
{
// see if a resubmission close time is set on submission level
resubmitCloseTime = TimeService.newTime(Long.parseLong(allowResubmitCloseTime));
}
else
{
// otherwise, use assignment close time as the resubmission close time
resubmitCloseTime = a.getCloseTime();
}
return (allowResubmitNumber > 0 /* additional submission number allowed */ || allowResubmitNumber == -1 /* unlimited submission times allowed */) && resubmitCloseTime != null && currentTime.before(resubmitCloseTime);
}
catch (NumberFormatException e)
{
M_log.warn(" canSubmit(String, Assignment) " + e.getMessage() + " allowResubmitNumString=" + allowResubmitNumString);
}
}
if (submission == null || (submission != null && submission.getTimeSubmitted() == null))
{
// if there is no submission yet
if (closeTime != null && currentTime.after(closeTime))
{
return false;
}
else
{
return true;
}
}
else
{
if (!submission.getSubmitted() && !(closeTime != null && currentTime.after(closeTime)))
{
// return true for drafted submissions
return true;
}
else
return false;
}
}
catch (UserNotDefinedException e)
{
// cannot find user
M_log.warn(" canSubmit(String, Assignment) " + e.getMessage() + " assignment ref=" + a.getReference());
return false;
}
}
/**********************************************************************************************************************************************************************************************************************************************************
* Assignment Implementation
*********************************************************************************************************************************************************************************************************************************************************/
public class BaseAssignment implements Assignment
{
protected ResourcePropertiesEdit m_properties;
protected String m_id;
protected String m_assignmentContent;
protected String m_title;
protected String m_context;
protected String m_section;
protected Time m_visibleTime;
protected Time m_openTime;
protected Time m_dueTime;
protected Time m_closeTime;
protected Time m_dropDeadTime;
protected List m_authors;
protected boolean m_draft;
protected boolean m_hideDueDate;
protected boolean m_group;
protected int m_position_order;
/** The Collection of groups (authorization group id strings). */
protected Collection m_groups = new ArrayList();
/** The assignment access. */
protected AssignmentAccess m_access = AssignmentAccess.SITE;
protected boolean m_allowPeerAssessment;
protected Time m_peerAssessmentPeriodTime;
protected boolean m_peerAssessmentAnonEval;
protected boolean m_peerAssessmentStudentViewReviews;
protected int m_peerAssessmentNumReviews;
protected String m_peerAssessmentInstructions;
/**
* constructor
*/
public BaseAssignment()
{
m_properties = new BaseResourcePropertiesEdit();
}// constructor
/**
* Copy constructor
*/
public BaseAssignment(Assignment assignment)
{
setAll(assignment);
}// copy constructor
/**
* Constructor used in addAssignment
*/
public BaseAssignment(String id, String context)
{
m_properties = new BaseResourcePropertiesEdit();
addLiveProperties(m_properties);
m_id = id;
m_assignmentContent = "";
m_title = "";
m_context = context;
m_section = "";
m_authors = new ArrayList();
m_draft = true;
m_hideDueDate = false;
m_groups = new ArrayList();
m_position_order = 0;
m_allowPeerAssessment = false;
m_peerAssessmentPeriodTime = null;
m_peerAssessmentAnonEval = false;
m_peerAssessmentStudentViewReviews = false;
m_peerAssessmentNumReviews = 0;
m_peerAssessmentInstructions = null;
}
/**
* Reads the Assignment's attribute values from xml.
*
* @param s -
* Data structure holding the xml info.
*/
public BaseAssignment(Element el)
{
M_log.debug(" BASE ASSIGNMENT : ENTERING STORAGE CONSTRUCTOR");
m_properties = new BaseResourcePropertiesEdit();
int numAttributes = 0;
String intString = null;
String attributeString = null;
String tempString = null;
m_id = el.getAttribute("id");
M_log.debug(" BASE ASSIGNMENT : STORAGE CONSTRUCTOR : ASSIGNMENT ID : " + m_id);
m_title = el.getAttribute("title");
m_section = el.getAttribute("section");
m_draft = getBool(el.getAttribute("draft"));
m_hideDueDate = getBool(el.getAttribute("hideduedate"));
m_group = getBool(el.getAttribute("group"));
M_log.debug(" BASE ASSIGNMENT : STORAGE CONSTRUCTOR : READ THROUGH REG ATTS");
m_assignmentContent = el.getAttribute("assignmentcontent");
M_log.debug(" BASE ASSIGNMENT : STORAGE CONSTRUCTOR : CONTENT ID : "
+ m_assignmentContent);
m_openTime = getTimeObject(el.getAttribute("opendate"));
m_dueTime = getTimeObject(el.getAttribute("duedate"));
m_visibleTime = getTimeObject(el.getAttribute("visibledate"));
m_dropDeadTime = getTimeObject(el.getAttribute("dropdeaddate"));
m_closeTime = getTimeObject(el.getAttribute("closedate"));
m_context = el.getAttribute("context");
m_position_order = 0; // prevents null pointer if there is no position_order defined as well as helps with the sorting
try
{
m_position_order = Long.valueOf(el.getAttribute("position_order")).intValue();
}
catch (Exception e)
{
M_log.warn(": BaseAssignment(Element) " + e.getMessage());
}
m_allowPeerAssessment = getBool(el.getAttribute("allowpeerassessment"));
m_peerAssessmentPeriodTime = getTimeObject(el.getAttribute("peerassessmentperiodtime"));
m_peerAssessmentAnonEval = getBool(el.getAttribute("peerassessmentanoneval"));
m_peerAssessmentStudentViewReviews = getBool(el.getAttribute("peerassessmentstudentviewreviews"));
String numReviews = el.getAttribute("peerassessmentnumreviews");
m_peerAssessmentNumReviews = 0;
if(numReviews != null && !"".equals(numReviews)){
try{
m_peerAssessmentNumReviews = Integer.parseInt(numReviews);
}catch(Exception e){}
}
m_peerAssessmentInstructions = el.getAttribute("peerassessmentinstructions");
// READ THE AUTHORS
m_authors = new ArrayList();
intString = el.getAttribute("numberofauthors");
M_log.debug(" BASE ASSIGNMENT : STORAGE CONSTRUCTOR : number of authors : " + intString);
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
M_log.debug(" BASE ASSIGNMENT : STORAGE CONSTRUCTOR : reading author # " + x);
attributeString = "author" + x;
tempString = el.getAttribute(attributeString);
if (tempString != null)
{
M_log.debug(" BASE ASSIGNMENT : STORAGE CONSTRUCTOR : adding author # " + x
+ " id : " + tempString);
m_authors.add(tempString);
}
}
}
catch (Exception e)
{
M_log.warn(" BASE ASSIGNMENT : STORAGE CONSTRUCTOR : Exception reading authors : " + e);
}
// READ THE PROPERTIES AND INSTRUCTIONS
NodeList children = el.getChildNodes();
final int length = children.getLength();
for (int i = 0; i < length; i++)
{
Node child = children.item(i);
if (child.getNodeType() != Node.ELEMENT_NODE) continue;
Element element = (Element) child;
// look for properties
if (element.getTagName().equals("properties"))
{
// re-create properties
m_properties = new BaseResourcePropertiesEdit(element);
}
// look for an group
else if (element.getTagName().equals("group"))
{
m_groups.add(element.getAttribute("authzGroup"));
}
}
// extract access
AssignmentAccess access = AssignmentAccess.fromString(el.getAttribute("access"));
if (access != null)
{
m_access = access;
}
M_log.debug(" BASE ASSIGNMENT : LEAVING STORAGE CONSTRUCTOR");
}// storage constructor
/**
* @param services
* @return
*/
public ContentHandler getContentHandler(Map<String, Object> services)
{
final Entity thisEntity = this;
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.DefaultEntityHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String,
* org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if ("assignment".equals(qName) && entity == null)
{
m_id = attributes.getValue("id");
m_properties = new BaseResourcePropertiesEdit();
int numAttributes = 0;
String intString = null;
String attributeString = null;
String tempString = null;
m_title = attributes.getValue("title");
m_section = attributes.getValue("section");
m_draft = getBool(attributes.getValue("draft"));
m_hideDueDate = getBool(attributes.getValue("hideduedate"));
m_group = getBool(attributes.getValue("group"));
M_log.debug(this + " getContentHandler: READ THROUGH REG ATTS");
m_assignmentContent = attributes.getValue("assignmentcontent");
M_log.debug(this + " getContentHandler: STORAGE CONSTRUCTOR : CONTENT ID : "
+ m_assignmentContent);
m_openTime = getTimeObject(attributes.getValue("opendate"));
m_dueTime = getTimeObject(attributes.getValue("duedate"));
m_visibleTime = getTimeObject(attributes.getValue("visibledate"));
m_dropDeadTime = getTimeObject(attributes.getValue("dropdeaddate"));
m_closeTime = getTimeObject(attributes.getValue("closedate"));
m_context = attributes.getValue("context");
try
{
m_position_order = NumberUtils.toInt(attributes.getValue("position_order"));
}
catch (Exception e)
{
m_position_order = 0; // prevents null pointer if there is no position_order defined as well as helps with the sorting
}
m_allowPeerAssessment = getBool(attributes.getValue("allowpeerassessment"));
m_peerAssessmentPeriodTime = getTimeObject(attributes.getValue("peerassessmentperiodtime"));
m_peerAssessmentAnonEval = getBool(attributes.getValue("peerassessmentanoneval"));
m_peerAssessmentStudentViewReviews = getBool(attributes.getValue("peerassessmentstudentviewreviews"));
String numReviews = attributes.getValue("peerassessmentnumreviews");
m_peerAssessmentNumReviews = 0;
if(numReviews != null && !"".equals(numReviews)){
try{
m_peerAssessmentNumReviews = Integer.parseInt(numReviews);
}catch(Exception e){}
}
m_peerAssessmentInstructions = attributes.getValue("peerassessmentinstructions");
// READ THE AUTHORS
m_authors = new ArrayList();
intString = attributes.getValue("numberofauthors");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "author" + x;
tempString = attributes.getValue(attributeString);
if (tempString != null)
{
m_authors.add(tempString);
}
}
}
catch (Exception e)
{
M_log.warn(" BASE ASSIGNMENT getContentHandler startElement : Exception reading authors : " + e.toString());
}
// extract access
AssignmentAccess access = AssignmentAccess.fromString(attributes.getValue("access"));
if (access != null)
{
m_access = access;
}
entity = thisEntity;
}
else if (GROUP_LIST.equals(qName))
{
String groupRef = attributes.getValue(GROUP_NAME);
if (groupRef != null)
{
m_groups.add(groupRef);
}
}
else
{
M_log.debug(this + " BaseAssignment getContentHandler Unexpected Element " + qName);
}
}
}
};
}
/**
* Takes the Assignment's attribute values and puts them into the xml document.
*
* @param s -
* Data structure holding the object to be stored.
* @param doc -
* The xml document.
*/
public Element toXml(Document doc, Stack stack)
{
M_log.debug(this + " BASE ASSIGNMENT : ENTERING TOXML");
Element assignment = doc.createElement("assignment");
if (stack.isEmpty())
{
doc.appendChild(assignment);
}
else
{
((Element) stack.peek()).appendChild(assignment);
}
stack.push(assignment);
// SET ASSIGNMENT ATTRIBUTES
String numItemsString = null;
String attributeString = null;
String itemString = null;
// SAK-13408 -The XML implementation in Websphere throws an LSException if the
// attribute is null, while in Tomcat it assumes an empty string. The following
// sets the attribute to an empty string if the value is null.
assignment.setAttribute("id", m_id == null ? "" : m_id);
assignment.setAttribute("title", m_title == null ? "" : m_title);
assignment.setAttribute("section", m_section == null ? "" : m_section);
assignment.setAttribute("context", m_context == null ? "" : m_context);
assignment.setAttribute("assignmentcontent", m_assignmentContent == null ? "" : m_assignmentContent);
assignment.setAttribute("draft", getBoolString(m_draft));
assignment.setAttribute("group", getBoolString(m_group));
assignment.setAttribute("hideduedate", getBoolString(m_hideDueDate));
assignment.setAttribute("opendate", getTimeString(m_openTime));
assignment.setAttribute("duedate", getTimeString(m_dueTime));
assignment.setAttribute("visibledate", getTimeString(m_visibleTime));
assignment.setAttribute("dropdeaddate", getTimeString(m_dropDeadTime));
assignment.setAttribute("closedate", getTimeString(m_closeTime));
assignment.setAttribute("position_order", Long.valueOf(m_position_order).toString().trim());
assignment.setAttribute("allowpeerassessment", getBoolString(m_allowPeerAssessment));
assignment.setAttribute("peerassessmentperiodtime", getTimeString(m_peerAssessmentPeriodTime));
assignment.setAttribute("peerassessmentanoneval", getBoolString(m_peerAssessmentAnonEval));
assignment.setAttribute("peerassessmentstudentviewreviews", getBoolString(m_peerAssessmentStudentViewReviews));
assignment.setAttribute("peerassessmentnumreviews", "" + m_peerAssessmentNumReviews);
assignment.setAttribute("peerassessmentinstructions", m_peerAssessmentInstructions);
M_log.debug(this + " BASE ASSIGNMENT : TOXML : saved regular properties");
// SAVE THE AUTHORS
numItemsString = "" + m_authors.size();
M_log.debug(this + " BASE ASSIGNMENT : TOXML : saving " + numItemsString + " authors");
assignment.setAttribute("numberofauthors", numItemsString);
for (int x = 0; x < m_authors.size(); x++)
{
attributeString = "author" + x;
itemString = (String) m_authors.get(x);
if (itemString != null)
{
assignment.setAttribute(attributeString, itemString);
M_log.debug(this + " BASE ASSIGNMENT : TOXML : saving author : " + itemString);
}
}
// add groups
if ((m_groups != null) && (m_groups.size() > 0))
{
for (Iterator i = m_groups.iterator(); i.hasNext();)
{
String group = (String) i.next();
Element sect = doc.createElement("group");
assignment.appendChild(sect);
sect.setAttribute("authzGroup", group);
}
}
// add access
assignment.setAttribute("access", m_access.toString());
// SAVE THE PROPERTIES
m_properties.toXml(doc, stack);
M_log.debug(this + " BASE ASSIGNMENT : TOXML : SAVED PROPERTIES");
stack.pop();
M_log.debug("ASSIGNMENT : BASE ASSIGNMENT : LEAVING TOXML");
return assignment;
}// toXml
protected void setAll(Assignment assignment)
{
if (assignment != null)
{
m_id = assignment.getId();
m_assignmentContent = assignment.getContentReference();
m_authors = assignment.getAuthors();
m_title = assignment.getTitle();
m_context = assignment.getContext();
m_section = assignment.getSection();
m_openTime = assignment.getOpenTime();
m_dueTime = assignment.getDueTime();
m_visibleTime = assignment.getVisibleTime();
m_closeTime = assignment.getCloseTime();
m_dropDeadTime = assignment.getDropDeadTime();
m_draft = assignment.getDraft();
m_group = assignment.isGroup();
m_position_order = 0;
try
{
m_position_order = assignment.getPosition_order();
}
catch (Exception e)
{
M_log.warn(": setAll(Assignment) get position order " + e.getMessage());
}
m_properties = new BaseResourcePropertiesEdit();
m_properties.addAll(assignment.getProperties());
m_groups = assignment.getGroups();
m_access = assignment.getAccess();
m_allowPeerAssessment = assignment.getAllowPeerAssessment();
m_peerAssessmentPeriodTime = assignment.getPeerAssessmentPeriod();
m_peerAssessmentAnonEval = assignment.getPeerAssessmentAnonEval();
m_peerAssessmentStudentViewReviews = assignment.getPeerAssessmentStudentViewReviews();
m_peerAssessmentNumReviews = assignment.getPeerAssessmentNumReviews();
m_peerAssessmentInstructions = assignment.getPeerAssessmentInstructions();
}
}
public String getId()
{
return m_id;
}
/**
* Access the URL which can be used to access the resource.
*
* @return The URL which can be used to access the resource.
*/
public String getUrl()
{
return getAccessPoint(false) + Entity.SEPARATOR + "a" + Entity.SEPARATOR + m_context + Entity.SEPARATOR + m_id;
} // getUrl
/**
* Access the internal reference which can be used to access the resource from within the system.
*
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String getReference()
{
return assignmentReference(m_context, m_id);
} // getReference
/**
* @inheritDoc
*/
public String getReference(String rootProperty)
{
return getReference();
}
/**
* @inheritDoc
*/
public String getUrl(String rootProperty)
{
return getUrl();
}
/**
* Access the resource's properties.
*
* @return The resource's properties.
*/
public ResourceProperties getProperties()
{
return m_properties;
}
/**
* Access the list of authors.
*
* @return FlexStringArray of user ids.
*/
public List getAuthors()
{
return m_authors;
}
/**
* Add an author to the author list.
*
* @param author -
* The User to add to the author list.
*/
public void addAuthor(User author)
{
if (author != null) m_authors.add(author.getId());
}
/**
* Remove an author from the author list.
*
* @param author -
* the User to remove from the author list.
*/
public void removeAuthor(User author)
{
if (author != null) m_authors.remove(author.getId());
}
/**
* Access the creator of this object.
*
* @return String The creator's user id.
*/
public String getCreator()
{
return m_properties.getProperty(ResourceProperties.PROP_CREATOR);
}
/**
* Access the person of last modificaiton
*
* @return the User's Id
*/
public String getAuthorLastModified()
{
return m_properties.getProperty(ResourceProperties.PROP_MODIFIED_BY);
}
/**
* Access the title.
*
* @return The Assignment's title.
*/
public String getTitle()
{
return m_title;
}
public Time getPeerAssessmentPeriod()
{
return m_peerAssessmentPeriodTime;
}
public boolean getPeerAssessmentAnonEval(){
return m_peerAssessmentAnonEval;
}
public boolean getPeerAssessmentStudentViewReviews(){
return m_peerAssessmentStudentViewReviews;
}
public int getPeerAssessmentNumReviews(){
return m_peerAssessmentNumReviews;
}
public String getPeerAssessmentInstructions(){
return m_peerAssessmentInstructions;
}
public boolean getAllowPeerAssessment()
{
return m_allowPeerAssessment;
}
/**
* peer assessment is set for this assignment and the current time
* falls between the assignment close time and the peer asseessment period time
* @return
*/
public boolean isPeerAssessmentOpen(){
if(getAllowPeerAssessment()){
Time now = TimeService.newTime();
return now.before(getPeerAssessmentPeriod()) && now.after(getCloseTime());
}else{
return false;
}
}
/**
* peer assessment is set for this assignment but the close time hasn't passed
* @return
*/
public boolean isPeerAssessmentPending(){
if(getAllowPeerAssessment()){
Time now = TimeService.newTime();
return now.before(getCloseTime());
}else{
return false;
}
}
/**
* peer assessment is set for this assignment but the current time is passed
* the peer assessment period
* @return
*/
public boolean isPeerAssessmentClosed(){
if(getAllowPeerAssessment()){
Time now = TimeService.newTime();
return now.after(getPeerAssessmentPeriod());
}else{
return false;
}
}
/**
* @inheritDoc
*/
public String getStatus()
{
Time currentTime = TimeService.newTime();
if (this.getDraft())
return rb.getString("gen.dra1");
else if (this.getOpenTime().after(currentTime))
return rb.getString("gen.notope");
else if (this.getDueTime().after(currentTime))
return rb.getString("gen.open");
else if ((this.getCloseTime() != null) && (this.getCloseTime().before(currentTime)))
return rb.getString("gen.closed");
else
return rb.getString("gen.due");
}
/**
* Access the time that this object was created.
*
* @return The Time object representing the time of creation.
*/
public Time getTimeCreated()
{
try
{
return m_properties.getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
}
catch (EntityPropertyNotDefinedException e)
{
M_log.warn(":getTimeCreated() no time property defined " + e.getMessage());
}
catch (EntityPropertyTypeException e)
{
M_log.warn(":getTimeCreated() no time property defined " + e.getMessage());
}
return null;
}
/**
* Access the time of last modificaiton.
*
* @return The Time of last modification.
*/
public Time getTimeLastModified()
{
try
{
return m_properties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
}
catch (EntityPropertyNotDefinedException e)
{
M_log.warn(":getTimeLastModified() no time property defined " + e.getMessage());
}
catch (EntityPropertyTypeException e)
{
M_log.warn(":getTimeLastModified() no time property defined " + e.getMessage());
}
return null;
}
/**
* Access the AssignmentContent of this Assignment.
*
* @return The Assignment's AssignmentContent.
*/
public AssignmentContent getContent()
{
AssignmentContent retVal = null;
if (m_assignmentContent != null)
{
try
{
retVal = getAssignmentContent(m_assignmentContent);
}
catch (Exception e)
{
M_log.warn(":getContent() " + e.getMessage());
}
}
return retVal;
}
/**
* Access the reference of the AssignmentContent of this Assignment.
*
* @return The Assignment's reference.
*/
public String getContentReference()
{
return m_assignmentContent;
}
/**
* Access the id of the Assignment's group.
*
* @return The id of the group for which this Assignment is designed.
*/
public String getContext()
{
return m_context;
}
/**
* Access the section info
*
* @return The section String
*/
public String getSection()
{
return m_section;
}
/**
* Access the first time at which the assignment can be viewed; may be null.
*
* @return The Time at which the assignment is due, or null if unspecified.
*/
public Time getOpenTime()
{
return m_openTime;
}
/**
* @inheritDoc
*/
public String getOpenTimeString()
{
if ( m_openTime == null )
return "";
else
return m_openTime.toStringLocalFull();
}
/**
* Access the time at which the assignment is due; may be null.
*
* @return The Time at which the Assignment is due, or null if unspecified.
*/
public Time getDueTime()
{
return m_dueTime;
}
/**
* Access the time at which the assignment is visible; may be null.
*
* @return The Time at which the Assignment is visible, or null if unspecified.
*/
public Time getVisibleTime()
{
return m_visibleTime;
}
/**
* @inheritDoc
*/
public String getDueTimeString()
{
if ( m_dueTime == null )
return "";
else
return m_dueTime.toStringLocalFull();
}
public String getVisibleTimeString()
{
if ( m_visibleTime == null )
return "";
else
return m_visibleTime.toStringLocalFull();
}
/**
* Access the drop dead time after which responses to this assignment are considered late; may be null.
*
* @return The Time object representing the drop dead time, or null if unspecified.
*/
public Time getDropDeadTime()
{
return m_dropDeadTime;
}
/**
* @inheritDoc
*/
public String getDropDeadTimeString()
{
if ( m_dropDeadTime == null )
return "";
else
return m_dropDeadTime.toStringLocalFull();
}
/**
* Access the close time after which this assignment can no longer be viewed, and after which submissions will not be accepted. May be null.
*
* @return The Time after which the Assignment is closed, or null if unspecified.
*/
public Time getCloseTime()
{
if (m_closeTime == null)
{
m_closeTime = m_dueTime;
}
return m_closeTime;
}
/**
* @inheritDoc
*/
public String getCloseTimeString()
{
if ( m_closeTime == null )
return "";
else
return m_closeTime.toStringLocalFull();
}
/**
* Get whether this is a draft or final copy.
*
* @return True if this is a draft, false if it is a final copy.
*/
public boolean getDraft()
{
return m_draft;
}
public boolean getHideDueDate()
{
return m_hideDueDate;
}
public boolean isGroup()
{
return m_group;
}
/**
* Access the position order.
*
* @return The Assignment's positionorder.
*/
public int getPosition_order()
{
return m_position_order;
}
/**
* @inheritDoc
*/
public Collection getGroups()
{
return new ArrayList(m_groups);
}
/**
* @inheritDoc
*/
public AssignmentAccess getAccess()
{
return m_access;
}
/**
* Are these objects equal? If they are both Assignment objects, and they have matching id's, they are.
*
* @return true if they are equal, false if not.
*/
public boolean equals(Object obj)
{
if (!(obj instanceof Assignment)) return false;
return ((Assignment) obj).getId().equals(getId());
} // equals
/**
* Make a hash code that reflects the equals() logic as well. We want two objects, even if different instances, if they have the same id to hash the same.
*/
public int hashCode()
{
return getId().hashCode();
} // hashCode
/**
* Compare this object with the specified object for order.
*
* @return A negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
*/
public int compareTo(Object obj)
{
if (!(obj instanceof Assignment)) throw new ClassCastException();
// if the object are the same, say so
if (obj == this) return 0;
// start the compare by comparing their sort names
int compare = getTitle().compareTo(((Assignment) obj).getTitle());
// if these are the same
if (compare == 0)
{
// sort based on (unique) id
compare = getId().compareTo(((Assignment) obj).getId());
}
return compare;
} // compareTo
} // BaseAssignment
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentEdit implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* <p>
* BaseAssignmentEdit is an implementation of the CHEF AssignmentEdit object.
* </p>
*
* @author University of Michigan, CHEF Software Development Team
*/
public class BaseAssignmentEdit extends BaseAssignment implements AssignmentEdit, SessionBindingListener
{
/** The event code for this edit. */
protected String m_event = null;
/** Active flag. */
protected boolean m_active = false;
/**
* Construct from another Assignment object.
*
* @param Assignment
* The Assignment object to use for values.
*/
public BaseAssignmentEdit(Assignment assignment)
{
super(assignment);
} // BaseAssignmentEdit
/**
* Construct.
*
* @param id
* The assignment id.
*/
public BaseAssignmentEdit(String id, String context)
{
super(id, context);
} // BaseAssignmentEdit
/**
* Construct from information in XML.
*
* @param el
* The XML DOM Element definining the Assignment.
*/
public BaseAssignmentEdit(Element el)
{
super(el);
} // BaseAssignmentEdit
/**
* Clean up.
*/
protected void finalize()
{
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelEdit(this);
}
} // finalize
/**
* Set the title.
*
* @param title -
* The Assignment's title.
*/
public void setTitle(String title)
{
m_title = title;
}
public void setPeerAssessmentPeriod(Time time)
{
m_peerAssessmentPeriodTime = time;
}
public void setAllowPeerAssessment(boolean allow)
{
m_allowPeerAssessment = allow;
}
public void setPeerAssessmentAnonEval(boolean anonEval){
m_peerAssessmentAnonEval = anonEval;
}
public void setPeerAssessmentStudentViewReviews(boolean studentViewReviews){
m_peerAssessmentStudentViewReviews = studentViewReviews;
}
public void setPeerAssessmentNumReviews(int numReviews){
m_peerAssessmentNumReviews = numReviews;
}
public void setPeerAssessmentInstructions(String instructions){
m_peerAssessmentInstructions = instructions;
}
/**
* Set the reference of the AssignmentContent of this Assignment.
*
* @param String -
* the reference of the AssignmentContent.
*/
public void setContentReference(String contentReference)
{
if (contentReference != null) m_assignmentContent = contentReference;
}
/**
* Set the AssignmentContent of this Assignment.
*
* @param content -
* the Assignment's AssignmentContent.
*/
public void setContent(AssignmentContent content)
{
if (content != null) m_assignmentContent = content.getReference();
}
/**
* Set the context at the time of creation.
*
* @param context -
* the context string.
*/
public void setContext(String context)
{
m_context = context;
}
/**
* Set the section info
*
* @param sectionId -
* The section id
*/
public void setSection(String sectionId)
{
m_section = sectionId;
}
/**
* Set the first time at which the assignment can be viewed; may be null.
*
* @param opentime -
* The Time at which the Assignment opens.
*/
public void setOpenTime(Time opentime)
{
m_openTime = opentime;
}
/**
* Set the time at which the assignment is due; may be null.
*
* @param dueTime -
* The Time at which the Assignment is due.
*/
public void setDueTime(Time duetime)
{
m_dueTime = duetime;
}
/**
* Set the time at which the assignment is visible; may be null.
*
* @param visibleTime -
* The Time at which the Assignment is visible
*/
public void setVisibleTime(Time visibletime)
{
m_visibleTime = visibletime;
}
/**
* Set the drop dead time after which responses to this assignment are considered late; may be null.
*
* @param dropdeadtime -
* The Time object representing the drop dead time.
*/
public void setDropDeadTime(Time dropdeadtime)
{
m_dropDeadTime = dropdeadtime;
}
/**
* Set the time after which this assignment can no longer be viewed, and after which submissions will not be accepted. May be null.
*
* @param closetime -
* The Time after which the Assignment is closed, or null if unspecified.
*/
public void setCloseTime(Time closetime)
{
m_closeTime = closetime;
}
/**
* Set whether this is a draft or final copy.
*
* @param draft -
* true if this is a draft, false if it is a final copy.
*/
public void setDraft(boolean draft)
{
m_draft = draft;
}
public void setHideDueDate (boolean hide)
{
m_hideDueDate = hide;
}
public void setGroup(boolean group) {
m_group = group;
}
/**
* Set the position order field for the an assignment.
*
* @param position_order -
* The position order.
*/
public void setPosition_order(int position_order)
{
m_position_order = position_order;
}
/**
* Take all values from this object.
*
* @param user
* The user object to take values from.
*/
protected void set(Assignment assignment)
{
setAll(assignment);
} // set
/**
* Access the event code for this edit.
*
* @return The event code for this edit.
*/
protected String getEvent()
{
return m_event;
}
/**
* Set the event code for this edit.
*
* @param event
* The event code for this edit.
*/
protected void setEvent(String event)
{
m_event = event;
}
/**
* Access the resource's properties for modification
*
* @return The resource's properties.
*/
public ResourcePropertiesEdit getPropertiesEdit()
{
return m_properties;
} // getPropertiesEdit
/**
* Enable editing.
*/
protected void activate()
{
m_active = true;
} // activate
/**
* Check to see if the edit is still active, or has already been closed.
*
* @return true if the edit is active, false if it's been closed.
*/
public boolean isActiveEdit()
{
return m_active;
} // isActiveEdit
/**
* Close the edit object - it cannot be used after this.
*/
protected void closeEdit()
{
m_active = false;
} // closeEdit
/******************************************************************************************************************************************************************************************************************************************************
* Group awareness implementation
*****************************************************************************************************************************************************************************************************************************************************/
/**
* @inheritDoc
*/
public void setAccess(AssignmentAccess access)
{
m_access = access;
}
/**
* @inheritDoc
*/
public void setGroupAccess(Collection groups) throws PermissionException
{
// convenience (and what else are we going to do?)
if ((groups == null) || (groups.size() == 0))
{
clearGroupAccess();
return;
}
// is there any change? If we are already grouped, and the group list is the same, ignore the call
if ((m_access == AssignmentAccess.GROUPED) && (EntityCollections.isEqualEntityRefsToEntities(m_groups, groups))) return;
// there should not be a case where there's no context
if (m_context == null)
{
M_log.warn(" setGroupAccess() called with null context: " + getReference());
throw new PermissionException(SessionManager.getCurrentSessionUserId(), "access:site", getReference());
}
// isolate any groups that would be removed or added
Collection addedGroups = new ArrayList();
Collection removedGroups = new ArrayList();
EntityCollections.computeAddedRemovedEntityRefsFromNewEntitiesOldRefs(addedGroups, removedGroups, groups, m_groups);
// verify that the user has permission to remove
if (removedGroups.size() > 0)
{
// the Group objects the user has remove permission
Collection allowedGroups = getGroupsAllowRemoveAssignment(m_context);
for (Iterator i = removedGroups.iterator(); i.hasNext();)
{
String ref = (String) i.next();
// is ref a group the user can remove from?
if (!EntityCollections.entityCollectionContainsRefString(allowedGroups, ref))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), "access:group:remove", ref);
}
}
}
// verify that the user has permission to add in those contexts
if (addedGroups.size() > 0)
{
// the Group objects the user has add permission
Collection allowedGroups = getGroupsAllowAddAssignment(m_context);
for (Iterator i = addedGroups.iterator(); i.hasNext();)
{
String ref = (String) i.next();
// is ref a group the user can remove from?
if (!EntityCollections.entityCollectionContainsRefString(allowedGroups, ref))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), "access:group:add", ref);
}
}
}
// we are clear to perform this
m_access = AssignmentAccess.GROUPED;
EntityCollections.setEntityRefsFromEntities(m_groups, groups);
}
/**
* @inheritDoc
*/
public void clearGroupAccess() throws PermissionException
{
// is there any change? If we are already site, ignore the call
if (m_access == AssignmentAccess.SITE)
{
m_groups.clear();
return;
}
if (m_context == null)
{
// there should not be a case where there's no context
M_log.warn(" clearGroupAccess() called with null context. " + getReference());
throw new PermissionException(SessionManager.getCurrentSessionUserId(), "access:site", getReference());
}
else
{
// verify that the user has permission to add in the site context
if (!allowAddSiteAssignment(m_context))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), "access:site", getReference());
}
}
// we are clear to perform this
m_access = AssignmentAccess.SITE;
m_groups.clear();
}
/******************************************************************************************************************************************************************************************************************************************************
* SessionBindingListener implementation
*****************************************************************************************************************************************************************************************************************************************************/
public void valueBound(SessionBindingEvent event)
{
}
public void valueUnbound(SessionBindingEvent event)
{
M_log.debug(this + " BaseAssignmentEdit valueUnbound()");
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelEdit(this);
}
} // valueUnbound
} // BaseAssignmentEdit
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentContent Implementation
*********************************************************************************************************************************************************************************************************************************************************/
public class BaseAssignmentContent implements AssignmentContent
{
protected ResourcePropertiesEdit m_properties;
protected String m_id;
protected String m_context;
protected List m_attachments;
protected List m_authors;
protected String m_title;
protected String m_instructions;
protected int m_honorPledge;
protected int m_typeOfSubmission;
protected int m_typeOfGrade;
protected int m_maxGradePoint;
protected boolean m_groupProject;
protected boolean m_individuallyGraded;
protected boolean m_releaseGrades;
protected boolean m_hideDueDate;
protected boolean m_allowAttachments;
protected boolean m_allowReviewService;
protected boolean m_allowStudentViewReport;
String m_submitReviewRepo;
String m_generateOriginalityReport;
boolean m_checkTurnitin = true;
boolean m_checkInternet = true;
boolean m_checkPublications = true;
boolean m_checkInstitution = true;
boolean m_excludeBibliographic = true;
boolean m_excludeQuoted = true;
int m_excludeType = 0;
int m_excludeValue = 1;
protected Time m_timeCreated;
protected Time m_timeLastModified;
/**
* constructor
*/
public BaseAssignmentContent()
{
m_properties = new BaseResourcePropertiesEdit();
}// constructor
/**
* Copy constructor.
*/
public BaseAssignmentContent(AssignmentContent content)
{
setAll(content);
}
/**
* Constructor used in addAssignmentContent.
*/
public BaseAssignmentContent(String id, String context)
{
m_id = id;
m_context = context;
m_properties = new BaseResourcePropertiesEdit();
addLiveProperties(m_properties);
m_authors = new ArrayList();
m_attachments = m_entityManager.newReferenceList();
m_title = "";
m_instructions = "";
m_honorPledge = Assignment.HONOR_PLEDGE_NOT_SET;
m_typeOfSubmission = Assignment.ASSIGNMENT_SUBMISSION_TYPE_NOT_SET;
m_typeOfGrade = Assignment.GRADE_TYPE_NOT_SET;
m_maxGradePoint = 0;
m_timeCreated = TimeService.newTime();
m_timeLastModified = TimeService.newTime();
}
/**
* Reads the AssignmentContent's attribute values from xml.
*
* @param s -
* Data structure holding the xml info.
*/
public BaseAssignmentContent(Element el)
{
int numAttributes = 0;
String intString = null;
String attributeString = null;
String tempString = null;
Reference tempReference = null;
M_log.debug(" BaseAssignmentContent : Entering read");
m_id = el.getAttribute("id");
m_context = el.getAttribute("context");
m_title = el.getAttribute("title");
m_groupProject = getBool(el.getAttribute("groupproject"));
m_individuallyGraded = getBool(el.getAttribute("indivgraded"));
m_releaseGrades = getBool(el.getAttribute("releasegrades"));
m_allowAttachments = getBool(el.getAttribute("allowattach"));
m_hideDueDate = getBool(el.getAttribute("hideduedate"));
m_allowReviewService = getBool(el.getAttribute("allowreview"));
m_allowStudentViewReport = getBool(el.getAttribute("allowstudentview"));
m_submitReviewRepo = el.getAttribute("submitReviewRepo");
m_generateOriginalityReport = el.getAttribute("generateOriginalityReport");
m_checkTurnitin = getBool(el.getAttribute("checkTurnitin"));
m_checkInternet = getBool(el.getAttribute("checkInternet"));
m_checkPublications = getBool(el.getAttribute("checkPublications"));
m_checkInstitution = getBool(el.getAttribute("checkInstitution"));
m_excludeBibliographic = getBool(el.getAttribute("excludeBibliographic"));
m_excludeQuoted = getBool(el.getAttribute("excludeQuoted"));
String excludeTypeStr = el.getAttribute("excludeType");
try{
m_excludeType = Integer.parseInt(excludeTypeStr);
if(m_excludeType != 0 && m_excludeType != 1 && m_excludeType != 2){
m_excludeType = 0;
}
}catch (Exception e) {
m_excludeType = 0;
}
String excludeValueStr = el.getAttribute("excludeValue");
try{
m_excludeValue = Integer.parseInt(excludeValueStr);
if(m_excludeValue < 0 || m_excludeValue > 100){
m_excludeValue = 1;
}
}catch (Exception e) {
m_excludeValue = 1;
}
m_timeCreated = getTimeObject(el.getAttribute("datecreated"));
m_timeLastModified = getTimeObject(el.getAttribute("lastmod"));
m_instructions = FormattedText.decodeFormattedTextAttribute(el, "instructions");
try
{
m_honorPledge = Integer.parseInt(el.getAttribute("honorpledge"));
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentContent Exception parsing honor pledge int from xml file string : " + e);
}
try
{
m_typeOfSubmission = Integer.parseInt(el.getAttribute("submissiontype"));
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentContent Exception parsing submission type int from xml file string : " + e);
}
try
{
m_typeOfGrade = Integer.parseInt(el.getAttribute("typeofgrade"));
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentContent Exception parsing grade type int from xml file string : " + e);
}
try
{
// %%%zqian
// read the scaled max grade point first; if there is none, get the old max grade value and multiple by 10
String maxGradePoint = StringUtils.trimToNull(el.getAttribute("scaled_maxgradepoint"));
if (maxGradePoint == null)
{
maxGradePoint = StringUtils.trimToNull(el.getAttribute("maxgradepoint"));
if (maxGradePoint != null)
{
maxGradePoint = maxGradePoint + "0";
}
}
if (maxGradePoint != null)
{
m_maxGradePoint = Integer.parseInt(maxGradePoint);
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentContent Exception parsing maxgradepoint int from xml file string : " + e);
}
// READ THE AUTHORS
m_authors = new ArrayList();
intString = el.getAttribute("numberofauthors");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "author" + x;
tempString = el.getAttribute(attributeString);
if (tempString != null) m_authors.add(tempString);
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentContent: Exception reading authors : " + e);
}
// READ THE ATTACHMENTS
m_attachments = m_entityManager.newReferenceList();
M_log.debug(" BaseAssignmentContent: Reading attachments : ");
intString = el.getAttribute("numberofattachments");
M_log.debug(" BaseAssignmentContent: num attachments : " + intString);
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "attachment" + x;
tempString = el.getAttribute(attributeString);
if (tempString != null)
{
tempReference = m_entityManager.newReference(tempString);
m_attachments.add(tempReference);
M_log.debug(" BaseAssignmentContent: " + attributeString + " : " + tempString);
}
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentContent: Exception reading attachments : " + e);
}
// READ THE PROPERTIES
NodeList children = el.getChildNodes();
final int length = children.getLength();
for (int i = 0; i < length; i++)
{
Node child = children.item(i);
if (child.getNodeType() != Node.ELEMENT_NODE) continue;
Element element = (Element) child;
// look for properties
if (element.getTagName().equals("properties"))
{
// re-create properties
m_properties = new BaseResourcePropertiesEdit(element);
}
// old style of encoding
else if (element.getTagName().equals("instructions-html") || element.getTagName().equals("instructions-formatted")
|| element.getTagName().equals("instructions"))
{
if ((element.getChildNodes() != null) && (element.getChildNodes().item(0) != null))
{
m_instructions = element.getChildNodes().item(0).getNodeValue();
if (element.getTagName().equals("instructions"))
m_instructions = FormattedText.convertPlaintextToFormattedText(m_instructions);
if (element.getTagName().equals("instructions-formatted"))
m_instructions = FormattedText.convertOldFormattedText(m_instructions);
M_log.debug(" BaseAssignmentContent(Element): instructions : " + m_instructions);
}
if (m_instructions == null)
{
m_instructions = "";
}
}
}
M_log.debug(" BaseAssignmentContent(Element): LEAVING STORAGE CONSTRUTOR");
}// storage constructor
/**
* @param services
* @return
*/
public ContentHandler getContentHandler(Map<String, Object> services)
{
final Entity thisEntity = this;
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.DefaultEntityHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String,
* org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if ("content".equals(qName) && entity == null)
{
int numAttributes = 0;
String intString = null;
String attributeString = null;
String tempString = null;
Reference tempReference = null;
m_id = attributes.getValue("id");
m_context = attributes.getValue("context");
m_title = attributes.getValue("title");
m_groupProject = getBool(attributes.getValue("groupproject"));
m_individuallyGraded = getBool(attributes.getValue("indivgraded"));
m_releaseGrades = getBool(attributes.getValue("releasegrades"));
m_allowAttachments = getBool(attributes.getValue("allowattach"));
m_hideDueDate = getBool(attributes.getValue("hideduedate"));
m_allowReviewService = getBool(attributes.getValue("allowreview"));
m_allowStudentViewReport = getBool(attributes.getValue("allowstudentview"));
m_submitReviewRepo = attributes.getValue("submitReviewRepo");
m_generateOriginalityReport = attributes.getValue("generateOriginalityReport");
m_checkTurnitin = getBool(attributes.getValue("checkTurnitin"));
m_checkInternet = getBool(attributes.getValue("checkInternet"));
m_checkPublications = getBool(attributes.getValue("checkPublications"));
m_checkInstitution = getBool(attributes.getValue("checkInstitution"));
m_excludeBibliographic = getBool(attributes.getValue("excludeBibliographic"));
m_excludeQuoted = getBool(attributes.getValue("excludeQuoted"));
String excludeTypeStr = attributes.getValue("excludeType");
try{
m_excludeType = Integer.parseInt(excludeTypeStr);
if(m_excludeType != 0 && m_excludeType != 1 && m_excludeType != 2){
m_excludeType = 0;
}
}catch (Exception e) {
m_excludeType = 0;
}
String excludeValueStr = attributes.getValue("excludeValue");
try{
m_excludeValue = Integer.parseInt(excludeValueStr);
if(m_excludeValue < 0 || m_excludeValue > 100){
m_excludeValue = 1;
}
}catch (Exception e) {
m_excludeValue = 1;
}
m_timeCreated = getTimeObject(attributes.getValue("datecreated"));
m_timeLastModified = getTimeObject(attributes.getValue("lastmod"));
m_instructions = formattedTextDecodeFormattedTextAttribute(attributes, "instructions");
try
{
m_honorPledge = Integer.parseInt(attributes.getValue("honorpledge"));
}
catch (Exception e)
{
M_log.warn(" getContentHandler startElement Exception parsing honor pledge int from xml file string : " + e);
}
try
{
m_typeOfSubmission = Integer.parseInt(attributes.getValue("submissiontype"));
}
catch (Exception e)
{
M_log.warn(" getContentHandler startElement Exception parsing submission type int from xml file string : " + e);
}
try
{
m_typeOfGrade = Integer.parseInt(attributes.getValue("typeofgrade"));
}
catch (Exception e)
{
M_log.warn(" getContentHandler startElement Exception parsing grade type int from xml file string : " + e);
}
try
{
// %%%zqian
// read the scaled max grade point first; if there is none, get the old max grade value and multiple by 10
String maxGradePoint = StringUtils.trimToNull(attributes.getValue("scaled_maxgradepoint"));
if (maxGradePoint == null)
{
maxGradePoint = StringUtils.trimToNull(attributes.getValue("maxgradepoint"));
if (maxGradePoint != null)
{
maxGradePoint = maxGradePoint + "0";
}
}
m_maxGradePoint = maxGradePoint != null ? Integer.parseInt(maxGradePoint) : m_maxGradePoint;
}
catch (Exception e)
{
M_log.warn(" getContentHandler startElement Exception parsing maxgradepoint int from xml file string : " + e);
}
// READ THE AUTHORS
m_authors = new ArrayList();
intString = attributes.getValue("numberofauthors");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "author" + x;
tempString = attributes.getValue(attributeString);
if (tempString != null) m_authors.add(tempString);
}
}
catch (Exception e)
{
M_log.warn(" getContentHandler startElement Exception reading authors : " + e);
}
// READ THE ATTACHMENTS
m_attachments = m_entityManager.newReferenceList();
intString = attributes.getValue("numberofattachments");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "attachment" + x;
tempString = attributes.getValue(attributeString);
if (tempString != null)
{
tempReference = m_entityManager.newReference(tempString);
m_attachments.add(tempReference);
}
}
}
catch (Exception e)
{
M_log.warn(" getContentHandler startElement DbCachedContent : Exception reading attachments : " + e);
}
entity = thisEntity;
}
else
{
M_log.warn(" getContentHandler startElement Unexpected Element " + qName);
}
}
}
};
}
/**
* Takes the AssignmentContent's attribute values and puts them into the xml document.
*
* @param s -
* Data structure holding the object to be stored.
* @param doc -
* The xml document.
*/
public Element toXml(Document doc, Stack stack)
{
M_log.debug(this + " BASE ASSIGNMENT : ENTERING TOXML");
Element content = doc.createElement("content");
if (stack.isEmpty())
{
doc.appendChild(content);
}
else
{
((Element) stack.peek()).appendChild(content);
}
stack.push(content);
String numItemsString = null;
String attributeString = null;
String itemString = null;
Reference tempReference = null;
// SAK-13408 -The XML implementation in Websphere throws an LSException if the
// attribute is null, while in Tomcat it assumes an empty string. The following
// sets the attribute to an empty string if the value is null.
content.setAttribute("id", m_id == null ? "" : m_id);
content.setAttribute("context", m_context == null ? "" : m_context);
content.setAttribute("title", m_title == null ? "" : m_title);
content.setAttribute("groupproject", getBoolString(m_groupProject));
content.setAttribute("indivgraded", getBoolString(m_individuallyGraded));
content.setAttribute("releasegrades", getBoolString(m_releaseGrades));
content.setAttribute("allowattach", getBoolString(m_allowAttachments));
content.setAttribute("hideduedate", getBoolString(m_hideDueDate));
content.setAttribute("allowreview", getBoolString(m_allowReviewService));
content.setAttribute("allowstudentview", getBoolString(m_allowStudentViewReport));
content.setAttribute("submitReviewRepo", m_submitReviewRepo);
content.setAttribute("generateOriginalityReport", m_generateOriginalityReport);
content.setAttribute("checkTurnitin", getBoolString(m_checkTurnitin));
content.setAttribute("checkInternet", getBoolString(m_checkInternet));
content.setAttribute("checkPublications", getBoolString(m_checkPublications));
content.setAttribute("checkInstitution", getBoolString(m_checkInstitution));
content.setAttribute("excludeBibliographic", getBoolString(m_excludeBibliographic));
content.setAttribute("excludeQuoted", getBoolString(m_excludeQuoted));
content.setAttribute("excludeType", Integer.toString(m_excludeType));
content.setAttribute("excludeValue", Integer.toString(m_excludeValue));
content.setAttribute("honorpledge", String.valueOf(m_honorPledge));
content.setAttribute("submissiontype", String.valueOf(m_typeOfSubmission));
content.setAttribute("typeofgrade", String.valueOf(m_typeOfGrade));
content.setAttribute("scaled_maxgradepoint", String.valueOf(m_maxGradePoint));
content.setAttribute("datecreated", getTimeString(m_timeCreated));
content.setAttribute("lastmod", getTimeString(m_timeLastModified));
M_log.debug(this + " BASE CONTENT : TOXML : SAVED REGULAR PROPERTIES");
// SAVE THE AUTHORS
numItemsString = "" + m_authors.size();
content.setAttribute("numberofauthors", numItemsString);
for (int x = 0; x < m_authors.size(); x++)
{
attributeString = "author" + x;
itemString = (String) m_authors.get(x);
if (itemString != null) content.setAttribute(attributeString, itemString);
}
M_log.debug(this + " BASE CONTENT : TOXML : SAVED AUTHORS");
// SAVE THE ATTACHMENTS
numItemsString = "" + m_attachments.size();
content.setAttribute("numberofattachments", numItemsString);
for (int x = 0; x < m_attachments.size(); x++)
{
attributeString = "attachment" + x;
tempReference = (Reference) m_attachments.get(x);
itemString = tempReference.getReference();
if (itemString != null) content.setAttribute(attributeString, itemString);
}
// SAVE THE PROPERTIES
m_properties.toXml(doc, stack);
M_log.debug(this + " BASE CONTENT : TOXML : SAVED REGULAR PROPERTIES");
stack.pop();
// SAVE THE INSTRUCTIONS
FormattedText.encodeFormattedTextAttribute(content, "instructions", m_instructions);
return content;
}// toXml
protected void setAll(AssignmentContent content)
{
if (content != null)
{
m_id = content.getId();
m_context = content.getContext();
m_authors = content.getAuthors();
m_attachments = content.getAttachments();
m_title = content.getTitle();
m_instructions = content.getInstructions();
m_honorPledge = content.getHonorPledge();
m_typeOfSubmission = content.getTypeOfSubmission();
m_typeOfGrade = content.getTypeOfGrade();
m_maxGradePoint = content.getMaxGradePoint();
m_groupProject = content.getGroupProject();
m_individuallyGraded = content.individuallyGraded();
m_releaseGrades = content.releaseGrades();
m_allowAttachments = content.getAllowAttachments();
m_hideDueDate = content.getHideDueDate();
//Uct
m_allowReviewService = content.getAllowReviewService();
m_allowStudentViewReport = content.getAllowStudentViewReport();
m_submitReviewRepo = content.getSubmitReviewRepo();
m_generateOriginalityReport = content.getGenerateOriginalityReport();
m_checkTurnitin = content.isCheckTurnitin();
m_checkInternet = content.isCheckInternet();
m_checkPublications = content.isCheckPublications();
m_checkInstitution = content.isCheckInstitution();
m_excludeBibliographic = content.isExcludeBibliographic();
m_excludeQuoted = content.isExcludeQuoted();
m_excludeType = content.getExcludeType();
m_excludeValue = content.getExcludeValue();
m_timeCreated = content.getTimeCreated();
m_timeLastModified = content.getTimeLastModified();
m_properties = new BaseResourcePropertiesEdit();
m_properties.addAll(content.getProperties());
}
}
public String getId()
{
return m_id;
}
/**
* Access the URL which can be used to access the resource.
*
* @return The URL which can be used to access the resource.
*/
public String getUrl()
{
return getAccessPoint(false) + Entity.SEPARATOR + "c" + Entity.SEPARATOR + m_context + Entity.SEPARATOR + m_id;
} // getUrl
/**
* Access the internal reference which can be used to access the resource from within the system.
*
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String getReference()
{
return contentReference(m_context, m_id);
} // getReference
/**
* @inheritDoc
*/
public String getReference(String rootProperty)
{
return getReference();
}
/**
* @inheritDoc
*/
public String getUrl(String rootProperty)
{
return getUrl();
}
/**
* Access the resource's properties.
*
* @return The resource's properties.
*/
public ResourceProperties getProperties()
{
return m_properties;
}
/******************************************************************************************************************************************************************************************************************************************************
* AttachmentContainer Implementation
*****************************************************************************************************************************************************************************************************************************************************/
/**
* Access the attachments.
*
* @return The set of attachments (a ReferenceVector containing Reference objects) (may be empty).
*/
public List getAttachments()
{
return m_attachments;
}
/******************************************************************************************************************************************************************************************************************************************************
* AssignmentContent Implementation
*****************************************************************************************************************************************************************************************************************************************************/
/**
* Access the AssignmentContent's context at the time of creation.
*
* @return String - the context string.
*/
public String getContext()
{
return m_context;
}
/**
* Access the list of authors.
*
* @return FlexStringArray of user ids.
*/
public List getAuthors()
{
return m_authors;
}
/**
* Access the creator of this object.
*
* @return The User object representing the creator.
*/
public String getCreator()
{
return m_properties.getProperty(ResourceProperties.PROP_CREATOR);
}
/**
* Access the person of last modificaiton
*
* @return the User
*/
public String getAuthorLastModified()
{
return m_properties.getProperty(ResourceProperties.PROP_MODIFIED_BY);
}
/**
* Access the title.
*
* @return The Assignment's title.
*/
public String getTitle()
{
return m_title;
}
/**
* Access the instructions.
*
* @return The Assignment Content's instructions.
*/
public String getInstructions()
{
return m_instructions;
}
/**
* Get the type of valid submission.
*
* @return int - Type of Submission.
*/
public int getTypeOfSubmission()
{
return m_typeOfSubmission;
}
/**
* Access a string describing the type of grade.
*
* @param gradeType -
* The integer representing the type of grade.
* @return Description of the type of grade.
*/
public String getTypeOfGradeString(int type)
{
String retVal = null;
switch (type)
{
case 1:
retVal = rb.getString("ungra");
break;
case 2:
retVal = rb.getString("letter");
break;
case 3:
retVal = rb.getString("points");
break;
case 4:
retVal = rb.getString("passfail");
break;
case 5:
retVal = rb.getString("check");
break;
default:
retVal = "Unknown Grade Type";
break;
}
return retVal;
}
/**
* Get the grade type.
*
* @return gradeType - The type of grade.
*/
public int getTypeOfGrade()
{
return m_typeOfGrade;
}
/**
* Get the maximum grade for grade type = SCORE_GRADE_TYPE(3)
*
* @return The maximum grade score.
*/
public int getMaxGradePoint()
{
return m_maxGradePoint;
}
/**
* Get the maximum grade for grade type = SCORE_GRADE_TYPE(3) Formated to show one decimal place
*
* @return The maximum grade score.
*/
public String getMaxGradePointDisplay()
{
// formated to show one decimal place, for example, 1000 to 100.0
String one_decimal_maxGradePoint = m_maxGradePoint / 10 + "." + (m_maxGradePoint % 10);
// get localized number format
NumberFormat nbFormat = NumberFormat.getInstance();
try {
Locale locale = null;
ResourceLoader rb = new ResourceLoader();
locale = rb.getLocale();
nbFormat = NumberFormat.getNumberInstance(locale);
}
catch (Exception e) {
M_log.warn("Error while retrieving local number format, using default ", e);
}
nbFormat.setMaximumFractionDigits(1);
nbFormat.setMinimumFractionDigits(1);
nbFormat.setGroupingUsed(false);
// show grade in localized number format
Double dblGrade = new Double(one_decimal_maxGradePoint);
one_decimal_maxGradePoint = nbFormat.format(dblGrade);
return one_decimal_maxGradePoint;
}
/**
* Get whether this project can be a group project.
*
* @return True if this can be a group project, false otherwise.
*/
public boolean getGroupProject()
{
return m_groupProject;
}
/**
* Get whether group projects should be individually graded.
*
* @return individGraded - true if projects are individually graded, false if grades are given to the group.
*/
public boolean individuallyGraded()
{
return m_individuallyGraded;
}
/**
* Gets whether grades can be released once submissions are graded.
*
* @return true if grades can be released once submission are graded, false if they must be released manually.
*/
public boolean releaseGrades()
{
return m_releaseGrades;
}
/**
* Get the Honor Pledge type; values are NONE and ENGINEERING_HONOR_PLEDGE.
*
* @return the Honor Pledge value.
*/
public int getHonorPledge()
{
return m_honorPledge;
}
/**
* Does this Assignment allow attachments?
*
* @return true if the Assignment allows attachments, false otherwise?
*/
public boolean getAllowAttachments()
{
return m_allowAttachments;
}
/**
* Does this Assignment have a hidden due date
*
* @return true if the Assignment due date hidden, false otherwise?
*/
public boolean getHideDueDate()
{
return m_hideDueDate;
}
/**
* Does this Assignment allow review service?
*
* @return true if the Assignment allows review service, false otherwise?
*/
public boolean getAllowReviewService()
{
return m_allowReviewService;
}
public boolean getAllowStudentViewReport() {
return m_allowStudentViewReport;
}
/**
* Access the time that this object was created.
*
* @return The Time object representing the time of creation.
*/
public Time getTimeCreated()
{
return m_timeCreated;
}
/**
* Access the time of last modificaiton.
*
* @return The Time of last modification.
*/
public Time getTimeLastModified()
{
return m_timeLastModified;
}
/**
* Is this AssignmentContent selected for use by an Assignment ?
*/
public boolean inUse()
{
boolean retVal = false;
Assignment assignment = null;
List allAssignments = getAssignments(m_context);
for (int x = 0; x < allAssignments.size(); x++)
{
assignment = (Assignment) allAssignments.get(x);
if (assignment.getContentReference().equals(getReference())) return true;
}
return retVal;
}
/**
* Are these objects equal? If they are both AssignmentContent objects, and they have matching id's, they are.
*
* @return true if they are equal, false if not.
*/
public boolean equals(Object obj)
{
if (!(obj instanceof AssignmentContent)) return false;
return ((AssignmentContent) obj).getId().equals(getId());
} // equals
/**
* Make a hash code that reflects the equals() logic as well. We want two objects, even if different instances, if they have the same id to hash the same.
*/
public int hashCode()
{
return getId().hashCode();
} // hashCode
/**
* Compare this object with the specified object for order.
*
* @return A negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
*/
public int compareTo(Object obj)
{
if (!(obj instanceof AssignmentContent)) throw new ClassCastException();
// if the object are the same, say so
if (obj == this) return 0;
// start the compare by comparing their sort names
int compare = getTitle().compareTo(((AssignmentContent) obj).getTitle());
// if these are the same
if (compare == 0)
{
// sort based on (unique) id
compare = getId().compareTo(((AssignmentContent) obj).getId());
}
return compare;
} // compareTo
public String getSubmitReviewRepo() {
return m_submitReviewRepo;
}
public void setSubmitReviewRepo(String m_submitReviewRepo) {
this.m_submitReviewRepo = m_submitReviewRepo;
}
public String getGenerateOriginalityReport() {
return m_generateOriginalityReport;
}
public void setGenerateOriginalityReport(String m_generateOriginalityReport) {
this.m_generateOriginalityReport = m_generateOriginalityReport;
}
public boolean isCheckTurnitin() {
return m_checkTurnitin;
}
public void setCheckTurnitin(boolean m_checkTurnitin) {
this.m_checkTurnitin = m_checkTurnitin;
}
public boolean isCheckInternet() {
return m_checkInternet;
}
public void setCheckInternet(boolean m_checkInternet) {
this.m_checkInternet = m_checkInternet;
}
public boolean isCheckPublications() {
return m_checkPublications;
}
public void setCheckPublications(boolean m_checkPublications) {
this.m_checkPublications = m_checkPublications;
}
public boolean isCheckInstitution() {
return m_checkInstitution;
}
public void setCheckInstitution(boolean m_checkInstitution) {
this.m_checkInstitution = m_checkInstitution;
}
public boolean isExcludeBibliographic() {
return m_excludeBibliographic;
}
public void setExcludeBibliographic(boolean m_excludeBibliographic) {
this.m_excludeBibliographic = m_excludeBibliographic;
}
public boolean isExcludeQuoted() {
return m_excludeQuoted;
}
public void setExcludeQuoted(boolean m_excludeQuoted) {
this.m_excludeQuoted = m_excludeQuoted;
}
public int getExcludeType(){
return m_excludeType;
}
public void setExcludeType(int m_excludeType){
this.m_excludeType = m_excludeType;
}
public int getExcludeValue(){
return m_excludeValue;
}
public void setExcludeValue(int m_excludeValue){
this.m_excludeValue = m_excludeValue;
}
}// BaseAssignmentContent
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentContentEdit implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* <p>
* BaseAssignmentContentEdit is an implementation of the CHEF AssignmentContentEdit object.
* </p>
*
* @author University of Michigan, CHEF Software Development Team
*/
public class BaseAssignmentContentEdit extends BaseAssignmentContent implements AttachmentContainer, AssignmentContentEdit,
SessionBindingListener
{
/** The event code for this edit. */
protected String m_event = null;
/** Active flag. */
protected boolean m_active = false;
/**
* Construct from another AssignmentContent object.
*
* @param AssignmentContent
* The AssignmentContent object to use for values.
*/
public BaseAssignmentContentEdit(AssignmentContent assignmentContent)
{
super(assignmentContent);
} // BaseAssignmentContentEdit
/**
* Construct.
*
* @param id
* The AssignmentContent id.
*/
public BaseAssignmentContentEdit(String id, String context)
{
super(id, context);
} // BaseAssignmentContentEdit
/**
* Construct from information in XML.
*
* @param el
* The XML DOM Element definining the AssignmentContent.
*/
public BaseAssignmentContentEdit(Element el)
{
super(el);
} // BaseAssignmentContentEdit
/**
* Clean up.
*/
protected void finalize()
{
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelEdit(this);
}
} // finalize
/******************************************************************************************************************************************************************************************************************************************************
* AttachmentContainer Implementation
*****************************************************************************************************************************************************************************************************************************************************/
/**
* Add an attachment.
*
* @param ref -
* The attachment Reference.
*/
public void addAttachment(Reference ref)
{
if (ref != null) m_attachments.add(ref);
}
/**
* Remove an attachment.
*
* @param ref -
* The attachment Reference to remove (the one removed will equal this, they need not be ==).
*/
public void removeAttachment(Reference ref)
{
if (ref != null) m_attachments.remove(ref);
}
/**
* Replace the attachment set.
*
* @param attachments -
* A ReferenceVector that will become the new set of attachments.
*/
public void replaceAttachments(List attachments)
{
m_attachments = attachments;
}
/**
* Clear all attachments.
*/
public void clearAttachments()
{
m_attachments.clear();
}
/******************************************************************************************************************************************************************************************************************************************************
* AssignmentContentEdit Implementation
*****************************************************************************************************************************************************************************************************************************************************/
/**
* Set the title.
*
* @param title -
* The Assignment's title.
*/
public void setTitle(String title)
{
m_title = title;
}
/**
* Set the instructions.
*
* @param instructions -
* The Assignment's instructions.
*/
public void setInstructions(String instructions)
{
m_instructions = instructions;
}
/**
* Set the context at the time of creation.
*
* @param context -
* the context string.
*/
public void setContext(String context)
{
m_context = context;
}
/**
* Set the type of valid submission.
*
* @param int -
* Type of Submission.
*/
public void setTypeOfSubmission(int type)
{
m_typeOfSubmission = type;
}
/**
* Set the grade type.
*
* @param gradeType -
* The type of grade.
*/
public void setTypeOfGrade(int gradeType)
{
m_typeOfGrade = gradeType;
}
/**
* Set the maximum grade for grade type = SCORE_GRADE_TYPE(3)
*
* @param maxPoints -
* The maximum grade score.
*/
public void setMaxGradePoint(int maxPoints)
{
m_maxGradePoint = maxPoints;
}
/**
* Set whether this project can be a group project.
*
* @param groupProject -
* True if this can be a group project, false otherwise.
*/
public void setGroupProject(boolean groupProject)
{
m_groupProject = groupProject;
}
/**
* Set whether group projects should be individually graded.
*
* @param individGraded -
* true if projects are individually graded, false if grades are given to the group.
*/
public void setIndividuallyGraded(boolean individGraded)
{
m_individuallyGraded = individGraded;
}
/**
* Sets whether grades can be released once submissions are graded.
*
* @param release -
* true if grades can be released once submission are graded, false if they must be released manually.
*/
public void setReleaseGrades(boolean release)
{
m_releaseGrades = release;
}
public void setHideDueDate(boolean hide)
{
m_hideDueDate = hide;
}
/**
* Set the Honor Pledge type; values are NONE and ENGINEERING_HONOR_PLEDGE.
*
* @param pledgeType -
* the Honor Pledge value.
*/
public void setHonorPledge(int pledgeType)
{
m_honorPledge = pledgeType;
}
/**
* Does this Assignment allow using the review service?
*
* @param allow -
* true if the Assignment allows review service, false otherwise?
*/
public void setAllowReviewService(boolean allow)
{
m_allowReviewService = allow;
}
/**
* Does this Assignment allow students to view the report?
*
* @param allow -
* true if the Assignment allows students to view the report, false otherwise?
*/
public void setAllowStudentViewReport(boolean allow) {
m_allowStudentViewReport = allow;
}
/**
* Does this Assignment allow attachments?
*
* @param allow -
* true if the Assignment allows attachments, false otherwise?
*/
public void setAllowAttachments(boolean allow)
{
m_allowAttachments = allow;
}
/**
* Add an author to the author list.
*
* @param author -
* The User to add to the author list.
*/
public void addAuthor(User author)
{
if (author != null) m_authors.add(author.getId());
}
/**
* Remove an author from the author list.
*
* @param author -
* the User to remove from the author list.
*/
public void removeAuthor(User author)
{
if (author != null) m_authors.remove(author.getId());
}
/**
* Set the time last modified.
*
* @param lastmod -
* The Time at which the Content was last modified.
*/
public void setTimeLastModified(Time lastmod)
{
if (lastmod != null) m_timeLastModified = lastmod;
}
/**
* Take all values from this object.
*
* @param AssignmentContent
* The AssignmentContent object to take values from.
*/
protected void set(AssignmentContent assignmentContent)
{
setAll(assignmentContent);
} // set
/**
* Access the event code for this edit.
*
* @return The event code for this edit.
*/
protected String getEvent()
{
return m_event;
}
/**
* Set the event code for this edit.
*
* @param event
* The event code for this edit.
*/
protected void setEvent(String event)
{
m_event = event;
}
/**
* Access the resource's properties for modification
*
* @return The resource's properties.
*/
public ResourcePropertiesEdit getPropertiesEdit()
{
return m_properties;
} // getPropertiesEdit
/**
* Enable editing.
*/
protected void activate()
{
m_active = true;
} // activate
/**
* Check to see if the edit is still active, or has already been closed.
*
* @return true if the edit is active, false if it's been closed.
*/
public boolean isActiveEdit()
{
return m_active;
} // isActiveEdit
/**
* Close the edit object - it cannot be used after this.
*/
protected void closeEdit()
{
m_active = false;
} // closeEdit
/******************************************************************************************************************************************************************************************************************************************************
* SessionBindingListener implementation
*****************************************************************************************************************************************************************************************************************************************************/
public void valueBound(SessionBindingEvent event)
{
}
public void valueUnbound(SessionBindingEvent event)
{
M_log.debug(" BaseAssignmentContent valueUnbound()");
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelEdit(this);
}
} // valueUnbound
} // BaseAssignmentContentEdit
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentSubmission implementation
*********************************************************************************************************************************************************************************************************************************************************/
public class BaseAssignmentSubmission implements AssignmentSubmission
{
protected final String STATUS_DRAFT = "Drafted";
protected final String STATUS_SUBMITTED = "Submitted";
protected final String STATUS_RETURNED = "Returned";
protected final String STATUS_GRADED = "Graded";
protected ResourcePropertiesEdit m_properties;
protected String m_id;
protected String m_assignment;
protected String m_context;
protected List m_submitters;
protected String m_submitterId;
protected List m_submissionLog;
protected List m_grades;
protected Time m_timeSubmitted;
protected Time m_timeReturned;
protected Time m_timeLastModified;
protected List m_submittedAttachments;
protected List m_feedbackAttachments;
protected String m_submittedText;
protected String m_feedbackComment;
protected String m_feedbackText;
protected String m_grade;
protected boolean m_submitted;
protected boolean m_returned;
protected boolean m_graded;
protected String m_gradedBy;
protected boolean m_gradeReleased;
protected boolean m_honorPledgeFlag;
protected boolean m_hideDueDate;
//The score given by the review service
protected Integer m_reviewScore;
// The report given by the content review service
protected String m_reviewReport;
// The status of the review service
protected String m_reviewStatus;
protected String m_reviewIconUrl;
protected String m_reviewError;
// return the variables
// Get new values from review service if defaults
public int getReviewScore() {
// Code to get updated score if default
M_log.debug(this + " getReviewScore for submission " + this.getId() + " and review service is: " + (this.getAssignment().getContent().getAllowReviewService()));
if (!this.getAssignment().getContent().getAllowReviewService()) {
M_log.debug(this + " getReviewScore Content review is not enabled for this assignment");
return -2;
}
if (m_submittedAttachments.isEmpty()) {
M_log.debug(this + " getReviewScore No attachments submitted.");
return -2;
}
else
{
//we may have already retrived this one
if (m_reviewScore != null && m_reviewScore > -1) {
M_log.debug("returning stored value of " + m_reviewScore);
return m_reviewScore.intValue();
}
ContentResource cr = getFirstAcceptableAttachement();
if (cr == null )
{
M_log.debug(this + " getReviewScore No suitable attachments found in list");
return -2;
}
try {
//we need to find the first attachment the CR will accept
String contentId = cr.getId();
M_log.debug(this + " getReviewScore checking for score for content: " + contentId);
Long status = contentReviewService.getReviewStatus(contentId);
if (status != null && (status.equals(ContentReviewItem.NOT_SUBMITTED_CODE) || status.equals(ContentReviewItem.SUBMITTED_AWAITING_REPORT_CODE))) {
M_log.debug(this + " getReviewStatus returned a status of: " + status);
return -2;
}
int score = contentReviewService.getReviewScore(contentId);
m_reviewScore = score;
M_log.debug(this + " getReviewScore CR returned a score of: " + score);
return score;
}
catch (QueueException cie) {
//should we add the item
try {
M_log.debug(this + " getReviewScore Item is not in queue we will try add it");
String contentId = cr.getId();
String userId = this.getSubmitterId();
try {
contentReviewService.queueContent(userId, null, getAssignment().getReference(), contentId);
}
catch (QueueException qe) {
M_log.warn(" getReviewScore Unable to queue content with content review Service: " + qe.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
catch (Exception e) {
M_log.warn(this + " getReviewScore " + e.getMessage());
return -1;
}
}
}
public String getReviewReport() {
// Code to get updated report if default
if (m_submittedAttachments.isEmpty()) {
M_log.debug(this.getId() + " getReviewReport No attachments submitted.");
return "Error";
}
else
{
try {
ContentResource cr = getFirstAcceptableAttachement();
if (cr == null )
{
M_log.debug(this + " getReviewReport No suitable attachments found in list");
return "error";
}
String contentId = cr.getId();
if (allowGradeSubmission(getReference()))
return contentReviewService.getReviewReportInstructor(contentId);
else
return contentReviewService.getReviewReportStudent(contentId);
} catch (Exception e) {
M_log.warn(":getReviewReport() " + e.getMessage());
return "Error";
}
}
}
private ContentResource getFirstAcceptableAttachement() {
String contentId = null;
try {
for( int i =0; i < m_submittedAttachments.size();i++ ) {
Reference ref = (Reference)m_submittedAttachments.get(i);
ContentResource contentResource = (ContentResource)ref.getEntity();
if (contentReviewService.isAcceptableContent(contentResource)) {
return (ContentResource)contentResource;
}
}
}
catch (Exception e) {
M_log.warn(":getFirstAcceptableAttachment() " + e.getMessage());
e.printStackTrace();
}
return null;
}
public String getReviewStatus() {
return m_reviewStatus;
}
public String getReviewError() {
// Code to get error report
if (m_submittedAttachments.isEmpty()) {
M_log.debug(this.getId() + " getReviewError No attachments submitted.");
return null;
}
else
{
try {
ContentResource cr = getFirstAcceptableAttachement();
if (cr == null )
{
M_log.debug(this + " getReviewError No suitable attachments found in list");
return null;
}
String contentId = cr.getId();
// This should use getLocalizedReviewErrorMessage(contentId)
// to get a i18n message of the error
Long status = contentReviewService.getReviewStatus(contentId);
String errorMessage = null;
if (status != null) {
if (status.equals(ContentReviewItem.REPORT_ERROR_NO_RETRY_CODE)) {
errorMessage = rb.getString("content_review.error.REPORT_ERROR_NO_RETRY_CODE");
} else if (status.equals(ContentReviewItem.REPORT_ERROR_RETRY_CODE)) {
errorMessage = rb.getString("content_review.error.REPORT_ERROR_RETRY_CODE");
} else if (status.equals(ContentReviewItem.SUBMISSION_ERROR_NO_RETRY_CODE)) {
errorMessage = rb.getString("content_review.error.SUBMISSION_ERROR_NO_RETRY_CODE");
} else if (status.equals(ContentReviewItem.SUBMISSION_ERROR_RETRY_CODE)) {
errorMessage = rb.getString("content_review.error.SUBMISSION_ERROR_RETRY_CODE");
} else if (status.equals(ContentReviewItem.SUBMISSION_ERROR_RETRY_EXCEEDED)) {
errorMessage = rb.getString("content_review.error.SUBMISSION_ERROR_RETRY_EXCEEDED_CODE");
} else if (status.equals(ContentReviewItem.SUBMISSION_ERROR_USER_DETAILS_CODE)) {
errorMessage = rb.getString("content_review.error.SUBMISSION_ERROR_USER_DETAILS_CODE");
} else if (ContentReviewItem.SUBMITTED_AWAITING_REPORT_CODE.equals(status)
|| ContentReviewItem.NOT_SUBMITTED_CODE.equals(status)) {
errorMessage = rb.getString("content_review.pending.info");
}
}
if (errorMessage == null) {
errorMessage = rb.getString("content_review.error");
}
return errorMessage;
} catch (Exception e) {
//e.printStackTrace();
M_log.warn(this + ":getReviewError() " + e.getMessage());
return null;
}
}
}
public String getReviewIconUrl() {
if (m_reviewIconUrl == null )
m_reviewIconUrl = contentReviewService.getIconUrlforScore(Long.valueOf(this.getReviewScore()));
return m_reviewIconUrl;
}
/**
* constructor
*/
public BaseAssignmentSubmission()
{
m_properties = new BaseResourcePropertiesEdit();
}// constructor
/**
* Copy constructor.
*/
public BaseAssignmentSubmission(AssignmentSubmission submission)
{
setAll(submission);
}
/**
* Constructor used by addSubmission.
*/
public BaseAssignmentSubmission(String id, String assignId, String submitterId, String submitTime, String submitted, String graded)
{
// must set initial review status
m_reviewStatus = "";
m_reviewScore = -1;
m_reviewReport = "Not available yet";
m_reviewError = "";
m_id = id;
m_assignment = assignId;
m_properties = new BaseResourcePropertiesEdit();
addLiveProperties(m_properties);
m_submitters = new ArrayList();
m_submissionLog = new ArrayList();
m_grades = new ArrayList();
m_feedbackAttachments = m_entityManager.newReferenceList();
m_submittedAttachments = m_entityManager.newReferenceList();
m_submitted = false;
m_returned = false;
m_graded = false;
m_gradedBy = null;
m_gradeReleased = false;
m_submittedText = "";
m_feedbackComment = "";
m_feedbackText = "";
m_grade = "";
m_timeLastModified = TimeService.newTime();
m_submitterId = submitterId;
if (submitterId == null)
{
String currentUser = SessionManager.getCurrentSessionUserId();
if (currentUser == null) currentUser = "";
m_submitters.add(currentUser);
m_submitterId = currentUser;
}
else
{
m_submitters.add(submitterId);
}
if (submitted != null)
{
m_submitted = Boolean.valueOf(submitted).booleanValue();
}
if (graded != null)
{
m_graded = Boolean.valueOf(graded).booleanValue();
}
}
// todo work out what this does
/**
* Reads the AssignmentSubmission's attribute values from xml.
*
* @param s -
* Data structure holding the xml info.
*/
public BaseAssignmentSubmission(Element el)
{
int numAttributes = 0;
String intString = null;
String attributeString = null;
String tempString = null;
Reference tempReference = null;
M_log.debug(" BaseAssigmentSubmission : ENTERING STORAGE CONSTRUCTOR");
m_id = el.getAttribute("id");
m_context = el.getAttribute("context");
// %%%zqian
// read the scaled grade point first; if there is none, get the old grade value
String grade = StringUtils.trimToNull(el.getAttribute("scaled_grade"));
if (grade == null)
{
grade = StringUtils.trimToNull(el.getAttribute("grade"));
if (grade != null)
{
try
{
Integer.parseInt(grade);
// for the grades in points, multiple those by 10
grade = grade + "0";
}
catch (Exception e)
{
M_log.warn(":BaseAssignmentSubmission(Element el) " + e.getMessage());
}
}
}
m_grade = grade;
m_assignment = el.getAttribute("assignment");
m_timeSubmitted = getTimeObject(el.getAttribute("datesubmitted"));
m_timeReturned = getTimeObject(el.getAttribute("datereturned"));
m_assignment = el.getAttribute("assignment");
m_timeLastModified = getTimeObject(el.getAttribute("lastmod"));
m_submitted = getBool(el.getAttribute("submitted"));
m_returned = getBool(el.getAttribute("returned"));
m_graded = getBool(el.getAttribute("graded"));
m_gradedBy = el.getAttribute("gradedBy");
m_gradeReleased = getBool(el.getAttribute("gradereleased"));
m_honorPledgeFlag = getBool(el.getAttribute("pledgeflag"));
m_hideDueDate = getBool(el.getAttribute("hideduedate"));
m_submittedText = FormattedText.decodeFormattedTextAttribute(el, "submittedtext");
m_feedbackComment = FormattedText.decodeFormattedTextAttribute(el, "feedbackcomment");
m_feedbackText = FormattedText.decodeFormattedTextAttribute(el, "feedbacktext");
m_submitterId = el.getAttribute("submitterid");
m_submissionLog = new ArrayList();
m_grades = new ArrayList();
intString = el.getAttribute("numberoflogs");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "log" + x;
tempString = el.getAttribute(attributeString);
if (tempString != null) m_submissionLog.add(tempString);
}
}
catch (Exception e)
{
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : Exception reading logs : " + e);
}
intString = el.getAttribute("numberofgrades");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "grade" + x;
tempString = el.getAttribute(attributeString);
if (tempString != null) m_grades.add(tempString);
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission: CONSTRUCTOR : Exception reading grades : " + e);
}
// READ THE SUBMITTERS
m_submitters = new ArrayList();
M_log.debug(" BaseAssignmentSubmission : CONSTRUCTOR : Reading submitters : ");
intString = el.getAttribute("numberofsubmitters");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "submitter" + x;
tempString = el.getAttribute(attributeString);
if (tempString != null) m_submitters.add(tempString);
}
}
catch (Exception e)
{
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : Exception reading submitters : " + e);
}
// READ THE FEEDBACK ATTACHMENTS
m_feedbackAttachments = m_entityManager.newReferenceList();
intString = el.getAttribute("numberoffeedbackattachments");
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : num feedback attachments : " + intString);
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "feedbackattachment" + x;
tempString = el.getAttribute(attributeString);
if (tempString != null)
{
tempReference = m_entityManager.newReference(tempString);
m_feedbackAttachments.add(tempReference);
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : " + attributeString + " : "
+ tempString);
}
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission: CONSTRUCTOR : Exception reading feedback attachments : " + e);
}
// READ THE SUBMITTED ATTACHMENTS
m_submittedAttachments = m_entityManager.newReferenceList();
intString = el.getAttribute("numberofsubmittedattachments");
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : num submitted attachments : " + intString);
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "submittedattachment" + x;
tempString = el.getAttribute(attributeString);
if (tempString != null)
{
tempReference = m_entityManager.newReference(tempString);
m_submittedAttachments.add(tempReference);
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : " + attributeString + " : "
+ tempString);
}
}
}
catch (Exception e)
{
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : Exception reading submitted attachments : " + e);
}
// READ THE PROPERTIES, SUBMITTED TEXT, FEEDBACK COMMENT, FEEDBACK TEXT
NodeList children = el.getChildNodes();
final int length = children.getLength();
for (int i = 0; i < length; i++)
{
Node child = children.item(i);
if (child.getNodeType() != Node.ELEMENT_NODE) continue;
Element element = (Element) child;
// look for properties
if (element.getTagName().equals("properties"))
{
// re-create properties
m_properties = new BaseResourcePropertiesEdit(element);
}
// old style encoding
else if (element.getTagName().equals("submittedtext"))
{
if ((element.getChildNodes() != null) && (element.getChildNodes().item(0) != null))
{
m_submittedText = element.getChildNodes().item(0).getNodeValue();
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : submittedtext : " + m_submittedText);
}
if (m_submittedText == null)
{
m_submittedText = "";
}
}
// old style encoding
else if (element.getTagName().equals("feedbackcomment"))
{
if ((element.getChildNodes() != null) && (element.getChildNodes().item(0) != null))
{
m_feedbackComment = element.getChildNodes().item(0).getNodeValue();
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : feedbackcomment : "
+ m_feedbackComment);
}
if (m_feedbackComment == null)
{
m_feedbackComment = "";
}
}
// old style encoding
else if (element.getTagName().equals("feedbacktext"))
{
if ((element.getChildNodes() != null) && (element.getChildNodes().item(0) != null))
{
m_feedbackText = element.getChildNodes().item(0).getNodeValue();
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : FEEDBACK TEXT : " + m_feedbackText);
}
if (m_feedbackText == null)
{
m_feedbackText = "";
}
}
}
try {
if (el.getAttribute("reviewScore")!=null)
m_reviewScore = Integer.parseInt(el.getAttribute("reviewScore"));
else
m_reviewScore = -1;
}
catch (NumberFormatException nfe) {
m_reviewScore = -1;
M_log.warn(":BaseAssignmentSubmission(Element) " + nfe.getMessage());
}
try {
// The report given by the content review service
if (el.getAttribute("reviewReport")!=null)
m_reviewReport = el.getAttribute("reviewReport");
else
m_reviewReport = "no report available";
// The status of the review service
if (el.getAttribute("reviewStatus")!=null)
m_reviewStatus = el.getAttribute("reviewStatus");
else
m_reviewStatus = "";
// The status of the review service
if (el.getAttribute("reviewError")!=null)
m_reviewError = el.getAttribute("reviewError");
else
m_reviewError = "";
}
catch (Exception e) {
M_log.error("error constructing Submission: " + e);
}
//get the review Status from ContentReview rather than using old ones
if (contentReviewService != null) {
m_reviewStatus = this.getReviewStatus();
m_reviewScore = this.getReviewScore();
m_reviewError = this.getReviewError();
}
M_log.debug(" BaseAssignmentSubmission: LEAVING STORAGE CONSTRUCTOR");
}// storage constructor
/**
* @param services
* @return
*/
public ContentHandler getContentHandler(Map<String, Object> services)
{
final Entity thisEntity = this;
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.DefaultEntityHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String,
* org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if ("submission".equals(qName) && entity == null)
{
try {
if (StringUtils.trimToNull(attributes.getValue("reviewScore"))!=null)
m_reviewScore = Integer.parseInt(attributes.getValue("reviewScore"));
else
m_reviewScore = -1;
}
catch (NumberFormatException nfe) {
m_reviewScore = -1;
M_log.warn(":AssignmentSubmission:getContentHandler:DefaultEntityHandler " + nfe.getMessage());
}
try {
// The report given by the content review service
if (attributes.getValue("reviewReport")!=null)
m_reviewReport = attributes.getValue("reviewReport");
else
m_reviewReport = "no report available";
// The status of the review service
if (attributes.getValue("reviewStatus")!=null)
m_reviewStatus = attributes.getValue("reviewStatus");
else
m_reviewStatus = "";
// The status of the review service
if (attributes.getValue("reviewError")!=null) {
m_reviewError = attributes.getValue("reviewError");
} else {
m_reviewError = "";
}
}
catch (Exception e) {
M_log.error("error constructing Submission: " + e);
}
int numAttributes = 0;
String intString = null;
String attributeString = null;
String tempString = null;
Reference tempReference = null;
m_id = attributes.getValue("id");
// M_log.info(this + " BASE SUBMISSION : CONSTRUCTOR : m_id : " + m_id);
m_context = attributes.getValue("context");
// M_log.info(this + " BASE SUBMISSION : CONSTRUCTOR : m_context : " + m_context);
// %%%zqian
// read the scaled grade point first; if there is none, get the old grade value
String grade = StringUtils.trimToNull(attributes.getValue("scaled_grade"));
if (grade == null)
{
grade = StringUtils.trimToNull(attributes.getValue("grade"));
if (grade != null)
{
try
{
Integer.parseInt(grade);
// for the grades in points, multiple those by 10
grade = grade + "0";
}
catch (Exception e)
{
M_log.warn(":BaseAssignmentSubmission:getContentHanler:DefaultEnityHandler " + e.getMessage());
}
}
}
m_grade = grade;
m_assignment = attributes.getValue("assignment");
m_timeSubmitted = getTimeObject(attributes.getValue("datesubmitted"));
m_timeReturned = getTimeObject(attributes.getValue("datereturned"));
m_assignment = attributes.getValue("assignment");
m_timeLastModified = getTimeObject(attributes.getValue("lastmod"));
m_submitted = getBool(attributes.getValue("submitted"));
m_returned = getBool(attributes.getValue("returned"));
m_graded = getBool(attributes.getValue("graded"));
m_gradedBy = attributes.getValue("gradedBy");
m_gradeReleased = getBool(attributes.getValue("gradereleased"));
m_honorPledgeFlag = getBool(attributes.getValue("pledgeflag"));
m_hideDueDate = getBool(attributes.getValue("hideduedate"));
m_submittedText = formattedTextDecodeFormattedTextAttribute(attributes, "submittedtext");
m_feedbackComment = formattedTextDecodeFormattedTextAttribute(attributes, "feedbackcomment");
m_feedbackText = formattedTextDecodeFormattedTextAttribute(attributes, "feedbacktext");
m_submitterId = attributes.getValue("submitterid");
m_submissionLog = new ArrayList();
m_grades = new ArrayList();
intString = attributes.getValue("numberoflogs");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "log" + x;
tempString = attributes.getValue(attributeString);
if (tempString != null) {
m_submissionLog.add(tempString);
}
}
}
catch (Exception e)
{
M_log.debug(" BaseAssignmentSubmission: CONSTRUCTOR : Exception reading logs : " + e);
}
intString = attributes.getValue("numberofgrades");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "grade" + x;
tempString = attributes.getValue(attributeString);
if (tempString != null) m_grades.add(tempString);
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission: CONSTRUCTOR : Exception reading logs : " + e);
}
// READ THE SUBMITTERS
m_submitters = new ArrayList();
intString = attributes.getValue("numberofsubmitters");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "submitter" + x;
tempString = attributes.getValue(attributeString);
if (tempString != null) {
m_submitters.add(tempString);
}
// for backward compatibility of assignments without submitter ids
if (m_submitterId == null) {
m_submitterId = tempString;
}
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission getContentHandler : Exception reading submitters : " + e);
}
// READ THE FEEDBACK ATTACHMENTS
m_feedbackAttachments = m_entityManager.newReferenceList();
intString = attributes.getValue("numberoffeedbackattachments");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "feedbackattachment" + x;
tempString = attributes.getValue(attributeString);
if (tempString != null)
{
tempReference = m_entityManager.newReference(tempString);
m_feedbackAttachments.add(tempReference);
}
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission getContentHandler : Exception reading feedback attachments : " + e);
}
// READ THE SUBMITTED ATTACHMENTS
m_submittedAttachments = m_entityManager.newReferenceList();
intString = attributes.getValue("numberofsubmittedattachments");
try
{
numAttributes = Integer.parseInt(intString);
for (int x = 0; x < numAttributes; x++)
{
attributeString = "submittedattachment" + x;
tempString = attributes.getValue(attributeString);
if (tempString != null)
{
tempReference = m_entityManager.newReference(tempString);
m_submittedAttachments.add(tempReference);
}
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission getContentHandler: Exception reading submitted attachments : " + e);
}
entity = thisEntity;
}
}
}
};
}
/**
* Takes the AssignmentContent's attribute values and puts them into the xml document.
*
* @param s -
* Data structure holding the object to be stored.
* @param doc -
* The xml document.
*/
public Element toXml(Document doc, Stack stack)
{
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission : ENTERING TOXML");
Element submission = doc.createElement("submission");
if (stack.isEmpty())
{
doc.appendChild(submission);
}
else
{
((Element) stack.peek()).appendChild(submission);
}
stack.push(submission);
String numItemsString = null;
String attributeString = null;
String itemString = null;
Reference tempReference = null;
// SAK-13408 -The XML implementation in Websphere throws an LSException if the
// attribute is null, while in Tomcat it assumes an empty string. The following
// sets the attribute to an empty string if the value is null.
submission.setAttribute("reviewScore",m_reviewScore == null ? "" : Integer.toString(m_reviewScore));
submission.setAttribute("reviewReport",m_reviewReport == null ? "" : m_reviewReport);
submission.setAttribute("reviewStatus",m_reviewStatus == null ? "" : m_reviewStatus);
submission.setAttribute("reviewError",m_reviewError == null ? "" : m_reviewError);
submission.setAttribute("id", m_id == null ? "" : m_id);
submission.setAttribute("context", m_context == null ? "" : m_context);
submission.setAttribute("scaled_grade", m_grade == null ? "" : m_grade);
submission.setAttribute("assignment", m_assignment == null ? "" : m_assignment);
submission.setAttribute("datesubmitted", getTimeString(m_timeSubmitted));
submission.setAttribute("datereturned", getTimeString(m_timeReturned));
submission.setAttribute("lastmod", getTimeString(m_timeLastModified));
submission.setAttribute("submitted", getBoolString(m_submitted));
submission.setAttribute("returned", getBoolString(m_returned));
submission.setAttribute("graded", getBoolString(m_graded));
submission.setAttribute("gradedBy", m_gradedBy == null ? "" : m_gradedBy);
submission.setAttribute("gradereleased", getBoolString(m_gradeReleased));
submission.setAttribute("pledgeflag", getBoolString(m_honorPledgeFlag));
submission.setAttribute("hideduedate", getBoolString(m_hideDueDate));
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: SAVED REGULAR PROPERTIES");
submission.setAttribute("submitterid", m_submitterId == null ? "": m_submitterId);
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: SAVED SUBMITTER ID : " + m_submitterId);
numItemsString = "" + m_submissionLog.size();
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: # logs " + numItemsString);
submission.setAttribute("numberoflogs", numItemsString);
for (int x = 0; x < m_submissionLog.size(); x++)
{
attributeString = "log" + x;
itemString = (String) m_submissionLog.get(x);
if (itemString != null) {
submission.setAttribute(attributeString, itemString);
}
}
numItemsString = "" + m_grades.size();
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: # grades " + numItemsString);
submission.setAttribute("numberofgrades", numItemsString);
for (int x = 0; x < m_grades.size(); x++)
{
attributeString = "grade" + x;
itemString = (String) m_grades.get(x);
if (itemString != null) {
submission.setAttribute(attributeString, itemString);
}
}
// SAVE THE SUBMITTERS
numItemsString = "" + m_submitters.size();
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: # submitters " + numItemsString);
submission.setAttribute("numberofsubmitters", numItemsString);
for (int x = 0; x < m_submitters.size(); x++)
{
attributeString = "submitter" + x;
itemString = (String) m_submitters.get(x);
if (itemString != null) {
submission.setAttribute(attributeString, itemString);
}
}
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: SAVED SUBMITTERS");
// SAVE THE FEEDBACK ATTACHMENTS
numItemsString = "" + m_feedbackAttachments.size();
submission.setAttribute("numberoffeedbackattachments", numItemsString);
if (M_log.isDebugEnabled()) M_log.debug("DB : DbCachedStorage : DbCachedAssignmentSubmission : entering fb attach loop : size : "
+ numItemsString);
for (int x = 0; x < m_feedbackAttachments.size(); x++)
{
attributeString = "feedbackattachment" + x;
tempReference = (Reference) m_feedbackAttachments.get(x);
itemString = tempReference.getReference();
if (itemString != null) {
submission.setAttribute(attributeString, itemString);
}
}
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: SAVED FEEDBACK ATTACHMENTS");
// SAVE THE SUBMITTED ATTACHMENTS
numItemsString = "" + m_submittedAttachments.size();
submission.setAttribute("numberofsubmittedattachments", numItemsString);
for (int x = 0; x < m_submittedAttachments.size(); x++)
{
attributeString = "submittedattachment" + x;
tempReference = (Reference) m_submittedAttachments.get(x);
itemString = tempReference.getReference();
if (itemString != null) {
submission.setAttribute(attributeString, itemString);
}
}
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: SAVED SUBMITTED ATTACHMENTS");
// SAVE THE PROPERTIES
m_properties.toXml(doc, stack);
stack.pop();
FormattedText.encodeFormattedTextAttribute(submission, "submittedtext", m_submittedText);
FormattedText.encodeFormattedTextAttribute(submission, "feedbackcomment", m_feedbackComment);
FormattedText.encodeFormattedTextAttribute(submission, "feedbacktext", m_feedbackText);
if (M_log.isDebugEnabled()) M_log.debug(this + " BaseAssignmentSubmission: LEAVING TOXML");
return submission;
}// toXml
protected void setAll(AssignmentSubmission submission)
{
if (contentReviewService != null) {
m_reviewScore = submission.getReviewScore();
// The report given by the content review service
m_reviewReport = submission.getReviewReport();
// The status of the review service
m_reviewStatus = submission.getReviewStatus();
// Error msg, if any from review service
m_reviewError = submission.getReviewError();
}
m_id = submission.getId();
m_context = submission.getContext();
m_assignment = submission.getAssignmentId();
m_grade = submission.getGrade();
m_submitters = submission.getSubmitterIds();
m_submitted = submission.getSubmitted();
m_timeSubmitted = submission.getTimeSubmitted();
m_timeReturned = submission.getTimeReturned();
m_timeLastModified = submission.getTimeLastModified();
m_submittedAttachments = submission.getSubmittedAttachments();
m_feedbackAttachments = submission.getFeedbackAttachments();
m_submittedText = submission.getSubmittedText();
m_submitterId = submission.getSubmitterId();
m_submissionLog = submission.getSubmissionLog();
m_grades = submission.getGrades();
m_feedbackComment = submission.getFeedbackComment();
m_feedbackText = submission.getFeedbackText();
m_returned = submission.getReturned();
m_graded = submission.getGraded();
m_gradedBy = submission.getGradedBy();
m_gradeReleased = submission.getGradeReleased();
m_honorPledgeFlag = submission.getHonorPledgeFlag();
m_properties = new BaseResourcePropertiesEdit();
m_properties.addAll(submission.getProperties());
}
/**
* Access the URL which can be used to access the resource.
*
* @return The URL which can be used to access the resource.
*/
public String getUrl()
{
return getAccessPoint(false) + Entity.SEPARATOR + "s" + Entity.SEPARATOR + m_context + Entity.SEPARATOR + m_id;
} // getUrl
/**
* Access the internal reference which can be used to access the resource from within the system.
*
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String getReference()
{
return submissionReference(m_context, m_id, m_assignment);
} // getReference
/**
* @inheritDoc
*/
public String getReference(String rootProperty)
{
return getReference();
}
/**
* @inheritDoc
*/
public String getUrl(String rootProperty)
{
return getUrl();
}
/**
* Access the id of the resource.
*
* @return The id.
*/
public String getId()
{
return m_id;
}
/**
* Access the resource's properties.
*
* @return The resource's properties.
*/
public ResourceProperties getProperties()
{
return m_properties;
}
/******************************************************************************************************************************************************************************************************************************************************
* AssignmentSubmission implementation
*****************************************************************************************************************************************************************************************************************************************************/
/**
* Access the AssignmentSubmission's context at the time of creation.
*
* @return String - the context string.
*/
public String getContext()
{
return m_context;
}
/**
* Access the Assignment for this Submission
*
* @return the Assignment
*/
public Assignment getAssignment()
{
Assignment retVal = null;
if (m_assignment != null)
{
retVal = m_assignmentStorage.get(m_assignment);
}
// track event
//EventTrackingService.post(EventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT, retVal.getReference(), false));
return retVal;
}
/**
* Access the Id for the Assignment for this Submission
*
* @return String - the Assignment Id
*/
public String getAssignmentId()
{
return m_assignment;
}
/**
* Get whether this is a final submission.
*
* @return True if a final submission, false if still a draft.
*/
public boolean getSubmitted()
{
return m_submitted;
}
public String getSubmitterId() {
return m_submitterId;
}
public List getSubmissionLog() {
return m_submissionLog;
}
public List getGrades() {
return m_grades;
}
public String getGradeForUser(String id) {
if (m_grades != null) {
Iterator<String> _it = m_grades.iterator();
while (_it.hasNext()) {
String _s = _it.next();
if (_s.startsWith(id + "::")) {
return _s.endsWith("null") ? null: _s.substring(_s.indexOf("::") + 2);
}
}
}
return null;
}
/**
*
* @return Array of User objects.
*/
public User[] getSubmitters() {
List retVal = new ArrayList();
Assignment a = getAssignment();
if (a.isGroup()) {
try {
Site site = SiteService.getSite(a.getContext());
Group _g = site.getGroup(m_submitterId);
if (_g != null) {
Iterator<Member> _members = _g.getMembers().iterator();
while (_members.hasNext()) {
Member _member = _members.next();
try
{
retVal.add(UserDirectoryService.getUser(_member.getUserId()));
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission Group getSubmitters" + e.getMessage() + _member.getUserId());
}
}
}
} catch (IdUnusedException _iue) {
throw new IllegalStateException("Site ("+a.getContext()+") not found: "+_iue, _iue);
}
} else {
for (int x = 0; x < m_submitters.size(); x++)
{
String userId = (String) m_submitters.get(x);
try
{
retVal.add(UserDirectoryService.getUser(userId));
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission getSubmitters" + e.getMessage() + userId);
}
}
}
// compare users on sortname
java.util.Collections.sort(retVal, new UserComparator());
// get the User[] array
int size = retVal.size();
User[] rv = new User[size];
for(int k = 0; k<size; k++)
{
rv[k] = (User) retVal.get(k);
}
return rv;
}
/**
* Access the list of Users who submitted this response to the Assignment.
*
* @return FlexStringArray of user ids.
*/
public List getSubmitterIds()
{
Assignment a = getAssignment();
if (a.isGroup()) {
List retVal = new ArrayList();
try {
Site site = SiteService.getSite(a.getContext());
Group _g = site.getGroup(m_submitterId);
if (_g != null) {
Iterator<Member> _members = _g.getMembers().iterator();
while (_members.hasNext()) {
Member _member = _members.next();
retVal.add(_member.getUserId());
}
}
return retVal;
} catch (IdUnusedException _iue) {
return null;
}
} else {
return m_submitters;
}
}
/**
* {@inheritDoc}
*/
public String getSubmitterIdString ()
{
String rv = "";
if (m_submitters != null)
{
for (int j = 0; j < m_submitters.size(); j++)
{
rv = rv.concat((String) m_submitters.get(j));
}
}
return rv;
}
/**
* Set the time at which this response was submitted; null signifies the response is unsubmitted.
*
* @return Time of submission.
*/
public Time getTimeSubmitted()
{
return m_timeSubmitted;
}
/**
* @inheritDoc
*/
public String getTimeSubmittedString()
{
if ( m_timeSubmitted == null )
return "";
else
return m_timeSubmitted.toStringLocalFull();
}
/**
* Get whether the grade has been released.
*
* @return True if the Submissions's grade has been released, false otherwise.
*/
public boolean getGradeReleased()
{
return m_gradeReleased;
}
/**
* Access the grade recieved.
*
* @return The Submission's grade..
*/
public String getGrade()
{
return getGrade(true);
}
/**
* {@inheritDoc}
*/
public String getGrade(boolean overrideWithGradebookValue)
{
String rv = m_grade;
if (!overrideWithGradebookValue)
{
// use assignment submission grade
return m_grade;
}
else
{
// use grade from associated Gradebook
Assignment m = getAssignment();
String gAssignmentName = StringUtils.trimToNull(m.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
if (gAssignmentName != null)
{
GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = m.getContext();
// return student score from Gradebook
String userId = m_submitterId;
SecurityAdvisor securityAdvisor = new MySecurityAdvisor(
SessionManager.getCurrentSessionUserId(),
new ArrayList<String>(Arrays.asList("gradebook.gradeAll", "gradebook.gradeSection", "gradebook.editAssignments", "gradebook.viewOwnGrades")),
gradebookUid);
try
{
// add the grade permission ("gradebook.gradeAll", "gradebook.gradeSection", "gradebook.editAssignments", or "gradebook.viewOwnGrades") in order to use g.getAssignmentScoreString()
securityService.pushAdvisor(securityAdvisor);
if (g.isGradebookDefined(gradebookUid) && g.isAssignmentDefined(gradebookUid, gAssignmentName))
{
String gString = StringUtils.trimToNull(g.getAssignmentScoreString(gradebookUid, gAssignmentName, userId));
if (gString != null)
{
rv = gString;
}
}
}
catch (Exception e)
{
M_log.warn(" BaseAssignmentSubmission getGrade getAssignmentScoreString from GradebookService " + e.getMessage() + " context=" + m_context + " assignment id=" + m_assignment + " userId=" + userId + " gAssignmentName=" + gAssignmentName);
}
finally
{
// remove advisor
securityService.popAdvisor(securityAdvisor);
}
}
}
return rv;
}
/**
* Access the grade recieved.
*
* @return The Submission's grade..
*/
public String getGradeDisplay()
{
Assignment m = getAssignment();
String grade = getGrade();
if (m.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE)
{
if (grade != null && grade.length() > 0 && !"0".equals(grade))
{
String one_decimal_gradePoint = "";
try
{
Integer.parseInt(grade);
// if point grade, display the grade with one decimal place
one_decimal_gradePoint = grade.substring(0, grade.length() - 1) + "." + grade.substring(grade.length() - 1);
}
catch (NumberFormatException e) {
try {
Float.parseFloat(grade);
one_decimal_gradePoint = grade;
}
catch (Exception e1) {
return grade;
}
}
// get localized number format
NumberFormat nbFormat = NumberFormat.getInstance();
try {
Locale locale = null;
ResourceLoader rb = new ResourceLoader();
locale = rb.getLocale();
nbFormat = NumberFormat.getNumberInstance(locale);
}
catch (Exception e) {
M_log.warn("Error while retrieving local number format, using default ", e);
}
nbFormat.setMaximumFractionDigits(1);
nbFormat.setMinimumFractionDigits(1);
nbFormat.setGroupingUsed(false);
// show grade in localized number format
try {
Double dblGrade = new Double(one_decimal_gradePoint);
one_decimal_gradePoint = nbFormat.format(dblGrade);
}
catch (Exception e) {
return grade;
}
return one_decimal_gradePoint;
}
else
{
return StringUtils.trimToEmpty(grade);
}
}
else if (m.getContent().getTypeOfGrade() == Assignment.UNGRADED_GRADE_TYPE) {
String ret = "";
if (grade != null) {
if (grade.equalsIgnoreCase("gen.nograd")) ret = rb.getString("gen.nograd");
}
return ret;
}
else if (m.getContent().getTypeOfGrade() == Assignment.PASS_FAIL_GRADE_TYPE) {
String ret = rb.getString("ungra");
if (grade != null) {
if (grade.equalsIgnoreCase("Pass")) ret = rb.getString("pass");
else if (grade.equalsIgnoreCase("Fail")) ret = rb.getString("fail");
}
return ret;
}
else if (m.getContent().getTypeOfGrade() == Assignment.CHECK_GRADE_TYPE) {
String ret = rb.getString("ungra");
if (grade != null) {
if (grade.equalsIgnoreCase("Checked")) ret = rb.getString("gen.checked");
}
return ret;
}
else
{
if (grade != null && grade.length() > 0)
{
return StringUtils.trimToEmpty(grade);
}
else
{
// return "ungraded" in stead
return rb.getString("ungra");
}
}
}
/**
* Get the time of last modification;
*
* @return The time of last modification.
*/
public Time getTimeLastModified()
{
return m_timeLastModified;
}
/**
* Text submitted in response to the Assignment.
*
* @return The text of the submission.
*/
public String getSubmittedText()
{
return m_submittedText;
}
/**
* Access the list of attachments to this response to the Assignment.
*
* @return ReferenceVector of the list of attachments as Reference objects;
*/
public List getSubmittedAttachments()
{
return m_submittedAttachments;
}
/**
* Get the general comments by the grader
*
* @return The text of the grader's comments; may be null.
*/
public String getFeedbackComment()
{
return m_feedbackComment;
}
/**
* Access the text part of the instructors feedback; usually an annotated copy of the submittedText
*
* @return The text of the grader's feedback.
*/
public String getFeedbackText()
{
return m_feedbackText;
}
/**
* Access the formatted text part of the instructors feedback; usually an annotated copy of the submittedText
*
* @return The formatted text of the grader's feedback.
*/
public String getFeedbackFormattedText()
{
if (m_feedbackText == null || m_feedbackText.length() == 0)
return m_feedbackText;
String value = fixAssignmentFeedback(m_feedbackText);
StringBuffer buf = new StringBuffer(value);
int pos = -1;
while ((pos = buf.indexOf("{{")) != -1)
{
buf.replace(pos, pos + "{{".length(), "<span class='highlight'>");
}
while ((pos = buf.indexOf("}}")) != -1)
{
buf.replace(pos, pos + "}}".length(), "</span>");
}
return FormattedText.escapeHtmlFormattedText(buf.toString());
}
/**
* Apply the fix to pre 1.1.05 assignments submissions feedback.
*/
private String fixAssignmentFeedback(String value)
{
if (value == null || value.length() == 0) return value;
StringBuffer buf = new StringBuffer(value);
int pos = -1;
// <br/> -> \n
while ((pos = buf.indexOf("<br/>")) != -1)
{
buf.replace(pos, pos + "<br/>".length(), "\n");
}
// <span class='chefAlert'>( -> {{
while ((pos = buf.indexOf("<span class='chefAlert'>(")) != -1)
{
buf.replace(pos, pos + "<span class='chefAlert'>(".length(), "{{");
}
// )</span> -> }}
while ((pos = buf.indexOf(")</span>")) != -1)
{
buf.replace(pos, pos + ")</span>".length(), "}}");
}
while ((pos = buf.indexOf("<ins>")) != -1)
{
buf.replace(pos, pos + "<ins>".length(), "{{");
}
while ((pos = buf.indexOf("</ins>")) != -1)
{
buf.replace(pos, pos + "</ins>".length(), "}}");
}
return buf.toString();
} // fixAssignmentFeedback
/**
* Access the list of attachments returned to the students in the process of grading this assignment; usually a modified or annotated version of the attachment submitted.
*
* @return ReferenceVector of the Resource objects pointing to the attachments.
*/
public List getFeedbackAttachments()
{
return m_feedbackAttachments;
}
/**
* Get whether this Submission was rejected by the grader.
*
* @return True if this response was rejected by the grader, false otherwise.
*/
public boolean getReturned()
{
return m_returned;
}
/**
* Get whether this Submission has been graded.
*
* @return True if the submission has been graded, false otherwise.
*/
public boolean getGraded()
{
return m_graded;
}
/**
* Get the grader id (used to determine auto or instructor grading)
*/
public String getGradedBy(){
return m_gradedBy;
}
/**
* Get the time on which the graded submission was returned; null means the response is not yet graded.
*
* @return the time (may be null)
*/
public Time getTimeReturned()
{
return m_timeReturned;
}
/**
* Access the checked status of the honor pledge flag.
*
* @return True if the honor pledge is checked, false otherwise.
*/
public boolean getHonorPledgeFlag()
{
return m_honorPledgeFlag;
}
/**
* Returns the status of the submission : Not Started, submitted, returned or graded.
*
* @return The Submission's status.
*/
public String getStatus()
{
Assignment assignment = getAssignment();
boolean allowGrade = assignment != null ? allowGradeSubmission(assignment.getReference()):false;
String retVal = "";
Time submitTime = getTimeSubmitted();
Time returnTime = getTimeReturned();
Time lastModTime = getTimeLastModified();
if (getSubmitted() || (!getSubmitted() && allowGrade))
{
if (submitTime != null)
{
if (getReturned())
{
if (returnTime != null && returnTime.before(submitTime))
{
if (!getGraded())
{
retVal = rb.getString("gen.resub") + " " + submitTime.toStringLocalFull();
if (submitTime.after(getAssignment().getDueTime()))
retVal = retVal + rb.getString("gen.late2");
}
else
retVal = rb.getString("gen.returned");
}
else
retVal = rb.getString("gen.returned");
}
else if (getGraded() && allowGrade)
{
retVal = getGradeOrComment();
}
else
{
if (allowGrade)
{
// ungraded submission
retVal = rb.getString("ungra");
}
else
{
// submitted
retVal = rb.getString("gen.subm4");
if(submitTime != null)
{
retVal = rb.getString("gen.subm4") + " " + submitTime.toStringLocalFull();
}
}
}
}
else
{
if (getReturned())
{
// instructor can return grading to non-submitted user
retVal = rb.getString("gen.returned");
}
else if (getGraded() && allowGrade)
{
// instructor can grade non-submitted ones
retVal = getGradeOrComment();
}
else
{
if (allowGrade)
{
// show "no submission" to graders
retVal = rb.getString("listsub.nosub");
}
else
{
// show "not started" to students
retVal = rb.getString("gen.notsta");
}
}
}
}
else
{
if (getGraded())
{
if (getReturned())
{
if (lastModTime != null && returnTime != null && lastModTime.after(TimeService.newTime(returnTime.getTime() + 1000 * 10)) && !allowGrade)
{
// working on a returned submission now
retVal = rb.getString("gen.dra2") + " " + rb.getString("gen.inpro");
}
else
{
// not submitted submmission has been graded and returned
retVal = rb.getString("gen.returned");
}
}
else if (allowGrade){
// grade saved but not release yet, show this to graders
retVal = getGradeOrComment();
}else{
// submission saved, not submitted.
retVal = rb.getString("gen.dra2") + " " + rb.getString("gen.inpro");
}
}
else
{
if (allowGrade)
retVal = rb.getString("ungra");
else
// submission saved, not submitted.
retVal = rb.getString("gen.dra2") + " " + rb.getString("gen.inpro");
}
}
return retVal;
}
private String getGradeOrComment() {
String retVal;
if (getGrade() != null && getGrade().length() > 0)
retVal = rb.getString("grad3");
else
retVal = rb.getString("gen.commented");
return retVal;
}
/**
* Are these objects equal? If they are both AssignmentSubmission objects, and they have matching id's, they are.
*
* @return true if they are equal, false if not.
*/
public boolean equals(Object obj)
{
if (!(obj instanceof AssignmentSubmission)) return false;
return ((AssignmentSubmission) obj).getId().equals(getId());
} // equals
/**
* Make a hash code that reflects the equals() logic as well. We want two objects, even if different instances, if they have the same id to hash the same.
*/
public int hashCode()
{
return getId().hashCode();
} // hashCode
/**
* Compare this object with the specified object for order.
*
* @return A negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
*/
public int compareTo(Object obj)
{
if (!(obj instanceof AssignmentSubmission)) throw new ClassCastException();
// if the object are the same, say so
if (obj == this) return 0;
// start the compare by comparing their sort names
int compare = getTimeSubmitted().toString().compareTo(((AssignmentSubmission) obj).getTimeSubmitted().toString());
// if these are the same
if (compare == 0)
{
// sort based on (unique) id
compare = getId().compareTo(((AssignmentSubmission) obj).getId());
}
return compare;
} // compareTo
/**
* {@inheritDoc}
*/
public int getResubmissionNum()
{
String numString = StringUtils.trimToNull(m_properties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
return numString != null?Integer.valueOf(numString).intValue():0;
}
/**
* {@inheritDoc}
*/
public Time getCloseTime()
{
String closeTimeString = StringUtils.trimToNull(m_properties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME));
if (closeTimeString != null && getResubmissionNum() != 0)
{
// return the close time if it is set
return TimeService.newTime(Long.parseLong(closeTimeString));
}
else
{
// else use the assignment close time setting
Assignment a = getAssignment();
return a!=null?a.getCloseTime():null;
}
}
} // AssignmentSubmission
/***************************************************************************
* AssignmentSubmissionEdit implementation
**************************************************************************/
/**
* <p>
* BaseAssignmentSubmissionEdit is an implementation of the CHEF AssignmentSubmissionEdit object.
* </p>
*
* @author University of Michigan, CHEF Software Development Team
*/
public class BaseAssignmentSubmissionEdit extends BaseAssignmentSubmission implements AssignmentSubmissionEdit,
SessionBindingListener
{
/** The event code for this edit. */
protected String m_event = null;
/** Active flag. */
protected boolean m_active = false;
/**
* Construct from another AssignmentSubmission object.
*
* @param AssignmentSubmission
* The AssignmentSubmission object to use for values.
*/
public BaseAssignmentSubmissionEdit(AssignmentSubmission assignmentSubmission)
{
super(assignmentSubmission);
} // BaseAssignmentSubmissionEdit
/**
* Construct.
*
* @param id
* The AssignmentSubmission id.
*/
public BaseAssignmentSubmissionEdit(String id, String assignmentId, String submitterId, String submitTime, String submitted, String graded)
{
super(id, assignmentId, submitterId, submitTime, submitted, graded);
} // BaseAssignmentSubmissionEdit
/**
* Construct from information in XML.
*
* @param el
* The XML DOM Element definining the AssignmentSubmission.
*/
public BaseAssignmentSubmissionEdit(Element el)
{
super(el);
} // BaseAssignmentSubmissionEdit
/**
* Clean up.
*/
protected void finalize()
{
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelEdit(this);
}
} // finalize
/**
* Set the context at the time of creation.
*
* @param context -
* the context string.
*/
public void setContext(String context)
{
m_context = context;
}
/**
* Set the Assignment for this Submission
*
* @param assignment -
* the Assignment
*/
public void setAssignment(Assignment assignment)
{
if (assignment != null)
{
m_assignment = assignment.getId();
}
else
m_assignment = "";
}
/**
* Set whether this is a final submission.
*
* @param submitted -
* True if a final submission, false if still a draft.
*/
public void setSubmitted(boolean submitted)
{
m_submitted = submitted;
}
/**
* Add a User to the submitters list.
*
* @param submitter -
* the User to add.
*/
public void addSubmitter(User submitter)
{
if (submitter != null) m_submitters.add(submitter.getId());
}
public void setSubmitterId(String id) {
m_submitterId = id;
}
public void addSubmissionLogEntry(String entry) {
if (m_submissionLog != null) m_submissionLog.add(entry);
}
public void addGradeForUser(String uid, String grade) {
if (m_grades != null)
{
Iterator<String> _it = m_grades.iterator();
while (_it.hasNext()) {
String _val = _it.next();
if (_val.startsWith(uid + "::")) {
m_grades.remove(_val);
break;
}
}
if (grade != null && !(grade.equals("null"))) {
m_grades.add(uid + "::" + grade);
}
}
}
/**
* Remove an User from the submitter list
*
* @param submitter -
* the User to remove.
*/
public void removeSubmitter(User submitter)
{
if (submitter != null) m_submitters.remove(submitter.getId());
}
/**
* Remove all user from the submitter list
*/
public void clearSubmitters()
{
m_submitters.clear();
}
/**
* Set the time at which this response was submitted; setting it to null signifies the response is unsubmitted.
*
* @param timeSubmitted -
* Time of submission.
*/
public void setTimeSubmitted(Time value)
{
m_timeSubmitted = value;
}
/**
* Set whether the grade has been released.
*
* @param released -
* True if the Submissions's grade has been released, false otherwise.
*/
public void setGradeReleased(boolean released)
{
m_gradeReleased = released;
}
/**
* Sets the grade for the Submisssion.
*
* @param grade -
* The Submission's grade.
*/
public void setGrade(String grade)
{
m_grade = grade;
}
/**
* Text submitted in response to the Assignment.
*
* @param submissionText -
* The text of the submission.
*/
public void setSubmittedText(String value)
{
m_submittedText = value;
}
/**
* Add an attachment to the list of submitted attachments.
*
* @param attachment -
* The Reference object pointing to the attachment.
*/
public void addSubmittedAttachment(Reference attachment)
{
if (attachment != null) m_submittedAttachments.add(attachment);
}
/**
* Remove an attachment from the list of submitted attachments
*
* @param attachment -
* The Reference object pointing to the attachment.
*/
public void removeSubmittedAttachment(Reference attachment)
{
if (attachment != null) m_submittedAttachments.remove(attachment);
}
/**
* Remove all submitted attachments.
*/
public void clearSubmittedAttachments()
{
m_submittedAttachments.clear();
}
/**
* Set the general comments by the grader.
*
* @param comment -
* the text of the grader's comments; may be null.
*/
public void setFeedbackComment(String value)
{
m_feedbackComment = value;
}
/**
* Set the text part of the instructors feedback; usually an annotated copy of the submittedText
*
* @param feedback -
* The text of the grader's feedback.
*/
public void setFeedbackText(String value)
{
m_feedbackText = value;
}
/**
* Add an attachment to the list of feedback attachments.
*
* @param attachment -
* The Resource object pointing to the attachment.
*/
public void addFeedbackAttachment(Reference attachment)
{
if (attachment != null) m_feedbackAttachments.add(attachment);
}
/**
* Remove an attachment from the list of feedback attachments.
*
* @param attachment -
* The Resource pointing to the attachment to remove.
*/
public void removeFeedbackAttachment(Reference attachment)
{
if (attachment != null) m_feedbackAttachments.remove(attachment);
}
/**
* Remove all feedback attachments.
*/
public void clearFeedbackAttachments()
{
m_feedbackAttachments.clear();
}
/**
* Set whether this Submission was rejected by the grader.
*
* @param returned -
* true if this response was rejected by the grader, false otherwise.
*/
public void setReturned(boolean value)
{
m_returned = value;
}
/**
* Set whether this Submission has been graded.
*
* @param graded -
* true if the submission has been graded, false otherwise.
*/
public void setGraded(boolean value)
{
m_graded = value;
}
/**
* set the grader id (used to distinguish between auto and instructor grading)
*/
public void setGradedBy(String gradedBy){
m_gradedBy = gradedBy;
}
/**
* Set the time at which the graded Submission was returned; setting it to null means it is not yet graded.
*
* @param timeReturned -
* The time at which the graded Submission was returned.
*/
public void setTimeReturned(Time timeReturned)
{
m_timeReturned = timeReturned;
}
/**
* Set the checked status of the honor pledge flag.
*
* @param honorPledgeFlag -
* True if the honor pledge is checked, false otherwise.
*/
public void setHonorPledgeFlag(boolean honorPledgeFlag)
{
m_honorPledgeFlag = honorPledgeFlag;
}
/**
* Set the time last modified.
*
* @param lastmod -
* The Time at which the Assignment was last modified.
*/
public void setTimeLastModified(Time lastmod)
{
if (lastmod != null) m_timeLastModified = lastmod;
}
public void postAttachment(List attachments){
//Send the attachment to the review service
try {
ContentResource cr = getFirstAcceptableAttachement(attachments);
Assignment ass = this.getAssignment();
if (ass != null && cr != null)
{
contentReviewService.queueContent(null, null, ass.getReference(), cr.getId());
}
else
{
// error, assignment couldn't be found. Log the error
M_log.debug(this + " BaseAssignmentSubmissionEdit postAttachment: Unable to find assignment associated with submission id= " + this.m_id + " and assignment id=" + this.m_assignment);
}
} catch (QueueException qe) {
M_log.warn(" BaseAssignmentSubmissionEdit postAttachment: Unable to add content to Content Review queue: " + qe.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
private ContentResource getFirstAcceptableAttachement(List attachments) {
for( int i =0; i < attachments.size();i++ ) {
Reference attachment = (Reference)attachments.get(i);
try {
ContentResource res = m_contentHostingService.getResource(attachment.getId());
if (contentReviewService.isAcceptableContent(res)) {
return res;
}
} catch (PermissionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
M_log.warn(":geFirstAcceptableAttachment " + e.getMessage());
} catch (IdUnusedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
M_log.warn(":geFirstAcceptableAttachment " + e.getMessage());
} catch (TypeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
M_log.warn(":geFirstAcceptableAttachment " + e.getMessage());
}
}
return null;
}
/**
* Take all values from this object.
*
* @param AssignmentSubmission
* The AssignmentSubmission object to take values from.
*/
protected void set(AssignmentSubmission assignmentSubmission)
{
setAll(assignmentSubmission);
} // set
/**
* Access the event code for this edit.
*
* @return The event code for this edit.
*/
protected String getEvent()
{
return m_event;
}
/**
* Set the event code for this edit.
*
* @param event
* The event code for this edit.
*/
protected void setEvent(String event)
{
m_event = event;
}
/**
* Access the resource's properties for modification
*
* @return The resource's properties.
*/
public ResourcePropertiesEdit getPropertiesEdit()
{
return m_properties;
} // getPropertiesEdit
/**
* Enable editing.
*/
protected void activate()
{
m_active = true;
} // activate
/**
* Check to see if the edit is still active, or has already been closed.
*
* @return true if the edit is active, false if it's been closed.
*/
public boolean isActiveEdit()
{
return m_active;
} // isActiveEdit
/**
* Close the edit object - it cannot be used after this.
*/
protected void closeEdit()
{
m_active = false;
} // closeEdit
/******************************************************************************************************************************************************************************************************************************************************
* SessionBindingListener implementation
*****************************************************************************************************************************************************************************************************************************************************/
public void valueBound(SessionBindingEvent event)
{
}
public void valueUnbound(SessionBindingEvent event)
{
M_log.debug(this + " BaseAssignmentSubmissionEdit valueUnbound()");
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelEdit(this);
}
} // valueUnbound
public void setReviewScore(int score) {
this.m_reviewScore = score;
}
public void setReviewIconUrl(String url) {
this.m_reviewIconUrl = url;
}
public void setReviewStatus(String status) {
this.m_reviewStatus = status;
}
public void setReviewError(String error) {
this.m_reviewError = error;
}
} // BaseAssignmentSubmissionEdit
/**********************************************************************************************************************************************************************************************************************************************************
* Assignment Storage
*********************************************************************************************************************************************************************************************************************************************************/
protected interface AssignmentStorage
{
/**
* Open.
*/
public void open();
/**
* Close.
*/
public void close();
/**
* Check if an Assignment by this id exists.
*
* @param id
* The assignment id.
* @return true if an Assignment by this id exists, false if not.
*/
public boolean check(String id);
/**
* Get the Assignment with this id, or null if not found.
*
* @param id
* The Assignment id.
* @return The Assignment with this id, or null if not found.
*/
public Assignment get(String id);
/**
* Get all Assignments.
*
* @return The list of all Assignments.
*/
public List getAll(String context);
/**
* Add a new Assignment with this id.
*
* @param id
* The Assignment id.
* @param context
* The context.
* @return The locked Assignment object with this id, or null if the id is in use.
*/
public AssignmentEdit put(String id, String context);
/**
* Get a lock on the Assignment with this id, or null if a lock cannot be gotten.
*
* @param id
* The Assignment id.
* @return The locked Assignment with this id, or null if this records cannot be locked.
*/
public AssignmentEdit edit(String id);
/**
* Commit the changes and release the lock.
*
* @param Assignment
* The Assignment to commit.
*/
public void commit(AssignmentEdit assignment);
/**
* Cancel the changes and release the lock.
*
* @param Assignment
* The Assignment to commit.
*/
public void cancel(AssignmentEdit assignment);
/**
* Remove this Assignment.
*
* @param Assignment
* The Assignment to remove.
*/
public void remove(AssignmentEdit assignment);
} // AssignmentStorage
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentContent Storage
*********************************************************************************************************************************************************************************************************************************************************/
protected interface AssignmentContentStorage
{
/**
* Open.
*/
public void open();
/**
* Close.
*/
public void close();
/**
* Check if a AssignmentContent by this id exists.
*
* @param id
* The AssignmentContent id.
* @return true if a AssignmentContent by this id exists, false if not.
*/
public boolean check(String id);
/**
* Get the AssignmentContent with this id, or null if not found.
*
* @param id
* The AssignmentContent id.
* @return The AssignmentContent with this id, or null if not found.
*/
public AssignmentContent get(String id);
/**
* Get all AssignmentContents.
*
* @return The list of all AssignmentContents.
*/
public List getAll(String context);
/**
* Add a new AssignmentContent with this id.
*
* @param id
* The AssignmentContent id.
* @param context
* The context.
* @return The locked AssignmentContent object with this id, or null if the id is in use.
*/
public AssignmentContentEdit put(String id, String context);
/**
* Get a lock on the AssignmentContent with this id, or null if a lock cannot be gotten.
*
* @param id
* The AssignmentContent id.
* @return The locked AssignmentContent with this id, or null if this records cannot be locked.
*/
public AssignmentContentEdit edit(String id);
/**
* Commit the changes and release the lock.
*
* @param AssignmentContent
* The AssignmentContent to commit.
*/
public void commit(AssignmentContentEdit content);
/**
* Cancel the changes and release the lock.
*
* @param AssignmentContent
* The AssignmentContent to commit.
*/
public void cancel(AssignmentContentEdit content);
/**
* Remove this AssignmentContent.
*
* @param AssignmentContent
* The AssignmentContent to remove.
*/
public void remove(AssignmentContentEdit content);
} // AssignmentContentStorage
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentSubmission Storage
*********************************************************************************************************************************************************************************************************************************************************/
protected interface AssignmentSubmissionStorage
{
/**
* Open.
*/
public void open();
/**
* Close.
*/
public void close();
/**
* Check if a AssignmentSubmission by this id exists.
*
* @param id
* The AssignmentSubmission id.
* @return true if a AssignmentSubmission by this id exists, false if not.
*/
public boolean check(String id);
/**
* Get the AssignmentSubmission with this id, or null if not found.
*
* @param id
* The AssignmentSubmission id.
* @return The AssignmentSubmission with this id, or null if not found.
*/
public AssignmentSubmission get(String id);
/**
* Get the AssignmentSubmission with this assignment id and user id.
*
* @param assignmentId
* The Assignment id.
* @param userId
* The user id
* @return The AssignmentSubmission with this id, or null if not found.
*/
public AssignmentSubmission get(String assignmentId, String userId);
/**
* Get the number of submissions which has been submitted.
*
* @param assignmentId -
* the id of Assignment who's submissions you would like.
* @return List over all the submissions for an Assignment.
*/
public int getSubmittedSubmissionsCount(String assignmentId);
/**
* Get the number of submissions which has not been submitted and graded.
*
* @param assignment -
* the Assignment who's submissions you would like.
* @return List over all the submissions for an Assignment.
*/
public int getUngradedSubmissionsCount(String assignmentId);
/**
* Get all AssignmentSubmissions.
*
* @return The list of all AssignmentSubmissions.
*/
public List getAll(String context);
/**
* Add a new AssignmentSubmission with this id.
*
* @param id
* The AssignmentSubmission id.
* @param context
* The context.
* @return The locked AssignmentSubmission object with this id, or null if the id is in use.
*/
public AssignmentSubmissionEdit put(String id, String assignmentId, String submitterId, String submitTime, String submitted, String graded);
/**
* Get a lock on the AssignmentSubmission with this id, or null if a lock cannot be gotten.
*
* @param id
* The AssignmentSubmission id.
* @return The locked AssignmentSubmission with this id, or null if this records cannot be locked.
*/
public AssignmentSubmissionEdit edit(String id);
/**
* Commit the changes and release the lock.
*
* @param AssignmentSubmission
* The AssignmentSubmission to commit.
*/
public void commit(AssignmentSubmissionEdit submission);
/**
* Cancel the changes and release the lock.
*
* @param AssignmentSubmission
* The AssignmentSubmission to commit.
*/
public void cancel(AssignmentSubmissionEdit submission);
/**
* Remove this AssignmentSubmission.
*
* @param AssignmentSubmission
* The AssignmentSubmission to remove.
*/
public void remove(AssignmentSubmissionEdit submission);
} // AssignmentSubmissionStorage
/**
* Utility function which returns the string representation of the long value of the time object.
*
* @param t -
* the Time object.
* @return A String representation of the long value of the time object.
*/
protected String getTimeString(Time t)
{
String retVal = "";
if (t != null) retVal = t.toString();
return retVal;
}
/**
* Utility function which returns a string from a boolean value.
*
* @param b -
* the boolean value.
* @return - "True" if the input value is true, "false" otherwise.
*/
protected String getBoolString(boolean b)
{
if (b)
return "true";
else
return "false";
}
/**
* Utility function which returns a boolean value from a string.
*
* @param s -
* The input string.
* @return the boolean true if the input string is "true", false otherwise.
*/
protected boolean getBool(String s)
{
boolean retVal = false;
if (s != null)
{
if (s.equalsIgnoreCase("true")) retVal = true;
}
return retVal;
}
/**
* Utility function which converts a string into a chef time object.
*
* @param timeString -
* String version of a time in long format, representing the standard ms since the epoch, Jan 1, 1970 00:00:00.
* @return A chef Time object.
*/
protected Time getTimeObject(String timeString)
{
Time aTime = null;
timeString = StringUtils.trimToNull(timeString);
if (timeString != null)
{
try
{
aTime = TimeService.newTimeGmt(timeString);
}
catch (Exception e)
{
M_log.warn(":geTimeObject " + e.getMessage());
try
{
long longTime = Long.parseLong(timeString);
aTime = TimeService.newTime(longTime);
}
catch (Exception ee)
{
M_log.warn(" getTimeObject Base Exception creating time object from xml file : " + ee.getMessage() + " timeString=" + timeString);
}
}
}
return aTime;
}
protected String getGroupNameFromContext(String context)
{
String retVal = "";
if (context != null)
{
int index = context.indexOf("group-");
if (index != -1)
{
String[] parts = StringUtil.splitFirst(context, "-");
if (parts.length > 1)
{
retVal = parts[1];
}
}
else
{
retVal = context;
}
}
return retVal;
}
/**********************************************************************************************************************************************************************************************************************************************************
* StorageUser implementations (no container)
*********************************************************************************************************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentStorageUser implementation
*********************************************************************************************************************************************************************************************************************************************************/
protected class AssignmentStorageUser implements SingleStorageUser, SAXEntityReader
{
private Map<String,Object> m_services;
/**
* Construct a new resource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Entity newResource(Entity container, String id, Object[] others)
{
return new BaseAssignment(id, (String) others[0]);
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Entity newResource(Entity container, Element element)
{
return new BaseAssignment(element);
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Entity newResource(Entity container, Entity other)
{
return new BaseAssignment((Assignment) other);
}
/**
* Construct a new resource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Edit newResourceEdit(Entity container, String id, Object[] others)
{
BaseAssignmentEdit e = new BaseAssignmentEdit(id, (String) others[0]);
e.activate();
return e;
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Edit newResourceEdit(Entity container, Element element)
{
BaseAssignmentEdit e = new BaseAssignmentEdit(element);
e.activate();
return e;
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Edit newResourceEdit(Entity container, Entity other)
{
BaseAssignmentEdit e = new BaseAssignmentEdit((Assignment) other);
e.activate();
return e;
}
/**
* Collect the fields that need to be stored outside the XML (for the resource).
*
* @return An array of field values to store in the record outside the XML (for the resource).
*/
public Object[] storageFields(Entity r)
{
Object rv[] = new Object[1];
rv[0] = ((Assignment) r).getContext();
return rv;
}
/***********************************************************************
* SAXEntityReader
*/
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.SAXEntityReader#getDefaultHandler(java.util.Map)
*/
public DefaultEntityHandler getDefaultHandler(final Map<String, Object> services)
{
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String,
* org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if (entity == null)
{
if ("assignment".equals(qName))
{
BaseAssignment ba = new BaseAssignment();
entity = ba;
setContentHandler(ba.getContentHandler(services), uri,
localName, qName, attributes);
}
else
{
M_log.warn(" AssignmentStorageUser getDefaultHandler startElement Unexpected Element in XML [" + qName + "]");
}
}
}
}
};
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.SAXEntityReader#getServices()
*/
public Map<String, Object> getServices()
{
if (m_services == null)
{
m_services = new HashMap<String, Object>();
}
return m_services;
}
}// AssignmentStorageUser
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentContentStorageUser implementation
*********************************************************************************************************************************************************************************************************************************************************/
protected class AssignmentContentStorageUser implements SingleStorageUser, SAXEntityReader
{
private Map<String,Object> m_services;
/**
* Construct a new resource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Entity newResource(Entity container, String id, Object[] others)
{
return new BaseAssignmentContent(id, (String) others[0]);
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Entity newResource(Entity container, Element element)
{
return new BaseAssignmentContent(element);
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Entity newResource(Entity container, Entity other)
{
return new BaseAssignmentContent((AssignmentContent) other);
}
/**
* Construct a new rsource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Edit newResourceEdit(Entity container, String id, Object[] others)
{
BaseAssignmentContentEdit e = new BaseAssignmentContentEdit(id, (String) others[0]);
e.activate();
return e;
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Edit newResourceEdit(Entity container, Element element)
{
BaseAssignmentContentEdit e = new BaseAssignmentContentEdit(element);
e.activate();
return e;
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Edit newResourceEdit(Entity container, Entity other)
{
BaseAssignmentContentEdit e = new BaseAssignmentContentEdit((AssignmentContent) other);
e.activate();
return e;
}
/**
* Collect the fields that need to be stored outside the XML (for the resource).
*
* @return An array of field values to store in the record outside the XML (for the resource).
*/
public Object[] storageFields(Entity r)
{
Object rv[] = new Object[1];
rv[0] = ((AssignmentContent) r).getCreator();
return rv;
}
/***********************************************************************
* SAXEntityReader
*/
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.SAXEntityReader#getDefaultHandler(java.util.Map)
*/
public DefaultEntityHandler getDefaultHandler(final Map<String, Object> services)
{
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String,
* org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if (entity == null)
{
if ("content".equals(qName))
{
BaseAssignmentContent bac = new BaseAssignmentContent();
entity = bac;
setContentHandler(bac.getContentHandler(services), uri,
localName, qName, attributes);
}
else
{
M_log.warn(" AssignmentContentStorageUser getDefaultEntityHandler startElement Unexpected Element in XML [" + qName + "]");
}
}
}
}
};
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.SAXEntityReader#getServices()
*/
public Map<String, Object> getServices()
{
if (m_services == null)
{
m_services = new HashMap<String, Object>();
}
return m_services;
}
}// ContentStorageUser
/**********************************************************************************************************************************************************************************************************************************************************
* SubmissionStorageUser implementation
*********************************************************************************************************************************************************************************************************************************************************/
protected class AssignmentSubmissionStorageUser implements SingleStorageUser, SAXEntityReader
{
private Map<String,Object> m_services;
/**
* Construct a new resource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Entity newResource(Entity container, String id, Object[] others)
{
return new BaseAssignmentSubmission(id, (String) others[0], (String) others[1], (String) others[2], (String) others[3], (String) others[4]);
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Entity newResource(Entity container, Element element)
{
return new BaseAssignmentSubmission(element);
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Entity newResource(Entity container, Entity other)
{
return new BaseAssignmentSubmission((AssignmentSubmission) other);
}
/**
* Construct a new rsource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Edit newResourceEdit(Entity container, String id, Object[] others)
{
BaseAssignmentSubmissionEdit e = new BaseAssignmentSubmissionEdit(id, (String) others[0], (String) others[1], (String) others[2], (String) others[3], (String) others[4]);
e.activate();
return e;
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Edit newResourceEdit(Entity container, Element element)
{
BaseAssignmentSubmissionEdit e = new BaseAssignmentSubmissionEdit(element);
e.activate();
return e;
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Edit newResourceEdit(Entity container, Entity other)
{
BaseAssignmentSubmissionEdit e = new BaseAssignmentSubmissionEdit((AssignmentSubmission) other);
e.activate();
return e;
}
/**
* Collect the fields that need to be stored outside the XML (for the resource).
*
* @return An array of field values to store in the record outside the XML (for the resource).
*/
public Object[] storageFields(Entity r)
{
/*"context", "SUBMITTER_ID", "SUBMIT_TIME", "SUBMITTED", "GRADED"*/
Object rv[] = new Object[5];
rv[0] = ((AssignmentSubmission) r).getAssignmentId();
rv[1] = ((AssignmentSubmission) r).getSubmitterId();
Time submitTime = ((AssignmentSubmission) r).getTimeSubmitted();
rv[2] = (submitTime != null)?String.valueOf(submitTime.getTime()):null;
rv[3] = Boolean.valueOf(((AssignmentSubmission) r).getSubmitted()).toString();
rv[4] = Boolean.valueOf(((AssignmentSubmission) r).getGraded()).toString();
return rv;
}
/***********************************************************************
* SAXEntityReader
*/
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.SAXEntityReader#getDefaultHandler(java.util.Map)
*/
public DefaultEntityHandler getDefaultHandler(final Map<String, Object> services)
{
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String,
* org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if (entity == null)
{
if ("submission".equals(qName))
{
BaseAssignmentSubmission bas = new BaseAssignmentSubmission();
entity = bas;
setContentHandler(bas.getContentHandler(services), uri,
localName, qName, attributes);
}
else
{
M_log.warn(" AssignmentSubmissionStorageUser getDefaultHandler startElement: Unexpected Element in XML [" + qName + "]");
}
}
}
}
};
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.SAXEntityReader#getServices()
*/
public Map<String, Object> getServices()
{
if (m_services == null)
{
m_services = new HashMap<String, Object>();
}
return m_services;
}
}// SubmissionStorageUser
/**********************************************************************************************************************************************************************************************************************************************************
* CacheRefresher implementations (no container)
*********************************************************************************************************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentCacheRefresher implementation
*********************************************************************************************************************************************************************************************************************************************************/
protected class AssignmentCacheRefresher implements CacheRefresher
{
/**
* Get a new value for this key whose value has already expired in the cache.
*
* @param key
* The key whose value has expired and needs to be refreshed.
* @param oldValue
* The old expired value of the key.
* @return a new value for use in the cache for this key; if null, the entry will be removed.
*/
public Object refresh(Object key, Object oldValue, Event event)
{
// key is a reference, but our storage wants an id
String id = assignmentId((String) key);
// get whatever we have from storage for the cache for this vale
Assignment assignment = m_assignmentStorage.get(id);
M_log.debug(this + " AssignmentCacheRefresher:refresh(): " + key + " : " + id);
return assignment;
} // refresh
}// AssignmentCacheRefresher
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentContentCacheRefresher implementation
*********************************************************************************************************************************************************************************************************************************************************/
protected class AssignmentContentCacheRefresher implements CacheRefresher
{
/**
* Get a new value for this key whose value has already expired in the cache.
*
* @param key
* The key whose value has expired and needs to be refreshed.
* @param oldValue
* The old expired value of the key.
* @return a new value for use in the cache for this key; if null, the entry will be removed.
*/
public Object refresh(Object key, Object oldValue, Event event)
{
// key is a reference, but our storage wants an id
String id = contentId((String) key);
// get whatever we have from storage for the cache for this vale
AssignmentContent content = m_contentStorage.get(id);
M_log.debug(this + " AssignmentContentCacheRefresher: refresh(): " + key + " : " + id);
return content;
} // refresh
}// AssignmentContentCacheRefresher
/**********************************************************************************************************************************************************************************************************************************************************
* AssignmentSubmissionCacheRefresher implementation
*********************************************************************************************************************************************************************************************************************************************************/
protected class AssignmentSubmissionCacheRefresher implements CacheRefresher
{
/**
* Get a new value for this key whose value has already expired in the cache.
*
* @param key
* The key whose value has expired and needs to be refreshed.
* @param oldValue
* The old expired value of the key.
* @return a new value for use in the cache for this key; if null, the entry will be removed.
*/
public Object refresh(Object key, Object oldValue, Event event)
{
// key is a reference, but our storage wants an id
String id = submissionId((String) key);
// get whatever we have from storage for the cache for this vale
AssignmentSubmission submission = m_submissionStorage.get(id);
M_log.debug(this + " AssignmentSubmissionCacheRefresher:refresh(): " + key + " : " + id);
return submission;
} // refresh
}// AssignmentSubmissionCacheRefresher
private class UserComparator implements Comparator
{
public UserComparator() {}
public int compare(Object o1, Object o2) {
User _u1 = (User)o1;
User _u2 = (User)o2;
return _u1.compareTo(_u2);
}
}
/**
* the AssignmentComparator clas
*/
static private class AssignmentComparator implements Comparator
{
/**
* the criteria
*/
String m_criteria = null;
/**
* the criteria
*/
String m_asc = null;
/**
* is group submission
*/
boolean m_group_submission = false;
/**
* constructor
* @param criteria
* The sort criteria string
* @param asc
* The sort order string. TRUE_STRING if ascending; "false" otherwise.
*/
public AssignmentComparator(String criteria, String asc)
{
m_criteria = criteria;
m_asc = asc;
} // constructor
public AssignmentComparator(String criteria, String asc, boolean group)
{
m_criteria = criteria;
m_asc = asc;
m_group_submission = group;
}
/**
* implementing the compare function
*
* @param o1
* The first object
* @param o2
* The second object
* @return The compare result. 1 is o1 < o2; -1 otherwise
*/
public int compare(Object o1, Object o2)
{
int result = -1;
/************** for sorting submissions ********************/
if ("submitterName".equals(m_criteria))
{
String name1 = getSubmitterSortname(o1);
String name2 = getSubmitterSortname(o2);
result = name1.compareTo(name2);
}
/** *********** for sorting assignments ****************** */
else if ("duedate".equals(m_criteria))
{
// sorted by the assignment due date
Time t1 = ((Assignment) o1).getDueTime();
Time t2 = ((Assignment) o2).getDueTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if ("sortname".equals(m_criteria))
{
// sorted by the user's display name
String s1 = null;
String userId1 = (String) o1;
if (userId1 != null)
{
try
{
User u1 = UserDirectoryService.getUser(userId1);
s1 = u1!=null?u1.getSortName():null;
}
catch (Exception e)
{
M_log.warn(" AssignmentComparator.compare " + e.getMessage() + " id=" + userId1);
}
}
String s2 = null;
String userId2 = (String) o2;
if (userId2 != null)
{
try
{
User u2 = UserDirectoryService.getUser(userId2);
s2 = u2!=null?u2.getSortName():null;
}
catch (Exception e)
{
M_log.warn(" AssignmentComparator.compare " + e.getMessage() + " id=" + userId2);
}
}
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
result = s1.compareTo(s2);
}
}
// sort ascending or descending
if (m_asc.equals(Boolean.FALSE.toString()))
{
result = -result;
}
return result;
}
/**
* get the submitter sortname String for the AssignmentSubmission object
* @param o2
* @return
*/
private String getSubmitterSortname(Object o2) {
String rv = "";
if (o2 instanceof AssignmentSubmission)
{
// get Assignment
AssignmentSubmission _submission =(AssignmentSubmission) o2;
if (_submission.getAssignment().isGroup()) {
// get the Group
try {
Site _site = SiteService.getSite( _submission.getAssignment().getContext() );
rv = _site.getGroup(_submission.getSubmitterId()).getTitle();
} catch (Throwable _dfd) { }
} else {
User[] users2 = ((AssignmentSubmission) o2).getSubmitters();
if (users2 != null)
{
StringBuffer users2Buffer = new StringBuffer();
for (int i = 0; i < users2.length; i++)
{
users2Buffer.append(users2[i].getSortName() + " ");
}
rv = users2Buffer.toString();
}
}
}
return rv;
}
}
/**
* {@inheritDoc}
*/
public void updateEntityReferences(String toContext, Map<String, String> transversalMap){
if(transversalMap != null && transversalMap.size() > 0){
Set<Entry<String, String>> entrySet = (Set<Entry<String, String>>) transversalMap.entrySet();
String toSiteId = toContext;
Iterator assignmentsIter = getAssignmentsForContext(toSiteId);
while (assignmentsIter.hasNext())
{
Assignment assignment = (Assignment) assignmentsIter.next();
String assignmentId = assignment.getId();
try
{
String msgBody = assignment.getContent().getInstructions();
StringBuffer msgBodyPreMigrate = new StringBuffer(msgBody);
msgBody = LinkMigrationHelper.migrateAllLinks(entrySet, msgBody);
SecurityAdvisor securityAdvisor = new MySecurityAdvisor(SessionManager.getCurrentSessionUserId(),
new ArrayList<String>(Arrays.asList(SECURE_UPDATE_ASSIGNMENT_CONTENT)),
assignment.getContentReference());
try
{
if(!msgBody.equals(msgBodyPreMigrate.toString())){
// add permission to update assignment content
securityService.pushAdvisor(securityAdvisor);
AssignmentContentEdit cEdit = editAssignmentContent(assignment.getContentReference());
cEdit.setInstructions(msgBody);
commitEdit(cEdit);
}
}
catch (Exception e)
{
// exception
M_log.warn("UpdateEntityReference: cannot get assignment content for " + assignment.getId() + e.getMessage());
}
finally
{
// remove advisor
securityService.popAdvisor(securityAdvisor);
}
}
catch(Exception ee)
{
M_log.warn("UpdateEntityReference: remove Assignment and all references for " + assignment.getId() + ee.getMessage());
}
}
}
}
public void transferCopyEntities(String fromContext, String toContext, List ids, boolean cleanup){
transferCopyEntitiesRefMigrator(fromContext, toContext, ids, cleanup);
}
public Map<String, String> transferCopyEntitiesRefMigrator(String fromContext, String toContext, List ids, boolean cleanup)
{
Map<String, String> transversalMap = new HashMap<String, String>();
try
{
if(cleanup == true)
{
String toSiteId = toContext;
Iterator assignmentsIter = getAssignmentsForContext(toSiteId);
while (assignmentsIter.hasNext())
{
Assignment assignment = (Assignment) assignmentsIter.next();
String assignmentId = assignment.getId();
SecurityAdvisor securityAdvisor = new MySecurityAdvisor(SessionManager.getCurrentSessionUserId(),
new ArrayList<String>(Arrays.asList(SECURE_UPDATE_ASSIGNMENT, SECURE_REMOVE_ASSIGNMENT)),
assignmentId);
try
{
// advisor to allow edit and remove assignment
securityService.pushAdvisor(securityAdvisor);
AssignmentEdit aEdit = editAssignment(assignmentId);
// remove this assignment with all its associated items
removeAssignmentAndAllReferences(aEdit);
}
catch(Exception ee)
{
M_log.warn(":transferCopyEntities: remove Assignment and all references for " + assignment.getId() + ee.getMessage());
}
finally
{
// remove SecurityAdvisor
securityService.popAdvisor(securityAdvisor);
}
}
}
transversalMap.putAll(transferCopyEntitiesRefMigrator(fromContext, toContext, ids));
}
catch (Exception e)
{
M_log.info(this + "transferCopyEntities: End removing Assignmentt data" + e.getMessage());
}
return transversalMap;
}
/**
* This is to mimic the FormattedText.decodeFormattedTextAttribute but use SAX serialization instead
* @return
*/
protected String formattedTextDecodeFormattedTextAttribute(Attributes attributes, String baseAttributeName)
{
String ret;
// first check if an HTML-encoded attribute exists, for example "foo-html", and use it if available
ret = StringUtils.trimToNull(xmlDecodeAttribute(attributes, baseAttributeName + "-html"));
if (ret != null) return ret;
// next try the older kind of formatted text like "foo-formatted", and convert it if found
ret = StringUtils.trimToNull(xmlDecodeAttribute(attributes, baseAttributeName + "-formatted"));
ret = FormattedText.convertOldFormattedText(ret);
if (ret != null) return ret;
// next try just a plaintext attribute and convert the plaintext to formatted text if found
// convert from old plaintext instructions to new formatted text instruction
ret = xmlDecodeAttribute(attributes, baseAttributeName);
ret = FormattedText.convertPlaintextToFormattedText(ret);
return ret;
}
/**
* this is to mimic the Xml.decodeAttribute
* @param el
* @param tag
* @return
*/
protected String xmlDecodeAttribute(Attributes attributes, String tag)
{
String charset = StringUtils.trimToNull(attributes.getValue("charset"));
if (charset == null) charset = "UTF-8";
String body = StringUtils.trimToNull(attributes.getValue(tag));
if (body != null)
{
try {
byte[] decoded = Base64.decodeBase64(body); // UTF-8 by default
body = org.apache.commons.codec.binary.StringUtils.newString(decoded, charset);
} catch (IllegalStateException e) {
M_log.warn(" XmlDecodeAttribute: " + e.getMessage() + " tag=" + tag);
}
}
if (body == null) body = "";
return body;
}
/**
* construct the right path for context string, used for permission checkings
* @param context
* @return
*/
public static String getContextReference(String context)
{
String resourceString = getAccessPoint(true) + Entity.SEPARATOR + "a" + Entity.SEPARATOR + context + Entity.SEPARATOR;
return resourceString;
}
/**
* the GroupSubmission clas
*/
public class GroupSubmission
{
/**
* the Group object
*/
Group m_group = null;
/**
* the AssignmentSubmission object
*/
AssignmentSubmission m_submission = null;
public GroupSubmission(Group g, AssignmentSubmission s)
{
m_group = g;
m_submission = s;
}
/**
* Returns the AssignmentSubmission object
*/
public AssignmentSubmission getSubmission()
{
return m_submission;
}
public Group getGroup()
{
return m_group;
}
}
private LRS_Statement getStatementForAssignmentGraded(LRS_Actor instructor, Event event, Assignment a, AssignmentSubmission s,
User studentUser) {
LRS_Verb verb = new LRS_Verb(SAKAI_VERB.scored);
LRS_Object lrsObject = new LRS_Object(m_serverConfigurationService.getPortalUrl() + event.getResource(),
"received-grade-assignment");
HashMap<String, String> nameMap = new HashMap<String, String>();
nameMap.put("en-US", "User received a grade");
lrsObject.setActivityName(nameMap);
HashMap<String, String> descMap = new HashMap<String, String>();
descMap.put("en-US", "User received a grade for their assginment: " + a.getTitle() + "; Submission #: " + s.getResubmissionNum());
lrsObject.setDescription(descMap);
LRS_Actor student = new LRS_Actor(studentUser.getEmail());
student.setName(studentUser.getDisplayName());
LRS_Context context = new LRS_Context(instructor);
context.setActivity("other", "assignment");
LRS_Statement statement = new LRS_Statement(student, verb, lrsObject, getLRS_Result(a, s, true), context);
return statement;
}
private LRS_Result getLRS_Result(Assignment a, AssignmentSubmission s, boolean completed) {
LRS_Result result = null;
AssignmentContent content = a.getContent();
if (3 == content.getTypeOfGrade() && NumberUtils.isNumber(s.getGradeDisplay())) { // Points
result = new LRS_Result(new Float(s.getGradeDisplay()), new Float(0.0), new Float(content.getMaxGradePointDisplay()), null);
result.setCompletion(completed);
} else {
result = new LRS_Result(completed);
result.setGrade(s.getGradeDisplay());
}
return result;
}
private LRS_Statement getStatementForUnsubmittedAssignmentGraded(LRS_Actor instructor, Event event, Assignment a,
AssignmentSubmission s, User studentUser) {
LRS_Verb verb = new LRS_Verb(SAKAI_VERB.scored);
LRS_Object lrsObject = new LRS_Object(m_serverConfigurationService.getAccessUrl() + event.getResource(), "received-grade-unsubmitted-assignment");
HashMap<String, String> nameMap = new HashMap<String, String>();
nameMap.put("en-US", "User received a grade");
lrsObject.setActivityName(nameMap);
HashMap<String, String> descMap = new HashMap<String, String>();
descMap.put("en-US", "User received a grade for an unsubmitted assginment: " + a.getTitle());
lrsObject.setDescription(descMap);
LRS_Actor student = new LRS_Actor(studentUser.getEmail());
student.setName(studentUser.getDisplayName());
LRS_Context context = new LRS_Context(instructor);
context.setActivity("other", "assignment");
LRS_Statement statement = new LRS_Statement(student, verb, lrsObject, getLRS_Result(a, s, false), context);
return statement;
}
} // BaseAssignmentService
|
SAK-26058 removing the unused CacheRefresher code
git-svn-id: d213257099f21e50eb3b4c197ffbeb2264dc0174@307901 66ffb92e-73f9-0310-93c1-f5514f145a0a
|
assignment/assignment-impl/impl/src/java/org/sakaiproject/assignment/impl/BaseAssignmentService.java
|
SAK-26058 removing the unused CacheRefresher code
|
|
Java
|
apache-2.0
|
f18065b9f231a3fc4941efc39516f7d0187032d7
| 0
|
RichRelevance/StashPRTriggerPlugin
|
package com.richrelevance.stash.plugin.settings;
import javax.annotation.Nonnull;
public final class ImmutablePullRequestTriggerSettings implements PullRequestTriggerSettings{
private final boolean enabled;
private final @Nonnull String url;
private final @Nonnull String user;
private final @Nonnull String password;
public ImmutablePullRequestTriggerSettings() {
this.enabled = false;
this.url = "http://localhost/bamboo";
this.user = "user";
this.password = "password";
}
public ImmutablePullRequestTriggerSettings(boolean enabled, @Nonnull String url, @Nonnull String user,
@Nonnull String password) {
this.enabled = enabled;
this.url = url;
this.user = user;
this.password = password;
}
@Override
public boolean isEnabled() {
return enabled;
}
@Nonnull
@Override
public String getUrl() {
return url;
}
@Nonnull
@Override
public String getUser() {
return user;
}
@Nonnull
@Override
public String getPassword() {
return password;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ImmutablePullRequestTriggerSettings that = (ImmutablePullRequestTriggerSettings) o;
if (enabled != that.enabled) return false;
if (!password.equals(that.password)) return false;
if (!url.equals(that.url)) return false;
return user.equals(that.user);
}
@Override
public int hashCode() {
int result = (enabled ? 1 : 0);
result = 31 * result + url.hashCode();
result = 31 * result + user.hashCode();
result = 31 * result + password.hashCode();
return result;
}
@Override
public String toString() {
return "ImmutablePullRequestTriggerSettings{" +
"enabled=" + enabled +
", url='" + url + '\'' +
", user='" + user + '\'' +
", password='" + password + '\'' +
'}';
}
}
|
src/main/java/com/richrelevance/stash/plugin/settings/ImmutablePullRequestTriggerSettings.java
|
package com.richrelevance.stash.plugin.settings;
import javax.annotation.Nonnull;
public final class ImmutablePullRequestTriggerSettings implements PullRequestTriggerSettings{
private final boolean enabled;
private final @Nonnull String url;
private final @Nonnull String user;
private final @Nonnull String password;
public ImmutablePullRequestTriggerSettings() {
this.enabled = false;
this.url = "http://localhost/bamboo";
this.user = "user";
this.password = "password";
// this.retestMsg = "(?i)retest this,? please|klaatu barada nikto";
}
public ImmutablePullRequestTriggerSettings(boolean enabled, @Nonnull String url, @Nonnull String user,
@Nonnull String password) {
this.enabled = enabled;
this.url = url;
this.user = user;
this.password = password;
}
@Override
public boolean isEnabled() {
return enabled;
}
@Nonnull
@Override
public String getUrl() {
return url;
}
@Nonnull
@Override
public String getUser() {
return user;
}
@Nonnull
@Override
public String getPassword() {
return password;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ImmutablePullRequestTriggerSettings that = (ImmutablePullRequestTriggerSettings) o;
if (enabled != that.enabled) return false;
if (!password.equals(that.password)) return false;
if (!url.equals(that.url)) return false;
return user.equals(that.user);
}
@Override
public int hashCode() {
int result = (enabled ? 1 : 0);
result = 31 * result + url.hashCode();
result = 31 * result + user.hashCode();
result = 31 * result + password.hashCode();
return result;
}
@Override
public String toString() {
return "ImmutablePullRequestTriggerSettings{" +
"enabled=" + enabled +
", url='" + url + '\'' +
", user='" + user + '\'' +
", password='" + password + '\'' +
'}';
}
}
|
Remove commented out line.
|
src/main/java/com/richrelevance/stash/plugin/settings/ImmutablePullRequestTriggerSettings.java
|
Remove commented out line.
|
|
Java
|
apache-2.0
|
9fd937018461162b2ced4cff03aa621d4fcdecfc
| 0
|
Hiroshi1978/lbhandler
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package web.component.impl.aws.model;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import web.component.api.model.Instance;
/**
*
* @author Hiroshi
*/
public class InstanceImplTest {
private static final List<Instance> testInstances = new ArrayList<>();
private static final String testImageId = "";
private static final String testInstanceType = "";
private static final String testInstanceLifeCycle = "";
private static final String testPlacement = "";
private static String testInstanceId;
public InstanceImplTest() {
}
@BeforeClass
public static void setUpClass() {
//build instance from create method to obtain reference to the object of the newly created instance.
Instance testInstance1 = new InstanceImpl.Builder().imageId(testImageId).type(testInstanceType).create();
testInstanceId = testInstance1.getId();
//build instance from get method to obtain reference to the object of the same instance.
Instance testInstance2 = new InstanceImpl.Builder().id(testInstanceId).get();
testInstances.add(testInstance1);
testInstances.add(testInstance2);
}
@AfterClass
public static void tearDownClass() {
//stop and terminate the test instance.
Instance testInstance = testInstances.get(0);
testInstance.stop();
testInstance.terminate();
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of asElbInstance method, of class InstanceImpl.
*/
@Test
public void testAsElbInstance() {
System.out.println("asElbInstance");
for(Instance testInstance : testInstances){
com.amazonaws.services.elasticloadbalancing.model.Instance elbInstance1 = ((InstanceImpl)testInstance).asElbInstance();
assertTrue(elbInstance1.getInstanceId() != null && !elbInstance1.getInstanceId().isEmpty());
}
}
/**
* Test of asEc2Instance method, of class InstanceImpl.
*/
@Test
public void testAsEc2Instance() {
System.out.println("asEc2Instance");
for(Instance testInstance : testInstances){
com.amazonaws.services.ec2.model.Instance ec2Instance = ((InstanceImpl)testInstance).asEc2Instance();
com.amazonaws.services.elasticloadbalancing.model.Instance elbInstance = ((InstanceImpl)testInstance).asElbInstance();
assertTrue(ec2Instance.getInstanceId() != null && !ec2Instance.getInstanceId().isEmpty());
assertEquals(ec2Instance.getInstanceId(),elbInstance.getInstanceId());
assertEquals(testImageId,ec2Instance.getImageId());
assertEquals(testInstanceType,ec2Instance.getInstanceType());
assertEquals(testInstanceType,ec2Instance.getInstanceLifecycle());
assertEquals(testPlacement,ec2Instance.getPlacement().toString());
}
}
/**
* Test of getLoadBalancer method, of class InstanceImpl.
*/
@Test
public void testGetLoadBalancer() {
System.out.println("getLoadBalancer");
int counter = 0;
for(Instance testInstance : testInstances){
try{
testInstance.getLoadBalancer();
}catch(UnsupportedOperationException e){
counter++;
}
}
assertEquals(testInstances.size(), counter);
}
/**
* Test of getLoadBalancers method, of class InstanceImpl.
*/
@Test
public void testGetLoadBalancers() {
System.out.println("getLoadBalancers");
int counter = 0;
for(Instance testInstance : testInstances){
try{
testInstance.getLoadBalancers();
}catch(UnsupportedOperationException e){
counter++;
}
}
assertEquals(testInstances.size(), counter);
}
/**
* Test of getId method, of class InstanceImpl.
*/
@Test
public void testGetId() {
System.out.println("getId");
assertEquals(testInstanceId, testInstances.get(1).getId());
}
/**
* Test of registerWith method, of class InstanceImpl.
*/
@Test
public void testRegisterWith() {
System.out.println("registerWith");
fail("The test case is a prototype.");
}
/**
* Test of deregisterFrom method, of class InstanceImpl.
*/
@Test
public void testDeregisterFrom() {
System.out.println("deregisterFrom");
fail("The test case is a prototype.");
}
/**
* Test of equals method, of class InstanceImpl.
*/
@Test
public void testEquals() {
System.out.println("equals");
fail("The test case is a prototype.");
}
/**
* Test of hashCode method, of class InstanceImpl.
*/
@Test
public void testHashCode() {
System.out.println("hashCode");
fail("The test case is a prototype.");
}
/**
* Test of getState method, of class InstanceImpl.
*/
@Test
public void testGetState() {
System.out.println("getState");
fail("The test case is a prototype.");
}
/**
* Test of getStateFromLB method, of class InstanceImpl.
*/
@Test
public void testGetStateFromLB() {
System.out.println("getStateFromLB");
fail("The test case is a prototype.");
}
/**
* Test of toString method, of class InstanceImpl.
*/
@Test
public void testToString() {
System.out.println("toString");
fail("The test case is a prototype.");
}
/**
* Test of start method, of class InstanceImpl.
*/
@Test
public void testStart() {
System.out.println("start");
fail("The test case is a prototype.");
}
/**
* Test of stop method, of class InstanceImpl.
*/
@Test
public void testStop() {
System.out.println("stop");
fail("The test case is a prototype.");
}
/**
* Test of getPlacement method, of class InstanceImpl.
*/
@Test
public void testGetPlacement() {
System.out.println("getPlacement");
for(Instance testInstance : testInstances)
assertEquals(testPlacement, testInstance.getPlacement());
}
/**
* Test of terminate method, of class InstanceImpl.
*/
@Test
public void testTerminate() {
System.out.println("terminate");
fail("The test case is a prototype.");
}
}
|
test/web/component/impl/aws/model/InstanceImplTest.java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package web.component.impl.aws.model;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import web.component.api.model.Instance;
/**
*
* @author Hiroshi
*/
public class InstanceImplTest {
private static final List<Instance> testInstances = new ArrayList<>();
private static final String testImageId = "";
private static final String testInstanceType = "";
private static final String testInstanceLifeCycle = "";
private static final String testPlacement = "";
private static String testInstanceId;
public InstanceImplTest() {
}
@BeforeClass
public static void setUpClass() {
//build instance from create method to obtain reference to the object of the newly created instance.
Instance testInstance1 = new InstanceImpl.Builder().imageId(testImageId).type(testInstanceType).create();
testInstanceId = testInstance1.getId();
//build instance from get method to obtain reference to the object of the same instance.
Instance testInstance2 = new InstanceImpl.Builder().id(testInstanceId).get();
testInstances.add(testInstance1);
testInstances.add(testInstance2);
}
@AfterClass
public static void tearDownClass() {
//stop and terminated the test instance.
Instance testInstance = testInstances.get(0);
testInstance.stop();
testInstance.terminate();
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of asElbInstance method, of class InstanceImpl.
*/
@Test
public void testAsElbInstance() {
System.out.println("asElbInstance");
for(Instance testInstance : testInstances){
com.amazonaws.services.elasticloadbalancing.model.Instance elbInstance1 = ((InstanceImpl)testInstance).asElbInstance();
assertTrue(elbInstance1.getInstanceId() != null && !elbInstance1.getInstanceId().isEmpty());
}
}
/**
* Test of asEc2Instance method, of class InstanceImpl.
*/
@Test
public void testAsEc2Instance() {
System.out.println("asEc2Instance");
for(Instance testInstance : testInstances){
com.amazonaws.services.ec2.model.Instance ec2Instance = ((InstanceImpl)testInstance).asEc2Instance();
com.amazonaws.services.elasticloadbalancing.model.Instance elbInstance = ((InstanceImpl)testInstance).asElbInstance();
assertTrue(ec2Instance.getInstanceId() != null && !ec2Instance.getInstanceId().isEmpty());
assertEquals(ec2Instance.getInstanceId(),elbInstance.getInstanceId());
assertEquals(testImageId,ec2Instance.getImageId());
assertEquals(testInstanceType,ec2Instance.getInstanceType());
assertEquals(testInstanceType,ec2Instance.getInstanceLifecycle());
assertEquals(testPlacement,ec2Instance.getPlacement().toString());
}
}
/**
* Test of getLoadBalancer method, of class InstanceImpl.
*/
@Test
public void testGetLoadBalancer() {
System.out.println("getLoadBalancer");
int counter = 0;
for(Instance testInstance : testInstances){
try{
testInstance.getLoadBalancer();
}catch(UnsupportedOperationException e){
counter++;
}
}
assertEquals(testInstances.size(), counter);
}
/**
* Test of getLoadBalancers method, of class InstanceImpl.
*/
@Test
public void testGetLoadBalancers() {
System.out.println("getLoadBalancers");
int counter = 0;
for(Instance testInstance : testInstances){
try{
testInstance.getLoadBalancers();
}catch(UnsupportedOperationException e){
counter++;
}
}
assertEquals(testInstances.size(), counter);
}
/**
* Test of getId method, of class InstanceImpl.
*/
@Test
public void testGetId() {
System.out.println("getId");
assertEquals(testInstanceId, testInstances.get(1).getId());
}
/**
* Test of registerWith method, of class InstanceImpl.
*/
@Test
public void testRegisterWith() {
System.out.println("registerWith");
fail("The test case is a prototype.");
}
/**
* Test of deregisterFrom method, of class InstanceImpl.
*/
@Test
public void testDeregisterFrom() {
System.out.println("deregisterFrom");
fail("The test case is a prototype.");
}
/**
* Test of equals method, of class InstanceImpl.
*/
@Test
public void testEquals() {
System.out.println("equals");
fail("The test case is a prototype.");
}
/**
* Test of hashCode method, of class InstanceImpl.
*/
@Test
public void testHashCode() {
System.out.println("hashCode");
fail("The test case is a prototype.");
}
/**
* Test of getState method, of class InstanceImpl.
*/
@Test
public void testGetState() {
System.out.println("getState");
fail("The test case is a prototype.");
}
/**
* Test of getStateFromLB method, of class InstanceImpl.
*/
@Test
public void testGetStateFromLB() {
System.out.println("getStateFromLB");
fail("The test case is a prototype.");
}
/**
* Test of toString method, of class InstanceImpl.
*/
@Test
public void testToString() {
System.out.println("toString");
fail("The test case is a prototype.");
}
/**
* Test of start method, of class InstanceImpl.
*/
@Test
public void testStart() {
System.out.println("start");
fail("The test case is a prototype.");
}
/**
* Test of stop method, of class InstanceImpl.
*/
@Test
public void testStop() {
System.out.println("stop");
fail("The test case is a prototype.");
}
/**
* Test of getPlacement method, of class InstanceImpl.
*/
@Test
public void testGetPlacement() {
System.out.println("getPlacement");
for(Instance testInstance : testInstances)
assertEquals(testPlacement, testInstance.getPlacement());
}
/**
* Test of terminate method, of class InstanceImpl.
*/
@Test
public void testTerminate() {
System.out.println("terminate");
fail("The test case is a prototype.");
}
}
|
Update InstanceImplTest.java
|
test/web/component/impl/aws/model/InstanceImplTest.java
|
Update InstanceImplTest.java
|
|
Java
|
apache-2.0
|
9c44ae231c826f5fae61a561af07ecb15a17cea2
| 0
|
yntelectual/nlighten,yntelectual/nlighten,yntelectual/nlighten,yntelectual/nlighten,yntelectual/nlighten
|
package me.nlighten.backend.test.db.services;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Named;
import me.nlighten.backend.cdi.annotations.Traced;
import me.nlighten.backend.cdi.annotations.TracedVerbosity;
import me.nlighten.backend.cdi.enums.VerbosityLevel;
/**
* Bean for testing verbosity annotation on class
*
* @author Ronald Kriek
*
*/
@Named
@Traced
@TracedVerbosity(VerbosityLevel.VERBOSE)
public class ClassVerbosityTestBean {
public List<String> interceptorArraySize() {
List<String> myList = new ArrayList<>();
myList.add("Foo");
myList.add("Bar");
return myList;
}
}
|
nlighten-backend/src/test/java/me/nlighten/backend/test/db/services/ClassVerbosityTestBean.java
|
package me.nlighten.backend.test.db.services;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Named;
import me.nlighten.backend.cdi.annotations.Traced;
import me.nlighten.backend.cdi.annotations.TracedVerbosity;
import me.nlighten.backend.cdi.enums.VerbosityLevel;
/**
* Test verbosity annotation on class
*
* @author Ronald Kriek
*
*/
@Named
@Traced
@TracedVerbosity(VerbosityLevel.VERBOSE)
public class ClassVerbosityTestBean {
public List<String> interceptorArraySize() {
List<String> myList = new ArrayList<>();
myList.add("Foo");
myList.add("Bar");
return myList;
}
}
|
Change comment.
|
nlighten-backend/src/test/java/me/nlighten/backend/test/db/services/ClassVerbosityTestBean.java
|
Change comment.
|
|
Java
|
apache-2.0
|
9d1cc884ad052083fb72b4107a62b0cbe3c2a027
| 0
|
apache/commons-codec,apache/commons-codec,apache/commons-codec,adrie4mac/commons-codec,mohanaraosv/commons-codec,adrie4mac/commons-codec,mohanaraosv/commons-codec,adrie4mac/commons-codec,mohanaraosv/commons-codec
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.codec.language.bm;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>
* A phoneme rule.
* </p>
* <p>
* Rules have a pattern, left context, right context, output phoneme, set of languages for which they apply and a logical flag indicating if
* all lanugages must be in play. A rule matches if:
* <ul>
* <li>the pattern matches at the current position</li>
* <li>the string up until the beginning of the pattern matches the left context</li>
* <li>the string from the end of the pattern matches the right context</li>
* <li>logical is ALL and all languages are in scope; or</li>
* <li>logical is any other value and at least one language is in scope</li>
* </ul>
* </p>
* <p>
* Rules are typically generated by parsing rules resources. In normal use, there will be no need for the user to explicitly construct their
* own.
* </p>
* <p>
* Rules are immutable and thread-safe.
* <h2>Rules resources</h2>
* <p>
* Rules are typically loaded from resource files. These are UTF-8 encoded text files. They are systematically named following the pattern:
* <blockquote>org/apache/commons/codec/language/bm/${NameType#getName}_${RuleType#getName}_${language}.txt</blockquote>
* </p>
* <p>
* The format of these resources is the following:
* <ul>
* <li><b>Rules:</b> whitespace separated, double-quoted strings. There should be 4 columns to each row, and these will be interpreted as:
* <ol>
* <li>pattern</li>
* <li>left context</li>
* <li>right context</li>
* <li>phoneme</li>
* </ol>
* </li>
* <li><b>End-of-line comments:</b> Any occurance of '//' will cause all text following on that line to be discarded as a comment.</li>
* <li><b>Multi-line comments:</b> Any line starting with '/*' will start multi-line commenting mode. This will skip all content until a
* line ending in '*' and '/' is found.</li>
* <li><b>Blank lines:</b> All blank lines will be skipped.</li>
* </ul>
* </p>
*
* @author Apache Software Foundation
* @since 2.0
*/
public class Rule {
private static class AppendableCharSeqeuence implements CharSequence {
private final CharSequence left;
private final CharSequence right;
private final int length;
private String contentCache = null;
private AppendableCharSeqeuence(CharSequence left, CharSequence right) {
this.left = left;
this.right = right;
this.length = left.length() + right.length();
}
public void buildString(StringBuilder sb) {
if (left instanceof AppendableCharSeqeuence) {
((AppendableCharSeqeuence) left).buildString(sb);
} else {
sb.append(left);
}
if (right instanceof AppendableCharSeqeuence) {
((AppendableCharSeqeuence) right).buildString(sb);
} else {
sb.append(right);
}
}
public char charAt(int index) {
// int lLength = left.length();
// if(index < lLength) return left.charAt(index);
// else return right.charAt(index - lLength);
return toString().charAt(index);
}
public int length() {
return length;
}
public CharSequence subSequence(int start, int end) {
// int lLength = left.length();
// if(start > lLength) return right.subSequence(start - lLength, end - lLength);
// else if(end <= lLength) return left.subSequence(start, end);
// else {
// CharSequence newLeft = left.subSequence(start, lLength);
// CharSequence newRight = right.subSequence(0, end - lLength);
// return new AppendableCharSeqeuence(newLeft, newRight);
// }
return toString().subSequence(start, end);
}
@Override
public String toString() {
if (contentCache == null) {
StringBuilder sb = new StringBuilder();
buildString(sb);
contentCache = sb.toString();
// System.err.println("Materialized string: " + contentCache);
}
return contentCache;
}
}
public static class Phoneme implements PhonemeExpr, Comparable<Phoneme> {
private final CharSequence phonemeText;
private final Languages.LanguageSet languages;
public Phoneme(CharSequence phonemeText, Languages.LanguageSet languages) {
this.phonemeText = phonemeText;
this.languages = languages;
}
public Phoneme append(CharSequence str) {
return new Phoneme(new AppendableCharSeqeuence(this.phonemeText, str), this.languages);
}
public int compareTo(Phoneme o) {
for (int i = 0; i < phonemeText.length(); i++) {
if (i >= o.phonemeText.length()) {
return +1;
}
int c = phonemeText.charAt(i) - o.phonemeText.charAt(i);
if (c != 0) {
return c;
}
}
if (phonemeText.length() < o.phonemeText.length()) {
return -1;
}
return 0;
}
public Languages.LanguageSet getLanguages() {
return this.languages;
}
public Iterable<Phoneme> getPhonemes() {
return Collections.singleton(this);
}
public CharSequence getPhonemeText() {
return this.phonemeText;
}
public Phoneme join(Phoneme right) {
return new Phoneme(new AppendableCharSeqeuence(this.phonemeText, right.phonemeText), this.languages.restrictTo(right.languages));
}
}
public interface PhonemeExpr {
Iterable<Phoneme> getPhonemes();
}
public static class PhonemeList implements PhonemeExpr {
private final List<Phoneme> phonemes;
public PhonemeList(List<Phoneme> phonemes) {
this.phonemes = phonemes;
}
public List<Phoneme> getPhonemes() {
return this.phonemes;
}
}
/**
* A minimal wrapper around the functionality of Matcher that we use, to allow for alternate implementations.
*/
public static interface RMatcher {
boolean find();
}
/**
* A minimal wrapper around the functionality of Pattern that we use, to allow for alternate implementations.
*/
public static interface RPattern {
RMatcher matcher(CharSequence input);
}
public static final String ALL = "ALL";
private static final String DOUBLE_QUOTE = "\"";
private static final String HASH_INCLUDE = "#include";
private static final Map<NameType, Map<RuleType, Map<String, List<Rule>>>> RULES = new EnumMap<NameType, Map<RuleType, Map<String, List<Rule>>>>(
NameType.class);
static {
for (NameType s : NameType.values()) {
Map<RuleType, Map<String, List<Rule>>> rts = new EnumMap<RuleType, Map<String, List<Rule>>>(RuleType.class);
for (RuleType rt : RuleType.values()) {
Map<String, List<Rule>> rs = new HashMap<String, List<Rule>>();
Languages ls = Languages.getInstance(s);
for (String l : ls.getLanguages()) {
try {
rs.put(l, parseRules(createScanner(s, rt, l), createResourceName(s, rt, l)));
} catch (IllegalStateException e) {
throw new IllegalStateException("Problem processing " + createResourceName(s, rt, l), e);
}
}
if (!rt.equals(RuleType.RULES)) {
rs.put("common", parseRules(createScanner(s, rt, "common"), createResourceName(s, rt, "common")));
}
rts.put(rt, Collections.unmodifiableMap(rs));
}
RULES.put(s, Collections.unmodifiableMap(rts));
}
}
private static boolean contains(CharSequence chars, char input) {
for (int i = 0; i < chars.length(); i++) {
if (chars.charAt(i) == input) {
return true;
}
}
return false;
}
private static String createResourceName(NameType nameType, RuleType rt, String lang) {
return String.format("org/apache/commons/codec/language/bm/%s_%s_%s.txt", nameType.getName(), rt.getName(), lang);
}
private static Scanner createScanner(NameType nameType, RuleType rt, String lang) {
String resName = createResourceName(nameType, rt, lang);
InputStream rulesIS = Languages.class.getClassLoader().getResourceAsStream(resName);
if (rulesIS == null) {
throw new IllegalArgumentException("Unable to load resource: " + resName);
}
return new Scanner(rulesIS, ResourceConstants.ENCODING);
}
private static Scanner createScanner(String lang) {
String resName = String.format("org/apache/commons/codec/language/bm/%s.txt", lang);
InputStream rulesIS = Languages.class.getClassLoader().getResourceAsStream(resName);
if (rulesIS == null) {
throw new IllegalArgumentException("Unable to load resource: " + resName);
}
return new Scanner(rulesIS, ResourceConstants.ENCODING);
}
private static boolean endsWith(CharSequence input, CharSequence suffix) {
if (suffix.length() > input.length()) {
return false;
}
for (int i = input.length() - 1, j = suffix.length() - 1; j >= 0; i--, j--) {
if (input.charAt(i) != suffix.charAt(j)) {
return false;
}
}
return true;
}
/**
* Gets rules for a combination of name type, rule type and languages.
*
* @param nameType
* the NameType to consider
* @param rt
* the RuleType to consider
* @param langs
* the set of languages to consider
* @return a list of Rules that apply
*/
public static List<Rule> getInstance(NameType nameType, RuleType rt, Languages.LanguageSet langs) {
return langs.isSingleton() ? getInstance(nameType, rt, langs.getAny()) : getInstance(nameType, rt, Languages.ANY);
}
/**
* Gets rules for a combination of name type, rule type and a single language.
*
* @param nameType
* the NameType to consider
* @param rt
* the RuleType to consider
* @param lang
* the language to consider
* @return a list rules for a combination of name type, rule type and a single language.
*/
public static List<Rule> getInstance(NameType nameType, RuleType rt, String lang) {
List<Rule> rules = RULES.get(nameType).get(rt).get(lang);
if (rules == null) {
throw new IllegalArgumentException(String.format("No rules found for %s, %s, %s.", nameType.getName(), rt.getName(), lang));
}
return rules;
}
private static Phoneme parsePhoneme(String ph) {
int open = ph.indexOf("[");
if (open >= 0) {
if (!ph.endsWith("]")) {
throw new IllegalArgumentException("Phoneme expression contains a '[' but does not end in ']'");
}
String before = ph.substring(0, open);
String in = ph.substring(open + 1, ph.length() - 1);
Set<String> langs = new HashSet<String>(Arrays.asList(in.split("[+]")));
return new Phoneme(before, Languages.LanguageSet.from(langs));
} else {
return new Phoneme(ph, Languages.ANY_LANGUAGE);
}
}
private static PhonemeExpr parsePhonemeExpr(String ph) {
if (ph.startsWith("(")) { // we have a bracketed list of options
if (!ph.endsWith(")")) {
throw new IllegalArgumentException("Phoneme starts with '(' so must end with ')'");
}
List<Phoneme> phs = new ArrayList<Phoneme>();
String body = ph.substring(1, ph.length() - 1);
for (String part : body.split("[|]")) {
phs.add(parsePhoneme(part));
}
if (body.startsWith("|") || body.endsWith("|")) {
phs.add(new Phoneme("", Languages.ANY_LANGUAGE));
}
return new PhonemeList(phs);
} else {
return parsePhoneme(ph);
}
}
private static List<Rule> parseRules(final Scanner scanner, final String location) {
List<Rule> lines = new ArrayList<Rule>();
int currentLine = 0;
boolean inMultilineComment = false;
while (scanner.hasNextLine()) {
currentLine++;
String rawLine = scanner.nextLine();
String line = rawLine;
if (inMultilineComment) {
if (line.endsWith(ResourceConstants.EXT_CMT_END)) {
inMultilineComment = false;
} else {
// skip
}
} else {
if (line.startsWith(ResourceConstants.EXT_CMT_START)) {
inMultilineComment = true;
} else {
// discard comments
int cmtI = line.indexOf(ResourceConstants.CMT);
if (cmtI >= 0) {
line = line.substring(0, cmtI);
}
// trim leading-trailing whitespace
line = line.trim();
if (line.length() == 0) {
continue; // empty lines can be safely skipped
}
if (line.startsWith(HASH_INCLUDE)) {
// include statement
String incl = line.substring(HASH_INCLUDE.length()).trim();
if (incl.contains(" ")) {
System.err.println("Warining: malformed import statement: " + rawLine);
} else {
lines.addAll(parseRules(createScanner(incl), location + "->" + incl));
}
} else {
// rule
String[] parts = line.split("\\s+");
if (parts.length != 4) {
System.err.println("Warning: malformed rule statement split into " + parts.length + " parts: " + rawLine);
} else {
try {
String pat = stripQuotes(parts[0]);
String lCon = stripQuotes(parts[1]);
String rCon = stripQuotes(parts[2]);
PhonemeExpr ph = parsePhonemeExpr(stripQuotes(parts[3]));
final int cLine = currentLine;
Rule r = new Rule(pat, lCon, rCon, ph) {
private final int line = cLine;
private final String loc = location;
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Rule");
sb.append("{line=").append(line);
sb.append(", loc='").append(loc).append('\'');
sb.append('}');
return sb.toString();
}
};
lines.add(r);
} catch (IllegalArgumentException e) {
throw new IllegalStateException("Problem parsing line " + currentLine, e);
}
}
}
}
}
}
return lines;
}
/**
* Attempts to compile the regex into direct string ops, falling back to Pattern and Matcher in the worst case.
*
* @param regex
* the regular expression to compile
* @return an RPattern that will match this regex
*/
private static RPattern pattern(final String regex) {
boolean startsWith = regex.startsWith("^");
boolean endsWith = regex.endsWith("$");
final String content = regex.substring(startsWith ? 1 : 0, endsWith ? regex.length() - 1 : regex.length());
boolean boxes = content.contains("[");
if (!boxes) {
if (startsWith && endsWith) {
// exact match
if (content.length() == 0) {
// empty
return new RPattern() {
public RMatcher matcher(final CharSequence input) {
return new RMatcher() {
public boolean find() {
return input.length() == 0;
}
};
}
};
} else {
return new RPattern() {
public RMatcher matcher(final CharSequence input) {
return new RMatcher() {
public boolean find() {
return input.equals(content);
}
};
}
};
}
} else if ((startsWith || endsWith) && content.length() == 0) {
// matches every string
return new RPattern() {
public RMatcher matcher(CharSequence input) {
return new RMatcher() {
public boolean find() {
return true;
}
};
}
};
} else if (startsWith) {
// matches from start
return new RPattern() {
public RMatcher matcher(final CharSequence input) {
return new RMatcher() {
public boolean find() {
return startsWith(input, content);
}
};
}
};
} else if (endsWith) {
// matches from start
return new RPattern() {
public RMatcher matcher(final CharSequence input) {
return new RMatcher() {
public boolean find() {
return endsWith(input, content);
}
};
}
};
}
} else {
boolean startsWithBox = content.startsWith("[");
boolean endsWithBox = content.endsWith("]");
if (startsWithBox && endsWithBox) {
String boxContent = content.substring(1, content.length() - 1);
if (!boxContent.contains("[")) {
// box containing alternatives
boolean negate = boxContent.startsWith("^");
if (negate) {
boxContent = boxContent.substring(1);
}
final String bContent = boxContent;
final boolean shouldMatch = !negate;
if (startsWith && endsWith) {
// exact match
return new RPattern() {
public RMatcher matcher(final CharSequence input) {
return new RMatcher() {
public boolean find() {
return input.length() == 1 && (contains(bContent, input.charAt(0)) == shouldMatch);
}
};
}
};
} else if (startsWith) {
// first char
return new RPattern() {
public RMatcher matcher(final CharSequence input) {
return new RMatcher() {
public boolean find() {
return input.length() > 0 && (contains(bContent, input.charAt(0)) == shouldMatch);
}
};
}
};
} else if (endsWith) {
// last char
return new RPattern() {
public RMatcher matcher(final CharSequence input) {
return new RMatcher() {
public boolean find() {
return input.length() > 0 && (contains(bContent, input.charAt(input.length() - 1)) == shouldMatch);
}
};
}
};
}
}
}
}
// System.out.println("Couldn't optimize regex: " + regex);
return new RPattern() {
Pattern pattern = Pattern.compile(regex);
public RMatcher matcher(CharSequence input) {
final Matcher matcher = pattern.matcher(input);
return new RMatcher() {
public boolean find() {
return matcher.find();
}
};
}
};
}
private static boolean startsWith(CharSequence input, CharSequence prefix) {
if (prefix.length() > input.length()) {
return false;
}
for (int i = 0; i < prefix.length(); i++) {
if (input.charAt(i) != prefix.charAt(i)) {
return false;
}
}
return true;
}
private static String stripQuotes(String str) {
if (str.startsWith(DOUBLE_QUOTE)) {
str = str.substring(1);
}
if (str.endsWith(DOUBLE_QUOTE)) {
str = str.substring(0, str.length() - 1);
}
return str;
}
private final RPattern lContext;
private final String pattern;
private final PhonemeExpr phoneme;
private final RPattern rContext;
/**
* Creates a new rule.
*
* @param pattern
* the pattern
* @param lContext
* the left context
* @param rContext
* the right context
* @param phoneme
* the resulting phoneme
*/
public Rule(String pattern, String lContext, String rContext, PhonemeExpr phoneme) {
this.pattern = pattern;
this.lContext = pattern(lContext + "$");
this.rContext = pattern("^" + rContext);
this.phoneme = phoneme;
}
/**
* Gets the left context. This is a regular expression that must match to the left of the pattern.
*
* @return the left context Pattern
*/
public RPattern getLContext() {
return this.lContext;
}
/**
* Gets the pattern. This is a string-literal that must exactly match.
*
* @return the pattern
*/
public String getPattern() {
return this.pattern;
}
/**
* Gets the phoneme. If the rule matches, this is the phoneme associated with the pattern match.
*
* @return the phoneme
*/
public PhonemeExpr getPhoneme() {
return this.phoneme;
}
/**
* Gets the right context. This is a regular expression that must match to the right of the pattern.
*
* @return the right context Pattern
*/
public RPattern getRContext() {
return this.rContext;
}
/**
* Decides if the pattern and context match the input starting at a position.
*
* @param input
* the input String
* @param i
* the int position within the input
* @return true if the pattern and left/right context match, false otherwise
*/
public boolean patternAndContextMatches(CharSequence input, int i) {
if (i < 0)
throw new IndexOutOfBoundsException("Can not match pattern at negative indexes");
int patternLength = this.pattern.length();
int ipl = i + patternLength;
if (ipl > input.length()) {
// not enough room for the pattern to match
return false;
}
boolean patternMatches = input.subSequence(i, ipl).equals(this.pattern);
boolean rContextMatches = this.rContext.matcher(input.subSequence(ipl, input.length())).find();
boolean lContextMatches = this.lContext.matcher(input.subSequence(0, i)).find();
return patternMatches && rContextMatches && lContextMatches;
}
}
|
src/java/org/apache/commons/codec/language/bm/Rule.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.codec.language.bm;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>
* A phoneme rule.
* </p>
* <p>
* Rules have a pattern, left context, right context, output phoneme, set of languages for which they apply and a logical flag indicating if
* all lanugages must be in play. A rule matches if:
* <ul>
* <li>the pattern matches at the current position</li>
* <li>the string up until the beginning of the pattern matches the left context</li>
* <li>the string from the end of the pattern matches the right context</li>
* <li>logical is ALL and all languages are in scope; or</li>
* <li>logical is any other value and at least one language is in scope</li>
* </ul>
* </p>
* <p>
* Rules are typically generated by parsing rules resources. In normal use, there will be no need for the user to explicitly construct their
* own.
* </p>
* <p>
* Rules are immutable and thread-safe.
* <h2>Rules resources</h2>
* <p>
* Rules are typically loaded from resource files. These are UTF-8 encoded text files. They are systematically named following the pattern:
* <blockquote>org/apache/commons/codec/language/bm/${NameType#getName}_${RuleType#getName}_${language}.txt</blockquote>
* </p>
* <p>
* The format of these resources is the following:
* <ul>
* <li><b>Rules:</b> whitespace separated, double-quoted strings. There should be 4 columns to each row, and these will be interpreted as:
* <ol>
* <li>pattern</li>
* <li>left context</li>
* <li>right context</li>
* <li>phoneme</li>
* </ol>
* </li>
* <li><b>End-of-line comments:</b> Any occurance of '//' will cause all text following on that line to be discarded as a comment.</li>
* <li><b>Multi-line comments:</b> Any line starting with '/*' will start multi-line commenting mode. This will skip all content until a
* line ending in '*' and '/' is found.</li>
* <li><b>Blank lines:</b> All blank lines will be skipped.</li>
* </ul>
* </p>
*
* @author Apache Software Foundation
* @since 2.0
*/
public class Rule {
private static class AppendableCharSeqeuence implements CharSequence {
private final CharSequence left;
private final CharSequence right;
private final int length;
private String contentCache = null;
private AppendableCharSeqeuence(CharSequence left, CharSequence right) {
this.left = left;
this.right = right;
this.length = left.length() + right.length();
}
public void buildString(StringBuilder sb) {
if (left instanceof AppendableCharSeqeuence) {
((AppendableCharSeqeuence) left).buildString(sb);
} else {
sb.append(left);
}
if (right instanceof AppendableCharSeqeuence) {
((AppendableCharSeqeuence) right).buildString(sb);
} else {
sb.append(right);
}
}
public char charAt(int index) {
// int lLength = left.length();
// if(index < lLength) return left.charAt(index);
// else return right.charAt(index - lLength);
return toString().charAt(index);
}
public int length() {
return length;
}
public CharSequence subSequence(int start, int end) {
// int lLength = left.length();
// if(start > lLength) return right.subSequence(start - lLength, end - lLength);
// else if(end <= lLength) return left.subSequence(start, end);
// else {
// CharSequence newLeft = left.subSequence(start, lLength);
// CharSequence newRight = right.subSequence(0, end - lLength);
// return new AppendableCharSeqeuence(newLeft, newRight);
// }
return toString().subSequence(start, end);
}
@Override
public String toString() {
if (contentCache == null) {
StringBuilder sb = new StringBuilder();
buildString(sb);
contentCache = sb.toString();
// System.err.println("Materialized string: " + contentCache);
}
return contentCache;
}
}
public static class Phoneme implements PhonemeExpr, Comparable<Phoneme> {
private final CharSequence phonemeText;
private final Languages.LanguageSet languages;
public Phoneme(CharSequence phonemeText, Languages.LanguageSet languages) {
this.phonemeText = phonemeText;
this.languages = languages;
}
public Phoneme append(CharSequence str) {
return new Phoneme(new AppendableCharSeqeuence(this.phonemeText, str), this.languages);
}
public int compareTo(Phoneme o) {
for (int i = 0; i < phonemeText.length(); i++) {
if (i >= o.phonemeText.length()) {
return +1;
}
int c = phonemeText.charAt(i) - o.phonemeText.charAt(i);
if (c != 0) {
return c;
}
}
if (phonemeText.length() < o.phonemeText.length()) {
return -1;
}
return 0;
}
public Languages.LanguageSet getLanguages() {
return this.languages;
}
public Iterable<Phoneme> getPhonemes() {
return Collections.singleton(this);
}
public CharSequence getPhonemeText() {
return this.phonemeText;
}
public Phoneme join(Phoneme right) {
return new Phoneme(new AppendableCharSeqeuence(this.phonemeText, right.phonemeText), this.languages.restrictTo(right.languages));
}
}
public interface PhonemeExpr {
Iterable<Phoneme> getPhonemes();
}
public static class PhonemeList implements PhonemeExpr {
private final List<Phoneme> phonemes;
public PhonemeList(List<Phoneme> phonemes) {
this.phonemes = phonemes;
}
public List<Phoneme> getPhonemes() {
return this.phonemes;
}
}
/**
* A minimal wrapper around the functionality of Matcher that we use, to allow for alternate implementations.
*/
public static interface RMatcher {
boolean find();
}
/**
* A minimal wrapper around the functionality of Pattern that we use, to allow for alternate implementations.
*/
public static interface RPattern {
RMatcher matcher(CharSequence input);
}
public static final String ALL = "ALL";
private static final String DOUBLE_QUOTE = "\"";
private static final String HASH_INCLUDE = "#include";
private static final Map<NameType, Map<RuleType, Map<String, List<Rule>>>> RULES = new EnumMap<NameType, Map<RuleType, Map<String, List<Rule>>>>(
NameType.class);
static {
for (NameType s : NameType.values()) {
Map<RuleType, Map<String, List<Rule>>> rts = new EnumMap<RuleType, Map<String, List<Rule>>>(RuleType.class);
for (RuleType rt : RuleType.values()) {
Map<String, List<Rule>> rs = new HashMap<String, List<Rule>>();
Languages ls = Languages.getInstance(s);
for (String l : ls.getLanguages()) {
try {
rs.put(l, parseRules(createScanner(s, rt, l), createResourceName(s, rt, l)));
} catch (IllegalStateException e) {
throw new IllegalStateException("Problem processing " + createResourceName(s, rt, l), e);
}
}
if (!rt.equals(RuleType.RULES)) {
rs.put("common", parseRules(createScanner(s, rt, "common"), createResourceName(s, rt, "common")));
}
rts.put(rt, Collections.unmodifiableMap(rs));
}
RULES.put(s, Collections.unmodifiableMap(rts));
}
}
private static boolean contains(CharSequence chars, char input) {
for (int i = 0; i < chars.length(); i++) {
if (chars.charAt(i) == input) {
return true;
}
}
return false;
}
private static String createResourceName(NameType nameType, RuleType rt, String lang) {
return String.format("org/apache/commons/codec/language/bm/%s_%s_%s.txt", nameType.getName(), rt.getName(), lang);
}
private static Scanner createScanner(NameType nameType, RuleType rt, String lang) {
String resName = createResourceName(nameType, rt, lang);
InputStream rulesIS = Languages.class.getClassLoader().getResourceAsStream(resName);
if (rulesIS == null) {
throw new IllegalArgumentException("Unable to load resource: " + resName);
}
return new Scanner(rulesIS, ResourceConstants.ENCODING);
}
private static Scanner createScanner(String lang) {
String resName = String.format("org/apache/commons/codec/language/bm/%s.txt", lang);
InputStream rulesIS = Languages.class.getClassLoader().getResourceAsStream(resName);
if (rulesIS == null) {
throw new IllegalArgumentException("Unable to load resource: " + resName);
}
return new Scanner(rulesIS, ResourceConstants.ENCODING);
}
private static boolean endsWith(CharSequence input, CharSequence suffix) {
if (suffix.length() > input.length()) {
return false;
}
for (int i = input.length() - 1, j = suffix.length() - 1; j >= 0; i--, j--) {
if (input.charAt(i) != suffix.charAt(j)) {
return false;
}
}
return true;
}
/**
* Gets rules for a combination of name type, rule type and languages.
*
* @param nameType
* the NameType to consider
* @param rt
* the RuleType to consider
* @param langs
* the set of languages to consider
* @return a list of Rules that apply
*/
public static List<Rule> getInstance(NameType nameType, RuleType rt, Languages.LanguageSet langs) {
return langs.isSingleton() ? getInstance(nameType, rt, langs.getAny()) : getInstance(nameType, rt, Languages.ANY);
}
/**
* Gets rules for a combination of name type, rule type and a single language.
*
* @param nameType
* the NameType to consider
* @param rt
* the RuleType to consider
* @param lang
* the language to consider
* @return a list rules for a combination of name type, rule type and a single language.
*/
public static List<Rule> getInstance(NameType nameType, RuleType rt, String lang) {
List<Rule> rules = RULES.get(nameType).get(rt).get(lang);
if (rules == null) {
throw new IllegalArgumentException(String.format("No rules found for %s, %s, %s.", nameType.getName(), rt.getName(), lang));
}
return rules;
}
private static Phoneme parsePhoneme(String ph) {
int open = ph.indexOf("[");
if (open >= 0) {
if (!ph.endsWith("]")) {
throw new IllegalArgumentException("Phoneme expression contains a '[' but does not end in ']'");
}
String before = ph.substring(0, open);
String in = ph.substring(open + 1, ph.length() - 1);
Set<String> langs = new HashSet<String>(Arrays.asList(in.split("[+]")));
return new Phoneme(before, Languages.LanguageSet.from(langs));
} else {
return new Phoneme(ph, Languages.ANY_LANGUAGE);
}
}
private static PhonemeExpr parsePhonemeExpr(String ph) {
if (ph.startsWith("(")) { // we have a bracketed list of options
if (!ph.endsWith(")")) {
throw new IllegalArgumentException("Phoneme starts with '(' so must end with ')'");
}
List<Phoneme> phs = new ArrayList<Phoneme>();
String body = ph.substring(1, ph.length() - 1);
for (String part : body.split("[|]")) {
phs.add(parsePhoneme(part));
}
if (body.startsWith("|") || body.endsWith("|")) {
phs.add(new Phoneme("", Languages.ANY_LANGUAGE));
}
return new PhonemeList(phs);
} else {
return parsePhoneme(ph);
}
}
private static List<Rule> parseRules(final Scanner scanner, final String location) {
List<Rule> lines = new ArrayList<Rule>();
int currentLine = 0;
boolean inMultilineComment = false;
while (scanner.hasNextLine()) {
currentLine++;
String rawLine = scanner.nextLine();
String line = rawLine;
if (inMultilineComment) {
if (line.endsWith(ResourceConstants.EXT_CMT_END)) {
inMultilineComment = false;
} else {
// skip
}
} else {
if (line.startsWith(ResourceConstants.EXT_CMT_START)) {
inMultilineComment = true;
} else {
// discard comments
int cmtI = line.indexOf(ResourceConstants.CMT);
if (cmtI >= 0) {
line = line.substring(0, cmtI);
}
// trim leading-trailing whitespace
line = line.trim();
if (line.length() == 0) {
continue; // empty lines can be safely skipped
}
if (line.startsWith(HASH_INCLUDE)) {
// include statement
String incl = line.substring(HASH_INCLUDE.length()).trim();
if (incl.contains(" ")) {
System.err.println("Warining: malformed import statement: " + rawLine);
} else {
lines.addAll(parseRules(createScanner(incl), location + "->" + incl));
}
} else {
// rule
String[] parts = line.split("\\s+");
if (parts.length != 4) {
System.err.println("Warning: malformed rule statement split into " + parts.length + " parts: " + rawLine);
} else {
try {
String pat = stripQuotes(parts[0]);
String lCon = stripQuotes(parts[1]);
String rCon = stripQuotes(parts[2]);
PhonemeExpr ph = parsePhonemeExpr(stripQuotes(parts[3]));
final int cLine = currentLine;
Rule r = new Rule(pat, lCon, rCon, ph) {
private final int line = cLine;
private final String loc = location;
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Rule");
sb.append("{line=").append(line);
sb.append(", loc='").append(loc).append('\'');
sb.append('}');
return sb.toString();
}
};
lines.add(r);
} catch (IllegalArgumentException e) {
throw new IllegalStateException("Problem parsing line " + currentLine, e);
}
}
}
}
}
}
return lines;
}
/**
* Attempt to compile the regex into direct string ops, falling back to Pattern and Matcher in the worst case.
*
* @param regex
* the regular expression to compile
* @return an RPattern that will match this regex
*/
private static RPattern pattern(final String regex) {
boolean startsWith = regex.startsWith("^");
boolean endsWith = regex.endsWith("$");
final String content = regex.substring(startsWith ? 1 : 0, endsWith ? regex.length() - 1 : regex.length());
boolean boxes = content.contains("[");
if (!boxes) {
if (startsWith && endsWith) {
// exact match
if (content.length() == 0) {
// empty
return new RPattern() {
public RMatcher matcher(final CharSequence input) {
return new RMatcher() {
public boolean find() {
return input.length() == 0;
}
};
}
};
} else {
return new RPattern() {
public RMatcher matcher(final CharSequence input) {
return new RMatcher() {
public boolean find() {
return input.equals(content);
}
};
}
};
}
} else if ((startsWith || endsWith) && content.length() == 0) {
// matches every string
return new RPattern() {
public RMatcher matcher(CharSequence input) {
return new RMatcher() {
public boolean find() {
return true;
}
};
}
};
} else if (startsWith) {
// matches from start
return new RPattern() {
public RMatcher matcher(final CharSequence input) {
return new RMatcher() {
public boolean find() {
return startsWith(input, content);
}
};
}
};
} else if (endsWith) {
// matches from start
return new RPattern() {
public RMatcher matcher(final CharSequence input) {
return new RMatcher() {
public boolean find() {
return endsWith(input, content);
}
};
}
};
}
} else {
boolean startsWithBox = content.startsWith("[");
boolean endsWithBox = content.endsWith("]");
if (startsWithBox && endsWithBox) {
String boxContent = content.substring(1, content.length() - 1);
if (!boxContent.contains("[")) {
// box containing alternatives
boolean negate = boxContent.startsWith("^");
if (negate) {
boxContent = boxContent.substring(1);
}
final String bContent = boxContent;
final boolean shouldMatch = !negate;
if (startsWith && endsWith) {
// exact match
return new RPattern() {
public RMatcher matcher(final CharSequence input) {
return new RMatcher() {
public boolean find() {
return input.length() == 1 && (contains(bContent, input.charAt(0)) == shouldMatch);
}
};
}
};
} else if (startsWith) {
// first char
return new RPattern() {
public RMatcher matcher(final CharSequence input) {
return new RMatcher() {
public boolean find() {
return input.length() > 0 && (contains(bContent, input.charAt(0)) == shouldMatch);
}
};
}
};
} else if (endsWith) {
// last char
return new RPattern() {
public RMatcher matcher(final CharSequence input) {
return new RMatcher() {
public boolean find() {
return input.length() > 0 && (contains(bContent, input.charAt(input.length() - 1)) == shouldMatch);
}
};
}
};
}
}
}
}
// System.out.println("Couldn't optimize regex: " + regex);
return new RPattern() {
Pattern pattern = Pattern.compile(regex);
public RMatcher matcher(CharSequence input) {
final Matcher matcher = pattern.matcher(input);
return new RMatcher() {
public boolean find() {
return matcher.find();
}
};
}
};
}
private static boolean startsWith(CharSequence input, CharSequence prefix) {
if (prefix.length() > input.length()) {
return false;
}
for (int i = 0; i < prefix.length(); i++) {
if (input.charAt(i) != prefix.charAt(i)) {
return false;
}
}
return true;
}
private static String stripQuotes(String str) {
if (str.startsWith(DOUBLE_QUOTE)) {
str = str.substring(1);
}
if (str.endsWith(DOUBLE_QUOTE)) {
str = str.substring(0, str.length() - 1);
}
return str;
}
private final RPattern lContext;
private final String pattern;
private final PhonemeExpr phoneme;
private final RPattern rContext;
/**
* Creates a new rule.
*
* @param pattern
* the pattern
* @param lContext
* the left context
* @param rContext
* the right context
* @param phoneme
* the resulting phoneme
*/
public Rule(String pattern, String lContext, String rContext, PhonemeExpr phoneme) {
this.pattern = pattern;
this.lContext = pattern(lContext + "$");
this.rContext = pattern("^" + rContext);
this.phoneme = phoneme;
}
/**
* Gets the left context. This is a regular expression that must match to the left of the pattern.
*
* @return the left context Pattern
*/
public RPattern getLContext() {
return this.lContext;
}
/**
* Gets the pattern. This is a string-literal that must exactly match.
*
* @return the pattern
*/
public String getPattern() {
return this.pattern;
}
/**
* Gets the phoneme. If the rule matches, this is the phoneme associated with the pattern match.
*
* @return the phoneme
*/
public PhonemeExpr getPhoneme() {
return this.phoneme;
}
/**
* Gets the right context. This is a regular expression that must match to the right of the pattern.
*
* @return the right context Pattern
*/
public RPattern getRContext() {
return this.rContext;
}
/**
* Decides if the pattern and context match the input starting at a position.
*
* @param input
* the input String
* @param i
* the int position within the input
* @return true if the pattern and left/right context match, false otherwise
*/
public boolean patternAndContextMatches(CharSequence input, int i) {
if (i < 0)
throw new IndexOutOfBoundsException("Can not match pattern at negative indexes");
int patternLength = this.pattern.length();
int ipl = i + patternLength;
if (ipl > input.length()) {
// not enough room for the pattern to match
return false;
}
boolean patternMatches = input.subSequence(i, ipl).equals(this.pattern);
boolean rContextMatches = this.rContext.matcher(input.subSequence(ipl, input.length())).find();
boolean lContextMatches = this.lContext.matcher(input.subSequence(0, i)).find();
return patternMatches && rContextMatches && lContextMatches;
}
}
|
Javadoc: use the active voice.
git-svn-id: cde5a1597f50f50feab6f72941f6b219c34291a1@1154724 13f79535-47bb-0310-9956-ffa450edef68
|
src/java/org/apache/commons/codec/language/bm/Rule.java
|
Javadoc: use the active voice.
|
|
Java
|
apache-2.0
|
801ad178c9234afd20a4ee4134f2aba4aa66f5e8
| 0
|
undertow-io/undertow,jamezp/undertow,ctomc/undertow,stuartwdouglas/undertow,popstr/undertow,rhatlapa/undertow,popstr/undertow,TomasHofman/undertow,msfm/undertow,pedroigor/undertow,stuartwdouglas/undertow,msfm/undertow,aradchykov/undertow,rhatlapa/undertow,jasonchaffee/undertow,soul2zimate/undertow,pedroigor/undertow,aradchykov/undertow,wildfly-security-incubator/undertow,rhusar/undertow,marschall/undertow,jamezp/undertow,biddyweb/undertow,jstourac/undertow,pedroigor/undertow,marschall/undertow,darranl/undertow,yonglehou/undertow,TomasHofman/undertow,aldaris/undertow,jstourac/undertow,rhusar/undertow,nkhuyu/undertow,pferraro/undertow,darranl/undertow,amannm/undertow,rhusar/undertow,jamezp/undertow,rogerchina/undertow,yonglehou/undertow,darranl/undertow,baranowb/undertow,popstr/undertow,golovnin/undertow,marschall/undertow,wildfly-security-incubator/undertow,soul2zimate/undertow,pferraro/undertow,golovnin/undertow,soul2zimate/undertow,rogerchina/undertow,nkhuyu/undertow,n1hility/undertow,aldaris/undertow,amannm/undertow,stuartwdouglas/undertow,jstourac/undertow,msfm/undertow,wildfly-security-incubator/undertow,ctomc/undertow,pferraro/undertow,jasonchaffee/undertow,n1hility/undertow,aradchykov/undertow,grassjedi/undertow,amannm/undertow,Karm/undertow,biddyweb/undertow,emag/codereading-undertow,jasonchaffee/undertow,rogerchina/undertow,grassjedi/undertow,baranowb/undertow,TomasHofman/undertow,grassjedi/undertow,n1hility/undertow,Karm/undertow,undertow-io/undertow,biddyweb/undertow,ctomc/undertow,baranowb/undertow,rhatlapa/undertow,nkhuyu/undertow,emag/codereading-undertow,Karm/undertow,yonglehou/undertow,undertow-io/undertow,aldaris/undertow,golovnin/undertow
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow.test.util;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpOpenListener;
import io.undertow.server.HttpTransferEncodingHandler;
import io.undertow.server.handlers.blocking.BlockingHandler;
import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.RunListener;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
import org.xnio.BufferAllocator;
import org.xnio.ByteBufferSlicePool;
import org.xnio.ChannelListener;
import org.xnio.ChannelListeners;
import org.xnio.OptionMap;
import org.xnio.Options;
import org.xnio.Xnio;
import org.xnio.XnioWorker;
import org.xnio.channels.AcceptingChannel;
import org.xnio.channels.ConnectedStreamChannel;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* A class that starts a server before the test suite. By swapping out the root handler
* tests can test various server functionality without continually starting and stopping the server.
*
* @author Stuart Douglas
*/
public class DefaultServer extends BlockJUnit4ClassRunner {
private static final String DEFAULT = "default";
private static boolean first = true;
private static HttpOpenListener openListener;
private static XnioWorker worker;
private static AcceptingChannel<? extends ConnectedStreamChannel> server;
private static Xnio xnio;
/**
* The executor service that is provided to
*/
private static ExecutorService blockingExecutorService;
/**
* @return The base URL that can be used to make connections to this server
*/
public static String getDefaultServerAddress() {
return "http://" + getHostAddress(DEFAULT) + ":" + getHostPort(DEFAULT);
}
/**
* This method returns a new blocking handler. The executor service it uses has its lifecycle controlled
* by the test framework, so should not be shut down between tests.
*
* @return A new blocking handler
*/
public static BlockingHandler newBlockingHandler() {
final BlockingHandler ret = new BlockingHandler();
ret.setExecutor(blockingExecutorService);
return ret;
}
public DefaultServer(Class<?> klass) throws InitializationError {
super(klass);
}
@Override
public Description getDescription() {
return super.getDescription();
}
@Override
public void run(final RunNotifier notifier) {
if (first) {
first = false;
xnio = Xnio.getInstance("nio", DefaultServer.class.getClassLoader());
try {
blockingExecutorService = Executors.newFixedThreadPool(10);
worker = xnio.createWorker(OptionMap.builder()
.set(Options.WORKER_WRITE_THREADS, 4)
.set(Options.WORKER_READ_THREADS, 4)
.set(Options.CONNECTION_HIGH_WATER, 1000000)
.set(Options.CONNECTION_LOW_WATER, 1000000)
.set(Options.WORKER_TASK_CORE_THREADS, 10)
.set(Options.WORKER_TASK_MAX_THREADS, 12)
.getMap());
openListener = new HttpOpenListener(new ByteBufferSlicePool(BufferAllocator.DIRECT_BYTE_BUFFER_ALLOCATOR, 8192, 8192 * 8192));
ChannelListener acceptListener = ChannelListeners.openListenerAdapter(openListener);
server = worker.createStreamServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT)), acceptListener, OptionMap.EMPTY);
server.resumeAccepts();
} catch (IOException e) {
throw new RuntimeException(e);
}
notifier.addListener(new RunListener() {
@Override
public void testRunFinished(final Result result) throws Exception {
server.close();
worker.shutdown();
blockingExecutorService.shutdownNow();
}
});
}
super.run(notifier);
}
/**
* Sets the root handler for the default web server
*
* @param rootHandler The handler to use
*/
public static void setRootHandler(HttpHandler rootHandler) {
final HttpTransferEncodingHandler ph = new HttpTransferEncodingHandler();
ph.setNext(rootHandler);
openListener.setRootHandler(ph);
}
private static String getHostAddress(String serverName) {
return System.getProperty(serverName + ".server.address");
}
private static int getHostPort(String serverName) {
return Integer.getInteger(serverName + ".server.port");
}
public static ExecutorService getBlockingExecutorService() {
return blockingExecutorService;
}
}
|
testsuite/core/src/test/java/io/undertow/test/util/DefaultServer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow.test.util;
import io.undertow.server.HttpTransferEncodingHandler;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.RunListener;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
import org.xnio.ByteBufferSlicePool;
import org.xnio.ChannelListener;
import org.xnio.ChannelListeners;
import org.xnio.OptionMap;
import org.xnio.Options;
import org.xnio.Xnio;
import org.xnio.XnioWorker;
import org.xnio.channels.AcceptingChannel;
import org.xnio.channels.ConnectedStreamChannel;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpOpenListener;
import io.undertow.server.handlers.blocking.BlockingHandler;
/**
* A class that starts a server before the test suite. By swapping out the root handler
* tests can test various server functionality without continually starting and stopping the server.
*
* @author Stuart Douglas
*/
public class DefaultServer extends BlockJUnit4ClassRunner {
private static final String DEFAULT = "default";
private static boolean first = true;
private static HttpOpenListener openListener;
private static XnioWorker worker;
private static AcceptingChannel<? extends ConnectedStreamChannel> server;
private static Xnio xnio;
/**
* The executor service that is provided to
*/
private static ExecutorService blockingExecutorService;
/**
* @return The base URL that can be used to make connections to this server
*/
public static String getDefaultServerAddress() {
return "http://" + getHostAddress(DEFAULT) + ":" + getHostPort(DEFAULT);
}
/**
* This method returns a new blocking handler. The executor service it uses has its lifecycle controlled
* by the test framework, so should not be shut down between tests.
*
* @return A new blocking handler
*/
public static BlockingHandler newBlockingHandler() {
final BlockingHandler ret = new BlockingHandler();
ret.setExecutor(blockingExecutorService);
return ret;
}
public DefaultServer(Class<?> klass) throws InitializationError {
super(klass);
}
@Override
public Description getDescription() {
return super.getDescription();
}
@Override
public void run(final RunNotifier notifier) {
if (first) {
first = false;
xnio = Xnio.getInstance("nio", DefaultServer.class.getClassLoader());
try {
blockingExecutorService = Executors.newFixedThreadPool(10);
worker = xnio.createWorker(OptionMap.create(Options.WORKER_WRITE_THREADS, 2, Options.WORKER_READ_THREADS, 2));
openListener = new HttpOpenListener(new ByteBufferSlicePool(10000, 10000));
ChannelListener acceptListener = ChannelListeners.openListenerAdapter(openListener);
server = worker.createStreamServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT)), acceptListener, OptionMap.EMPTY);
server.resumeAccepts();
} catch (IOException e) {
throw new RuntimeException(e);
}
notifier.addListener(new RunListener() {
@Override
public void testRunFinished(final Result result) throws Exception {
server.close();
worker.shutdown();
blockingExecutorService.shutdownNow();
}
});
}
super.run(notifier);
}
/**
* Sets the root handler for the default web server
*
* @param rootHandler The handler to use
*/
public static void setRootHandler(HttpHandler rootHandler) {
final HttpTransferEncodingHandler ph = new HttpTransferEncodingHandler();
ph.setNext(rootHandler);
openListener.setRootHandler(ph);
}
private static String getHostAddress(String serverName) {
return System.getProperty(serverName + ".server.address");
}
private static int getHostPort(String serverName) {
return Integer.getInteger(serverName + ".server.port");
}
public static ExecutorService getBlockingExecutorService() {
return blockingExecutorService;
}
}
|
Use more reasonable defaults from testsuite
|
testsuite/core/src/test/java/io/undertow/test/util/DefaultServer.java
|
Use more reasonable defaults from testsuite
|
|
Java
|
apache-2.0
|
94dba9ff2b142f56b5e8afc959258824ea26f0f6
| 0
|
nengxu/OrientDB,nengxu/OrientDB,nengxu/OrientDB,nengxu/OrientDB
|
/*
* Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.server.network.protocol.http;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import com.orientechnologies.common.collection.OMultiValue;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.OBinaryProtocol;
import com.orientechnologies.orient.core.serialization.serializer.OJSONWriter;
/**
* Maintains information about current HTTP response.
*
* @author Luca Garulli
*
*/
public class OHttpResponse {
public static final String JSON_FORMAT = "type,indent:2,rid,version,attribSameRow,class";
public static final char[] URL_SEPARATOR = { '/' };
private final OutputStream out;
public final String httpVersion;
public String headers;
public String[] additionalHeaders;
public String characterSet;
public String contentType;
public String serverInfo;
public String sessionId;
public String callbackFunction;
public OHttpResponse(final OutputStream iOutStream, final String iHttpVersion, final String[] iAdditionalHeaders,
final String iResponseCharSet, final String iServerInfo, final String iSessionId, final String iCallbackFunction) {
out = iOutStream;
httpVersion = iHttpVersion;
additionalHeaders = iAdditionalHeaders;
characterSet = iResponseCharSet;
serverInfo = iServerInfo;
sessionId = iSessionId;
callbackFunction = iCallbackFunction;
}
public void send(final int iCode, final String iReason, final String iContentType, final Object iContent, final String iHeaders)
throws IOException {
send(iCode, iReason, iContentType, iContent, iHeaders, true);
}
public void send(final int iCode, final String iReason, final String iContentType, final Object iContent, final String iHeaders,
final boolean iKeepAlive) throws IOException {
final String content;
final String contentType;
if (callbackFunction != null) {
content = callbackFunction + "(" + iContent + ")";
contentType = "text/javascript";
} else {
content = iContent != null ? iContent.toString() : null;
contentType = iContentType;
}
final boolean empty = content == null || content.length() == 0;
writeStatus(empty && iCode == 200 ? 204 : iCode, iReason);
writeHeaders(contentType, iKeepAlive);
if (additionalHeaders != null)
for (String h : additionalHeaders)
writeLine(h);
if (iHeaders != null)
writeLine(iHeaders);
final String sessId = sessionId != null ? sessionId : "-";
writeLine("Set-Cookie: " + OHttpUtils.OSESSIONID + "=" + sessId + "; Path=/; HttpOnly");
final byte[] binaryContent = empty ? null : OBinaryProtocol.string2bytes(content);
writeLine(OHttpUtils.HEADER_CONTENT_LENGTH + (empty ? 0 : binaryContent.length));
writeLine(null);
if (binaryContent != null)
out.write(binaryContent);
out.flush();
}
public void writeStatus(final int iStatus, final String iReason) throws IOException {
writeLine(httpVersion + " " + iStatus + " " + iReason);
}
public void writeHeaders(final String iContentType) throws IOException {
writeHeaders(iContentType, true);
}
public void writeHeaders(final String iContentType, final boolean iKeepAlive) throws IOException {
if (headers != null)
writeLine(headers);
writeLine("Date: " + new Date());
writeLine("Content-Type: " + iContentType + "; charset=" + characterSet);
writeLine("Server: " + serverInfo);
writeLine("Connection: " + (iKeepAlive ? "Keep-Alive" : "close"));
// INCLUDE COMMON CUSTOM HEADERS
if (additionalHeaders != null)
for (String h : additionalHeaders)
writeLine(h);
}
public void writeLine(final String iContent) throws IOException {
writeContent(iContent);
out.write(OHttpUtils.EOL);
}
public void writeContent(final String iContent) throws IOException {
if (iContent != null)
out.write(OBinaryProtocol.string2bytes(iContent));
}
@SuppressWarnings("unchecked")
public void writeResult(Object iResult) throws InterruptedException, IOException {
if (iResult == null)
send(OHttpUtils.STATUS_OK_NOCONTENT_CODE, "", OHttpUtils.CONTENT_TEXT_PLAIN, null, null, true);
else {
if (OMultiValue.isMultiValue(iResult)
&& (OMultiValue.getSize(iResult) > 0 && !(OMultiValue.getFirstValue(iResult) instanceof OIdentifiable))) {
final List<OIdentifiable> resultSet = new ArrayList<OIdentifiable>();
resultSet.add(new ODocument().field("value", iResult));
iResult = resultSet.iterator();
} else if (iResult instanceof OIdentifiable) {
// CONVERT SIGLE VALUE IN A COLLECTION
final List<OIdentifiable> resultSet = new ArrayList<OIdentifiable>();
resultSet.add((OIdentifiable) iResult);
iResult = resultSet.iterator();
} else if (iResult instanceof Iterable<?>)
iResult = ((Iterable<OIdentifiable>) iResult).iterator();
else if (OMultiValue.isMultiValue(iResult))
iResult = OMultiValue.getMultiValueIterator(iResult);
else {
final List<OIdentifiable> resultSet = new ArrayList<OIdentifiable>();
resultSet.add(new ODocument().field("value", iResult));
iResult = resultSet.iterator();
}
if (iResult == null)
send(OHttpUtils.STATUS_OK_NOCONTENT_CODE, "", OHttpUtils.CONTENT_TEXT_PLAIN, null, null, true);
else if (iResult instanceof Iterator<?>)
writeRecords((Iterator<OIdentifiable>) iResult);
}
}
public void writeRecords(final Iterable<OIdentifiable> iRecords) throws IOException {
if (iRecords == null)
return;
writeRecords(iRecords.iterator(), null);
}
public void writeRecords(final Iterable<OIdentifiable> iRecords, final String iFetchPlan) throws IOException {
if (iRecords == null)
return;
writeRecords(iRecords.iterator(), iFetchPlan);
}
public void writeRecords(final Iterator<OIdentifiable> iRecords) throws IOException {
writeRecords(iRecords, null);
}
public void writeRecords(final Iterator<OIdentifiable> iRecords, final String iFetchPlan) throws IOException {
if (iRecords == null)
return;
final StringWriter buffer = new StringWriter();
final OJSONWriter json = new OJSONWriter(buffer, JSON_FORMAT);
json.beginObject();
final String format = iFetchPlan != null ? JSON_FORMAT + ",fetchPlan:" + iFetchPlan : JSON_FORMAT;
// WRITE RECORDS
json.beginCollection(1, true, "result");
formatMultiValue(iRecords, buffer, format);
json.endCollection(1, true);
json.endObject();
send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, buffer.toString(), null);
}
public void formatMultiValue(final Iterator<OIdentifiable> iIterator, final StringWriter buffer, final String format) {
if (iIterator != null) {
int counter = 0;
String objectJson;
while (iIterator.hasNext()) {
final OIdentifiable rec = iIterator.next();
if (rec != null)
try {
objectJson = rec.getRecord().toJSON(format);
if (counter++ > 0)
buffer.append(", ");
buffer.append(objectJson);
} catch (Exception e) {
OLogManager.instance().error(this, "Error transforming record " + rec.getIdentity() + " to JSON", e);
}
}
}
}
public void writeRecord(final ORecord<?> iRecord) throws IOException {
writeRecord(iRecord, null);
}
public void writeRecord(final ORecord<?> iRecord, String iFetchPlan) throws IOException {
final String format = iFetchPlan != null ? JSON_FORMAT + ",fetchPlan:" + iFetchPlan : JSON_FORMAT;
if (iRecord != null)
send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, iRecord.toJSON(format), null);
}
public void sendStream(final int iCode, final String iReason, final String iContentType, final InputStream iContent,
final long iSize) throws IOException {
writeStatus(iCode, iReason);
writeHeaders(iContentType);
writeLine(OHttpUtils.HEADER_CONTENT_LENGTH + (iSize));
writeLine(null);
if (iContent != null) {
int b;
while ((b = iContent.read()) > -1)
out.write(b);
}
out.flush();
}
/**
* Stores additional headers to send
*
* @param iHeader
*/
public void setHeader(final String iHeader) {
headers = iHeader;
}
public OutputStream getOutputStream() {
return out;
}
public void flush() throws IOException {
out.flush();
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
|
server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/OHttpResponse.java
|
/*
* Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.server.network.protocol.http;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import com.orientechnologies.common.collection.OMultiValue;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.OBinaryProtocol;
import com.orientechnologies.orient.core.serialization.serializer.OJSONWriter;
/**
* Maintains information about current HTTP response.
*
* @author Luca Garulli
*
*/
public class OHttpResponse {
public static final String JSON_FORMAT = "type,indent:2,rid,version,attribSameRow,class";
public static final char[] URL_SEPARATOR = { '/' };
private final OutputStream out;
public final String httpVersion;
public String headers;
public String[] additionalHeaders;
public String characterSet;
public String contentType;
public String serverInfo;
public String sessionId;
public String callbackFunction;
public OHttpResponse(final OutputStream iOutStream, final String iHttpVersion, final String[] iAdditionalHeaders,
final String iResponseCharSet, final String iServerInfo, final String iSessionId, final String iCallbackFunction) {
out = iOutStream;
httpVersion = iHttpVersion;
additionalHeaders = iAdditionalHeaders;
characterSet = iResponseCharSet;
serverInfo = iServerInfo;
sessionId = iSessionId;
callbackFunction = iCallbackFunction;
}
public void send(final int iCode, final String iReason, final String iContentType, final Object iContent, final String iHeaders)
throws IOException {
send(iCode, iReason, iContentType, iContent, iHeaders, true);
}
public void send(final int iCode, final String iReason, final String iContentType, final Object iContent, final String iHeaders,
final boolean iKeepAlive) throws IOException {
final String content;
final String contentType;
if (callbackFunction != null) {
content = callbackFunction + "(" + iContent + ")";
contentType = "text/javascript";
} else {
content = iContent != null ? iContent.toString() : null;
contentType = iContentType;
}
final boolean empty = content == null || content.length() == 0;
writeStatus(empty && iCode == 200 ? 204 : iCode, iReason);
writeHeaders(contentType, iKeepAlive);
if (additionalHeaders != null)
for (String h : additionalHeaders)
writeLine(h);
if (iHeaders != null)
writeLine(iHeaders);
final String sessId = sessionId != null ? sessionId : "-";
writeLine("Set-Cookie: " + OHttpUtils.OSESSIONID + "=" + sessId + "; Path=/; HttpOnly");
final byte[] binaryContent = empty ? null : OBinaryProtocol.string2bytes(content);
writeLine(OHttpUtils.HEADER_CONTENT_LENGTH + (empty ? 0 : binaryContent.length));
writeLine(null);
if (binaryContent != null)
out.write(binaryContent);
out.flush();
}
public void writeStatus(final int iStatus, final String iReason) throws IOException {
writeLine(httpVersion + " " + iStatus + " " + iReason);
}
public void writeHeaders(final String iContentType) throws IOException {
writeHeaders(iContentType, true);
}
public void writeHeaders(final String iContentType, final boolean iKeepAlive) throws IOException {
if (headers != null)
writeLine(headers);
writeLine("Date: " + new Date());
writeLine("Content-Type: " + iContentType + "; charset=" + characterSet);
writeLine("Server: " + serverInfo);
writeLine("Connection: " + (iKeepAlive ? "Keep-Alive" : "close"));
// INCLUDE COMMON CUSTOM HEADERS
if (additionalHeaders != null)
for (String h : additionalHeaders)
writeLine(h);
}
public void writeLine(final String iContent) throws IOException {
writeContent(iContent);
out.write(OHttpUtils.EOL);
}
public void writeContent(final String iContent) throws IOException {
if (iContent != null)
out.write(OBinaryProtocol.string2bytes(iContent));
}
@SuppressWarnings("unchecked")
public void writeResult(Object iResult) throws InterruptedException, IOException {
if (iResult == null)
send(OHttpUtils.STATUS_OK_NOCONTENT_CODE, "", OHttpUtils.CONTENT_TEXT_PLAIN, null, null, true);
else {
if (iResult instanceof Collection<?>) {
if (!((Collection<?>) iResult).isEmpty() && !(((Collection<?>) iResult).iterator().next() instanceof OIdentifiable))
iResult = new ODocument().field("result", iResult);
}
if (iResult instanceof OIdentifiable) {
// CONVERT SIGLE VLUE IN A COLLECTION
final List<OIdentifiable> resultSet = new ArrayList<OIdentifiable>();
resultSet.add((OIdentifiable) iResult);
iResult = resultSet.iterator();
}
if (iResult instanceof Iterable<?>)
iResult = ((Iterable<OIdentifiable>) iResult).iterator();
else if (iResult.getClass().isArray())
iResult = OMultiValue.getMultiValueIterator(iResult);
if (iResult instanceof Iterator<?>)
writeRecords((Iterator<OIdentifiable>) iResult);
else if (iResult == null || iResult instanceof Integer)
send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_TEXT_PLAIN, iResult, null);
else {
if (contentType == null)
contentType = OHttpUtils.CONTENT_TEXT_PLAIN;
send(OHttpUtils.STATUS_OK_CODE, "OK", contentType, iResult.toString(), null);
}
}
}
public void writeRecords(final Iterable<OIdentifiable> iRecords) throws IOException {
if (iRecords == null)
return;
writeRecords(iRecords.iterator(), null);
}
public void writeRecords(final Iterable<OIdentifiable> iRecords, final String iFetchPlan) throws IOException {
if (iRecords == null)
return;
writeRecords(iRecords.iterator(), iFetchPlan);
}
public void writeRecords(final Iterator<OIdentifiable> iRecords) throws IOException {
writeRecords(iRecords, null);
}
public void writeRecords(final Iterator<OIdentifiable> iRecords, final String iFetchPlan) throws IOException {
if (iRecords == null)
return;
final StringWriter buffer = new StringWriter();
final OJSONWriter json = new OJSONWriter(buffer, JSON_FORMAT);
json.beginObject();
final String format = iFetchPlan != null ? JSON_FORMAT + ",fetchPlan:" + iFetchPlan : JSON_FORMAT;
// WRITE RECORDS
json.beginCollection(1, true, "result");
formatMultiValue(iRecords, buffer, format);
json.endCollection(1, true);
json.endObject();
send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, buffer.toString(), null);
}
public void formatMultiValue(final Iterator<OIdentifiable> iIterator, final StringWriter buffer, final String format) {
if (iIterator != null) {
int counter = 0;
String objectJson;
while (iIterator.hasNext()) {
final OIdentifiable rec = iIterator.next();
if (rec != null)
try {
objectJson = rec.getRecord().toJSON(format);
if (counter++ > 0)
buffer.append(", ");
buffer.append(objectJson);
} catch (Exception e) {
OLogManager.instance().error(this, "Error transforming record " + rec.getIdentity() + " to JSON", e);
}
}
}
}
public void writeRecord(final ORecord<?> iRecord) throws IOException {
writeRecord(iRecord, null);
}
public void writeRecord(final ORecord<?> iRecord, String iFetchPlan) throws IOException {
final String format = iFetchPlan != null ? JSON_FORMAT + ",fetchPlan:" + iFetchPlan : JSON_FORMAT;
if (iRecord != null)
send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, iRecord.toJSON(format), null);
}
public void sendStream(final int iCode, final String iReason, final String iContentType, final InputStream iContent,
final long iSize) throws IOException {
writeStatus(iCode, iReason);
writeHeaders(iContentType);
writeLine(OHttpUtils.HEADER_CONTENT_LENGTH + (iSize));
writeLine(null);
if (iContent != null) {
int b;
while ((b = iContent.read()) > -1)
out.write(b);
}
out.flush();
}
/**
* Stores additional headers to send
*
* @param iHeader
*/
public void setHeader(final String iHeader) {
headers = iHeader;
}
public OutputStream getOutputStream() {
return out;
}
public void flush() throws IOException {
out.flush();
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
|
Fixed issue 1150 about Not returning proper JSON response when gremlin query results in 1 string using REST
git-svn-id: 9ddf022f45b579842a47abc018ed2b18cdc52108@7122 3625ad7b-9c83-922f-a72b-73d79161f2ea
|
server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/OHttpResponse.java
|
Fixed issue 1150 about Not returning proper JSON response when gremlin query results in 1 string using REST
|
|
Java
|
apache-2.0
|
67319fdf756f7ecbb69453d508ba2751a3a40b2f
| 0
|
cauchymop/goblob,cauchymop/goblob,cauchymop/goblob
|
package com.cauchymop.goblob.ui;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import com.cauchymop.goblob.R;
import com.cauchymop.goblob.model.AvatarManager;
import com.cauchymop.goblob.model.GameMoveSerializer;
import com.cauchymop.goblob.model.GoGame;
import com.cauchymop.goblob.model.GoPlayer;
import com.google.android.gms.games.GamesClient;
import com.google.android.gms.games.Player;
import com.google.android.gms.games.multiplayer.realtime.RoomConfig;
import com.google.android.gms.games.multiplayer.turnbased.OnTurnBasedMatchInitiatedListener;
import com.google.android.gms.games.multiplayer.turnbased.OnTurnBasedMatchUpdateReceivedListener;
import com.google.android.gms.games.multiplayer.turnbased.OnTurnBasedMatchUpdatedListener;
import com.google.android.gms.games.multiplayer.turnbased.TurnBasedMatch;
import com.google.android.gms.games.multiplayer.turnbased.TurnBasedMatchConfig;
import com.google.example.games.basegameutils.BaseGameActivity;
import java.util.ArrayList;
import static com.cauchymop.goblob.model.Player.PlayerType;
public class MainActivity extends BaseGameActivity implements OnTurnBasedMatchInitiatedListener,
OnTurnBasedMatchUpdatedListener, OnTurnBasedMatchUpdateReceivedListener {
public static final int REQUEST_ACHIEVEMENTS = 1;
public static final int SELECT_PLAYER = 2;
public static final int CHECK_MATCHES = 3;
private static final String TAG = MainActivity.class.getName();
private int boardSize = 9;
private AvatarManager avatarManager = new AvatarManager();
private GameMoveSerializer<GoGame> gameMoveSerializer = new GameMoveSerializer<GoGame>();
private TurnBasedMatch turnBasedMatch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (getSupportFragmentManager().getBackStackEntryCount() <= 0) {
HomeFragment homeFragment = new HomeFragment();
displayFragment(homeFragment, false);
}
}
@Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
if (responseCode != Activity.RESULT_OK) {
Log.w(TAG, "*** select players UI cancelled, " + responseCode);
return;
}
switch (requestCode) {
case SELECT_PLAYER:
handleSelectPlayersResult(intent);
break;
case CHECK_MATCHES:
handleMatchSelected(intent);
break;
}
}
private void handleMatchSelected(Intent intent) {
Log.d(TAG, "handleMatchSelected.");
turnBasedMatch = intent.getParcelableExtra(GamesClient.EXTRA_TURN_BASED_MATCH);
startGame(turnBasedMatch);
}
@Override
public void onSignInFailed() {
invalidateOptionsMenu();
getCurrentFragment().onSignInFailed();
}
@Override
public void onSignInSucceeded() {
invalidateOptionsMenu();
getCurrentFragment().onSignInSucceeded();
if (mHelper.getTurnBasedMatch() != null) {
Log.d(TAG, "Found match");
// prevent screen from sleeping during handshake
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
turnBasedMatch = mHelper.getTurnBasedMatch();
startGame(createGoGame(turnBasedMatch));
}
getGamesClient().registerMatchUpdateListener(this);
}
@Override
protected void signOut() {
super.signOut();
onSignOut();
}
@Override
protected boolean isSignedIn() {
return super.isSignedIn();
}
@Override
protected GamesClient getGamesClient() {
return super.getGamesClient();
}
private GoBlobBaseFragment getCurrentFragment() {
return (GoBlobBaseFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container);
}
private void displayFragment(GoBlobBaseFragment fragment, boolean addToBackStack) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
ft.replace(R.id.fragment_container, fragment);
// Add the transaction to the back stack if needed.
if (addToBackStack) {
ft.addToBackStack(null);
}
// Commit the transaction
ft.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game_menu, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean signedIn = isSignedIn();
menu.setGroupVisible(R.id.group_signedIn, signedIn);
menu.setGroupVisible(R.id.group_signedOut, !signedIn);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_achievements) {
startActivityForResult(getGamesClient().getAchievementsIntent(), REQUEST_ACHIEVEMENTS);
return true;
} else if (id == R.id.menu_signout) {
signOut();
} else if (id == R.id.menu_signin) {
beginUserInitiatedSignIn();
}
return false;
}
@Override
protected void beginUserInitiatedSignIn() {
super.beginUserInitiatedSignIn();
}
public void onSignOut() {
invalidateOptionsMenu();
getCurrentFragment().onSignOut();
}
public void signOut(View v) {
signOut();
}
public void startChallenges(View v) {
}
public void startFreeGame(View v) {
PlayerChoiceFragment playerChoiceFragment = new PlayerChoiceFragment();
displayFragment(playerChoiceFragment, true);
}
public void checkMatches(View v) {
Intent checkMatchesIntent = getGamesClient().getMatchInboxIntent();
startActivityForResult(checkMatchesIntent, CHECK_MATCHES);
}
public void configureGame(GoPlayer opponentPlayer, int boardSize) {
this.boardSize = boardSize;
if (opponentPlayer.getType().isRemote()) {
Intent selectPlayersIntent = getGamesClient().getSelectPlayersIntent(1, 1);
startActivityForResult(selectPlayersIntent, SELECT_PLAYER);
} else {
displayGameConfigurationScreen(opponentPlayer, boardSize);
}
}
public void displayGameConfigurationScreen(GoPlayer opponentPlayer, int boardSize) {
GameConfigurationFragment gameConfigurationFragment = GameConfigurationFragment.newInstance(opponentPlayer, boardSize);
displayFragment(gameConfigurationFragment, true);
}
public void startGame(TurnBasedMatch turnBasedMatch) {
startGame(createGoGame(turnBasedMatch));
}
public void startGame(GoGame goGame) {
GameFragment gameFragment = GameFragment.newInstance(goGame);
displayFragment(gameFragment, true);
}
public void giveTurn(GoGame gogame) {
getGamesClient().takeTurn(this, turnBasedMatch.getMatchId(),
gameMoveSerializer.serialize(gogame), getOpponentId(turnBasedMatch, getMyId(turnBasedMatch)));
}
public AvatarManager getAvatarManager() {
return avatarManager;
}
private void handleSelectPlayersResult(Intent intent) {
Log.d(TAG, "Select players UI succeeded.");
// get the invitee list
final ArrayList<String> invitees = intent.getStringArrayListExtra(GamesClient.EXTRA_PLAYERS);
Log.d(TAG, "Invitee count: " + invitees.size());
// get the automatch criteria
Bundle autoMatchCriteria = null;
int minAutoMatchPlayers = intent.getIntExtra(GamesClient.EXTRA_MIN_AUTOMATCH_PLAYERS, 0);
int maxAutoMatchPlayers = intent.getIntExtra(GamesClient.EXTRA_MAX_AUTOMATCH_PLAYERS, 0);
if (minAutoMatchPlayers > 0 || maxAutoMatchPlayers > 0) {
autoMatchCriteria = RoomConfig.createAutoMatchCriteria(
minAutoMatchPlayers, maxAutoMatchPlayers, 0);
Log.d(TAG, "Automatch criteria: " + autoMatchCriteria);
}
// create game
TurnBasedMatchConfig tbmc = TurnBasedMatchConfig.builder()
.addInvitedPlayers(invitees)
.setVariant(boardSize)
.setAutoMatchCriteria(autoMatchCriteria).build();
// kick the match off
getGamesClient().createTurnBasedMatch(this, tbmc);
}
@Override
public void onTurnBasedMatchInitiated(int statusCode, TurnBasedMatch turnBasedMatch) {
Log.d(TAG, "onTurnBasedMatchInitiated " + statusCode);
if (statusCode != GamesClient.STATUS_OK) {
return;
}
this.turnBasedMatch = turnBasedMatch;
GoGame gogame = createGoGame(turnBasedMatch);
if (turnBasedMatch.getData() == null) {
Log.d(TAG, "getData is null, saving a new game");
getGamesClient().takeTurn(this, turnBasedMatch.getMatchId(),
gameMoveSerializer.serialize(gogame), getMyId(turnBasedMatch));
}
// TODO: start activity
Log.d(TAG, "Game created, starting game activity...");
startGame(gogame);
}
private GoGame createGoGame(TurnBasedMatch turnBasedMatch) {
String myId = getMyId(turnBasedMatch);
String opponentId = getOpponentId(turnBasedMatch, myId);
for (String participantId : turnBasedMatch.getParticipantIds()) {
Log.i(TAG, String.format(" participant %s: player %s", participantId,
turnBasedMatch.getParticipant(participantId).getPlayer().getPlayerId()));
}
GoGame gogame = new GoGame(turnBasedMatch.getVariant());
gameMoveSerializer.deserializeTo(turnBasedMatch.getData(), gogame);
GoPlayer myPlayer = createGoPlayer(turnBasedMatch, myId, PlayerType.HUMAN_LOCAL);
GoPlayer opponentPlayer =
createGoPlayer(turnBasedMatch, opponentId, PlayerType.HUMAN_REMOTE_FRIEND);
if (gogame.getMoveHistory().size() % 2 == 0) {
gogame.setBlackPlayer(myPlayer);
gogame.setWhitePlayer(opponentPlayer);
} else {
gogame.setBlackPlayer(opponentPlayer);
gogame.setWhitePlayer(myPlayer);
}
return gogame;
}
private String getOpponentId(TurnBasedMatch turnBasedMatch, String id) {
for (String participantId : turnBasedMatch.getParticipantIds()) {
if (!participantId.equals(id)) {
return participantId;
}
}
return null;
}
private String getMyId(TurnBasedMatch turnBasedMatch) {
return turnBasedMatch.getParticipantId(getGamesClient().getCurrentPlayerId());
}
private GoPlayer createGoPlayer(TurnBasedMatch turnBasedMatch, String creatorId,
PlayerType humanLocal) {
Player player = turnBasedMatch.getParticipant(creatorId).getPlayer();
GoPlayer goPlayer = new GoPlayer(humanLocal, player.getDisplayName());
avatarManager.setAvatarUri(getApplicationContext(), goPlayer, player.getIconImageUri());
return goPlayer;
}
@Override
public void onTurnBasedMatchUpdated(int statusCode, TurnBasedMatch turnBasedMatch) {
Log.d(TAG, "onTurnBasedMatchUpdated " + statusCode);
if (turnBasedMatch.getTurnStatus() == TurnBasedMatch.MATCH_TURN_STATUS_MY_TURN) {
startGame(turnBasedMatch);
}
}
@Override
public void onTurnBasedMatchReceived(TurnBasedMatch turnBasedMatch) {
Log.d(TAG, "onTurnBasedMatchReceived");
startGame(turnBasedMatch);
}
@Override
public void onTurnBasedMatchRemoved(String s) {
}
}
|
goblob/src/main/com/cauchymop/goblob/ui/MainActivity.java
|
package com.cauchymop.goblob.ui;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import com.cauchymop.goblob.R;
import com.cauchymop.goblob.model.AvatarManager;
import com.cauchymop.goblob.model.GameMoveSerializer;
import com.cauchymop.goblob.model.GoGame;
import com.cauchymop.goblob.model.GoPlayer;
import com.google.android.gms.games.GamesClient;
import com.google.android.gms.games.Player;
import com.google.android.gms.games.multiplayer.realtime.RoomConfig;
import com.google.android.gms.games.multiplayer.turnbased.OnTurnBasedMatchInitiatedListener;
import com.google.android.gms.games.multiplayer.turnbased.OnTurnBasedMatchUpdateReceivedListener;
import com.google.android.gms.games.multiplayer.turnbased.OnTurnBasedMatchUpdatedListener;
import com.google.android.gms.games.multiplayer.turnbased.TurnBasedMatch;
import com.google.android.gms.games.multiplayer.turnbased.TurnBasedMatchConfig;
import com.google.example.games.basegameutils.BaseGameActivity;
import java.util.ArrayList;
import static com.cauchymop.goblob.model.Player.PlayerType;
public class MainActivity extends BaseGameActivity implements OnTurnBasedMatchInitiatedListener,
OnTurnBasedMatchUpdatedListener, OnTurnBasedMatchUpdateReceivedListener {
public static final int REQUEST_ACHIEVEMENTS = 1;
public static final int SELECT_PLAYER = 2;
public static final int CHECK_MATCHES = 3;
private static final String TAG = MainActivity.class.getName();
private int boardSize = 9;
private AvatarManager avatarManager = new AvatarManager();
private GameMoveSerializer<GoGame> gameMoveSerializer = new GameMoveSerializer<GoGame>();
private TurnBasedMatch turnBasedMatch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (getSupportFragmentManager().getBackStackEntryCount() <= 0) {
HomeFragment homeFragment = new HomeFragment();
displayFragment(homeFragment, false);
}
}
@Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
if (responseCode != Activity.RESULT_OK) {
Log.w(TAG, "*** select players UI cancelled, " + responseCode);
return;
}
switch (requestCode) {
case SELECT_PLAYER:
handleSelectPlayersResult(intent);
break;
case CHECK_MATCHES:
handleMatchSelected(intent);
break;
}
}
private void handleMatchSelected(Intent intent) {
Log.d(TAG, "handleMatchSelected.");
TurnBasedMatch turnBasedMatch = intent.getParcelableExtra(GamesClient.EXTRA_TURN_BASED_MATCH);
startGame(turnBasedMatch);
}
@Override
public void onSignInFailed() {
invalidateOptionsMenu();
getCurrentFragment().onSignInFailed();
}
@Override
public void onSignInSucceeded() {
invalidateOptionsMenu();
getCurrentFragment().onSignInSucceeded();
if (mHelper.getTurnBasedMatch() != null) {
Log.d(TAG, "Found match");
// prevent screen from sleeping during handshake
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
turnBasedMatch = mHelper.getTurnBasedMatch();
startGame(createGoGame(turnBasedMatch));
}
getGamesClient().registerMatchUpdateListener(this);
}
@Override
protected void signOut() {
super.signOut();
onSignOut();
}
@Override
protected boolean isSignedIn() {
return super.isSignedIn();
}
@Override
protected GamesClient getGamesClient() {
return super.getGamesClient();
}
private GoBlobBaseFragment getCurrentFragment() {
return (GoBlobBaseFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container);
}
private void displayFragment(GoBlobBaseFragment fragment, boolean addToBackStack) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
ft.replace(R.id.fragment_container, fragment);
// Add the transaction to the back stack if needed.
if (addToBackStack) {
ft.addToBackStack(null);
}
// Commit the transaction
ft.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game_menu, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean signedIn = isSignedIn();
menu.setGroupVisible(R.id.group_signedIn, signedIn);
menu.setGroupVisible(R.id.group_signedOut, !signedIn);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_achievements) {
startActivityForResult(getGamesClient().getAchievementsIntent(), REQUEST_ACHIEVEMENTS);
return true;
} else if (id == R.id.menu_signout) {
signOut();
} else if (id == R.id.menu_signin) {
beginUserInitiatedSignIn();
}
return false;
}
@Override
protected void beginUserInitiatedSignIn() {
super.beginUserInitiatedSignIn();
}
public void onSignOut() {
invalidateOptionsMenu();
getCurrentFragment().onSignOut();
}
public void signOut(View v) {
signOut();
}
public void startChallenges(View v) {
}
public void startFreeGame(View v) {
PlayerChoiceFragment playerChoiceFragment = new PlayerChoiceFragment();
displayFragment(playerChoiceFragment, true);
}
public void checkMatches(View v) {
Intent checkMatchesIntent = getGamesClient().getMatchInboxIntent();
startActivityForResult(checkMatchesIntent, CHECK_MATCHES);
}
public void configureGame(GoPlayer opponentPlayer, int boardSize) {
this.boardSize = boardSize;
if (opponentPlayer.getType().isRemote()) {
Intent selectPlayersIntent = getGamesClient().getSelectPlayersIntent(1, 1);
startActivityForResult(selectPlayersIntent, SELECT_PLAYER);
} else {
displayGameConfigurationScreen(opponentPlayer, boardSize);
}
}
public void displayGameConfigurationScreen(GoPlayer opponentPlayer, int boardSize) {
GameConfigurationFragment gameConfigurationFragment = GameConfigurationFragment.newInstance(opponentPlayer, boardSize);
displayFragment(gameConfigurationFragment, true);
}
public void startGame(TurnBasedMatch turnBasedMatch) {
startGame(createGoGame(turnBasedMatch));
}
public void startGame(GoGame goGame) {
GameFragment gameFragment = GameFragment.newInstance(goGame);
displayFragment(gameFragment, true);
}
public void giveTurn(GoGame gogame) {
getGamesClient().takeTurn(this, turnBasedMatch.getMatchId(),
gameMoveSerializer.serialize(gogame), getOpponentId(turnBasedMatch, getMyId(turnBasedMatch)));
}
public AvatarManager getAvatarManager() {
return avatarManager;
}
private void handleSelectPlayersResult(Intent intent) {
Log.d(TAG, "Select players UI succeeded.");
// get the invitee list
final ArrayList<String> invitees = intent.getStringArrayListExtra(GamesClient.EXTRA_PLAYERS);
Log.d(TAG, "Invitee count: " + invitees.size());
// get the automatch criteria
Bundle autoMatchCriteria = null;
int minAutoMatchPlayers = intent.getIntExtra(GamesClient.EXTRA_MIN_AUTOMATCH_PLAYERS, 0);
int maxAutoMatchPlayers = intent.getIntExtra(GamesClient.EXTRA_MAX_AUTOMATCH_PLAYERS, 0);
if (minAutoMatchPlayers > 0 || maxAutoMatchPlayers > 0) {
autoMatchCriteria = RoomConfig.createAutoMatchCriteria(
minAutoMatchPlayers, maxAutoMatchPlayers, 0);
Log.d(TAG, "Automatch criteria: " + autoMatchCriteria);
}
// create game
TurnBasedMatchConfig tbmc = TurnBasedMatchConfig.builder()
.addInvitedPlayers(invitees)
.setVariant(boardSize)
.setAutoMatchCriteria(autoMatchCriteria).build();
// kick the match off
getGamesClient().createTurnBasedMatch(this, tbmc);
}
@Override
public void onTurnBasedMatchInitiated(int statusCode, TurnBasedMatch turnBasedMatch) {
Log.d(TAG, "onTurnBasedMatchInitiated " + statusCode);
if (statusCode != GamesClient.STATUS_OK) {
return;
}
this.turnBasedMatch = turnBasedMatch;
GoGame gogame = createGoGame(turnBasedMatch);
if (turnBasedMatch.getData() == null) {
Log.d(TAG, "getData is null, saving a new game");
getGamesClient().takeTurn(this, turnBasedMatch.getMatchId(),
gameMoveSerializer.serialize(gogame), getMyId(turnBasedMatch));
}
// TODO: start activity
Log.d(TAG, "Game created, starting game activity...");
startGame(gogame);
}
private GoGame createGoGame(TurnBasedMatch turnBasedMatch) {
String myId = getMyId(turnBasedMatch);
String opponentId = getOpponentId(turnBasedMatch, myId);
for (String participantId : turnBasedMatch.getParticipantIds()) {
Log.i(TAG, String.format(" participant %s: player %s", participantId,
turnBasedMatch.getParticipant(participantId).getPlayer().getPlayerId()));
}
GoGame gogame = new GoGame(turnBasedMatch.getVariant());
gameMoveSerializer.deserializeTo(turnBasedMatch.getData(), gogame);
GoPlayer myPlayer = createGoPlayer(turnBasedMatch, myId, PlayerType.HUMAN_LOCAL);
GoPlayer opponentPlayer =
createGoPlayer(turnBasedMatch, opponentId, PlayerType.HUMAN_REMOTE_FRIEND);
if (gogame.getMoveHistory().size() % 2 == 0) {
gogame.setBlackPlayer(myPlayer);
gogame.setWhitePlayer(opponentPlayer);
} else {
gogame.setBlackPlayer(opponentPlayer);
gogame.setWhitePlayer(myPlayer);
}
return gogame;
}
private String getOpponentId(TurnBasedMatch turnBasedMatch, String id) {
for (String participantId : turnBasedMatch.getParticipantIds()) {
if (!participantId.equals(id)) {
return participantId;
}
}
return null;
}
private String getMyId(TurnBasedMatch turnBasedMatch) {
return turnBasedMatch.getParticipantId(getGamesClient().getCurrentPlayerId());
}
private GoPlayer createGoPlayer(TurnBasedMatch turnBasedMatch, String creatorId,
PlayerType humanLocal) {
Player player = turnBasedMatch.getParticipant(creatorId).getPlayer();
GoPlayer goPlayer = new GoPlayer(humanLocal, player.getDisplayName());
avatarManager.setAvatarUri(getApplicationContext(), goPlayer, player.getIconImageUri());
return goPlayer;
}
@Override
public void onTurnBasedMatchUpdated(int statusCode, TurnBasedMatch turnBasedMatch) {
Log.d(TAG, "onTurnBasedMatchUpdated " + statusCode);
if (turnBasedMatch.getTurnStatus() == TurnBasedMatch.MATCH_TURN_STATUS_MY_TURN) {
startGame(turnBasedMatch);
}
}
@Override
public void onTurnBasedMatchReceived(TurnBasedMatch turnBasedMatch) {
Log.d(TAG, "onTurnBasedMatchReceived");
startGame(turnBasedMatch);
}
@Override
public void onTurnBasedMatchRemoved(String s) {
}
}
|
Fixed: the turnBasedMatch was not stored, leading to an NPE.
|
goblob/src/main/com/cauchymop/goblob/ui/MainActivity.java
|
Fixed: the turnBasedMatch was not stored, leading to an NPE.
|
|
Java
|
apache-2.0
|
7b9e9858335651edf57335a92ebf178433097220
| 0
|
joansmith/jackrabbit-oak,bdelacretaz/jackrabbit-oak,kwin/jackrabbit-oak,alexkli/jackrabbit-oak,leftouterjoin/jackrabbit-oak,code-distillery/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,ieb/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,meggermo/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,alexkli/jackrabbit-oak,kwin/jackrabbit-oak,stillalex/jackrabbit-oak,rombert/jackrabbit-oak,afilimonov/jackrabbit-oak,code-distillery/jackrabbit-oak,catholicon/jackrabbit-oak,francescomari/jackrabbit-oak,bdelacretaz/jackrabbit-oak,chetanmeh/jackrabbit-oak,leftouterjoin/jackrabbit-oak,davidegiannella/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,chetanmeh/jackrabbit-oak,joansmith/jackrabbit-oak,mduerig/jackrabbit-oak,alexkli/jackrabbit-oak,anchela/jackrabbit-oak,bdelacretaz/jackrabbit-oak,afilimonov/jackrabbit-oak,meggermo/jackrabbit-oak,leftouterjoin/jackrabbit-oak,afilimonov/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,francescomari/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,leftouterjoin/jackrabbit-oak,meggermo/jackrabbit-oak,stillalex/jackrabbit-oak,alexkli/jackrabbit-oak,yesil/jackrabbit-oak,yesil/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,kwin/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,yesil/jackrabbit-oak,alexparvulescu/jackrabbit-oak,alexparvulescu/jackrabbit-oak,catholicon/jackrabbit-oak,alexkli/jackrabbit-oak,davidegiannella/jackrabbit-oak,meggermo/jackrabbit-oak,kwin/jackrabbit-oak,yesil/jackrabbit-oak,chetanmeh/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,code-distillery/jackrabbit-oak,joansmith/jackrabbit-oak,alexparvulescu/jackrabbit-oak,anchela/jackrabbit-oak,francescomari/jackrabbit-oak,alexparvulescu/jackrabbit-oak,rombert/jackrabbit-oak,francescomari/jackrabbit-oak,mduerig/jackrabbit-oak,mduerig/jackrabbit-oak,anchela/jackrabbit-oak,catholicon/jackrabbit-oak,chetanmeh/jackrabbit-oak,joansmith/jackrabbit-oak,meggermo/jackrabbit-oak,stillalex/jackrabbit-oak,alexparvulescu/jackrabbit-oak,francescomari/jackrabbit-oak,tripodsan/jackrabbit-oak,davidegiannella/jackrabbit-oak,afilimonov/jackrabbit-oak,tripodsan/jackrabbit-oak,mduerig/jackrabbit-oak,ieb/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,davidegiannella/jackrabbit-oak,code-distillery/jackrabbit-oak,davidegiannella/jackrabbit-oak,mduerig/jackrabbit-oak,catholicon/jackrabbit-oak,ieb/jackrabbit-oak,anchela/jackrabbit-oak,kwin/jackrabbit-oak,joansmith/jackrabbit-oak,tripodsan/jackrabbit-oak,code-distillery/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,stillalex/jackrabbit-oak,stillalex/jackrabbit-oak,rombert/jackrabbit-oak,catholicon/jackrabbit-oak,rombert/jackrabbit-oak,anchela/jackrabbit-oak,ieb/jackrabbit-oak,chetanmeh/jackrabbit-oak,bdelacretaz/jackrabbit-oak,tripodsan/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.index.solr.query;
import java.util.Collection;
import javax.annotation.CheckForNull;
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.oak.api.PropertyValue;
import org.apache.jackrabbit.oak.plugins.index.aggregate.NodeAggregator;
import org.apache.jackrabbit.oak.plugins.index.solr.configuration.OakSolrConfiguration;
import org.apache.jackrabbit.oak.query.QueryImpl;
import org.apache.jackrabbit.oak.query.fulltext.FullTextAnd;
import org.apache.jackrabbit.oak.query.fulltext.FullTextExpression;
import org.apache.jackrabbit.oak.query.fulltext.FullTextOr;
import org.apache.jackrabbit.oak.query.fulltext.FullTextTerm;
import org.apache.jackrabbit.oak.query.fulltext.FullTextVisitor;
import org.apache.jackrabbit.oak.spi.query.Cursor;
import org.apache.jackrabbit.oak.spi.query.Filter;
import org.apache.jackrabbit.oak.spi.query.IndexRow;
import org.apache.jackrabbit.oak.spi.query.PropertyValues;
import org.apache.jackrabbit.oak.spi.query.QueryIndex;
import org.apache.jackrabbit.oak.spi.query.QueryIndex.FulltextQueryIndex;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.jackrabbit.oak.commons.PathUtils.getName;
/**
* A Solr based {@link QueryIndex}
*/
public class SolrQueryIndex implements FulltextQueryIndex {
private static final String NATIVE_SOLR_QUERY = "native*solr";
private static final String NATIVE_LUCENE_QUERY = "native*lucene";
public static final String TYPE = "solr";
private final Logger log = LoggerFactory.getLogger(SolrQueryIndex.class);
private final String name;
private final SolrServer solrServer;
private final OakSolrConfiguration configuration;
private final NodeAggregator aggregator;
public SolrQueryIndex(String name, SolrServer solrServer, OakSolrConfiguration configuration) {
this.name = name;
this.solrServer = solrServer;
this.configuration = configuration;
// TODO this index should support aggregation in the same way as the Lucene index
this.aggregator = null;
}
@Override
public String getIndexName() {
return name;
}
@Override
public double getCost(Filter filter, NodeState root) {
if (filter.getFullTextConstraint() == null && filter.getFulltextConditions() == null ||
(filter.getPropertyRestrictions() != null && filter.getPropertyRestrictions().size() == 1 && filter.getPropertyRestriction(JcrConstants.JCR_UUID) != null)) {
return Double.POSITIVE_INFINITY;
}
int cost = 10;
Collection<Filter.PropertyRestriction> restrictions = filter.getPropertyRestrictions();
if (restrictions != null) {
cost /= 5;
}
if (filter.getPathRestriction() != null) {
cost /= 2;
}
return cost;
}
@Override
public String getPlan(Filter filter, NodeState nodeState) {
return getQuery(filter).toString();
}
private SolrQuery getQuery(Filter filter) {
SolrQuery solrQuery = new SolrQuery();
setDefaults(solrQuery);
StringBuilder queryBuilder = new StringBuilder();
if (filter.getFullTextConstraint() != null) {
queryBuilder.append(getFullTextQuery(filter.getFullTextConstraint()));
queryBuilder.append(' ');
} else if (filter.getFulltextConditions() != null) {
Collection<String> fulltextConditions = filter.getFulltextConditions();
for (String fulltextCondition : fulltextConditions) {
queryBuilder.append(fulltextCondition).append(" ");
}
}
Collection<Filter.PropertyRestriction> propertyRestrictions = filter.getPropertyRestrictions();
if (propertyRestrictions != null && !propertyRestrictions.isEmpty()) {
for (Filter.PropertyRestriction pr : propertyRestrictions) {
// native query support
if (NATIVE_SOLR_QUERY.equals(pr.propertyName) || NATIVE_LUCENE_QUERY.equals(pr.propertyName)) {
String nativeQueryString = String.valueOf(pr.first.getValue(pr.first.getType()));
if (isSupportedHttpRequest(nativeQueryString)) {
// pass through the native HTTP Solr request
String requestHandlerString = nativeQueryString.substring(0, nativeQueryString.indexOf('?'));
if (!"select".equals(requestHandlerString)) {
if (requestHandlerString.charAt(0) != '/') {
requestHandlerString = "/" + requestHandlerString;
}
solrQuery.setRequestHandler(requestHandlerString);
}
String parameterString = nativeQueryString.substring(nativeQueryString.indexOf('?') + 1);
for (String param : parameterString.split("&")) {
String[] kv = param.split("=");
if (kv.length != 2) {
throw new RuntimeException("Unparsable native HTTP Solr query");
} else {
if ("stream.body".equals(kv[0])) {
kv[0] = "q";
String mltFlString = "mlt.fl=";
int mltFlIndex = parameterString.indexOf(mltFlString);
if (mltFlIndex > -1) {
int beginIndex = mltFlIndex + mltFlString.length();
int endIndex = parameterString.indexOf('&', beginIndex);
String fields;
if (endIndex > beginIndex) {
fields = parameterString.substring(beginIndex, endIndex);
} else {
fields = parameterString.substring(beginIndex);
}
kv[1] = "_query_:\"{!dismax qf=" + fields + " q.op=OR}" + kv[1] + "\"";
}
}
solrQuery.setParam(kv[0], kv[1]);
}
}
return solrQuery; // every other restriction is not considered
} else {
queryBuilder.append(nativeQueryString);
}
} else {
if (pr.propertyName.contains("/")) {
// cannot handle child-level property restrictions
continue;
}
if ("rep:excerpt".equals(pr.propertyName)) {
continue;
}
String first = null;
if (pr.first != null) {
first = partialEscape(String.valueOf(pr.first.getValue(pr.first.getType()))).toString();
}
String last = null;
if (pr.last != null) {
last = partialEscape(String.valueOf(pr.last.getValue(pr.last.getType()))).toString();
}
String prField = configuration.getFieldForPropertyRestriction(pr);
CharSequence fieldName = partialEscape(prField != null ?
prField : pr.propertyName);
if ("jcr\\:path".equals(fieldName.toString())) {
queryBuilder.append(configuration.getPathField());
queryBuilder.append(':');
queryBuilder.append(first);
} else {
if (pr.first != null && pr.last != null && pr.first.equals(pr.last)) {
queryBuilder.append(fieldName).append(':');
queryBuilder.append(first);
} else if (pr.first == null && pr.last == null) {
if (!queryBuilder.toString().contains(fieldName + ":")) {
queryBuilder.append(fieldName).append(':');
queryBuilder.append('*');
}
} else if ((pr.first != null && pr.last == null) || (pr.last != null && pr.first == null) || (!pr.first.equals(pr.last))) {
// TODO : need to check if this works for all field types (most likely not!)
queryBuilder.append(fieldName).append(':');
queryBuilder.append(createRangeQuery(first, last, pr.firstIncluding, pr.lastIncluding));
} else if (pr.isLike) {
// TODO : the current parameter substitution is not expected to work well
queryBuilder.append(fieldName).append(':');
queryBuilder.append(partialEscape(String.valueOf(pr.first.getValue(pr.first.getType())).replace('%', '*').replace('_', '?')));
} else {
throw new RuntimeException("[unexpected!] not handled case");
}
}
}
queryBuilder.append(" ");
}
}
String[] pts = filter.getPrimaryTypes().toArray(new String[filter.getPrimaryTypes().size()]);
for (int i = 0; i < pts.length; i++) {
String pt = pts[i];
if (i == 0) {
queryBuilder.append("(");
}
if (i > 0 && i < pts.length) {
queryBuilder.append("OR ");
}
queryBuilder.append("jcr\\:primaryType").append(':').append(partialEscape(pt)).append(" ");
if (i == pts.length - 1) {
queryBuilder.append(")");
queryBuilder.append(' ');
}
}
Filter.PathRestriction pathRestriction = filter.getPathRestriction();
if (pathRestriction != null) {
String path = purgePath(filter);
String fieldName = configuration.getFieldForPathRestriction(pathRestriction);
if (fieldName != null) {
queryBuilder.append(fieldName);
queryBuilder.append(':');
queryBuilder.append(path);
}
}
if (queryBuilder.length() == 0) {
queryBuilder.append("*:*");
}
String escapedQuery = queryBuilder.toString();
solrQuery.setQuery(escapedQuery);
if (log.isDebugEnabled()) {
log.debug("JCR query {} has been converted to Solr query {}",
filter.getQueryStatement(), solrQuery.toString());
}
return solrQuery;
}
private String getFullTextQuery(FullTextExpression ft) {
final StringBuilder fullTextString = new StringBuilder();
ft.accept(new FullTextVisitor() {
@Override
public boolean visit(FullTextOr or) {
fullTextString.append('(');
for (int i = 0; i < or.list.size(); i++) {
if (i > 0 && i < or.list.size()) {
fullTextString.append(" OR ");
}
FullTextExpression e = or.list.get(i);
String orTerm = getFullTextQuery(e);
fullTextString.append(orTerm);
}
fullTextString.append(')');
fullTextString.append(' ');
return true;
}
@Override
public boolean visit(FullTextAnd and) {
fullTextString.append('(');
for (int i = 0; i < and.list.size(); i++) {
if (i > 0 && i < and.list.size()) {
fullTextString.append(" AND ");
}
FullTextExpression e = and.list.get(i);
String andTerm = getFullTextQuery(e);
fullTextString.append(andTerm);
}
fullTextString.append(')');
fullTextString.append(' ');
return true;
}
@Override
public boolean visit(FullTextTerm term) {
if (term.isNot()) {
fullTextString.append('-');
}
String p = term.getPropertyName();
if (p != null && p.indexOf('/') >= 0) {
p = getName(p);
}
if (p == null || "*".equals(p)) {
p = configuration.getCatchAllField();
}
fullTextString.append(partialEscape(p));
fullTextString.append(':');
String termText = term.getText();
if (termText.indexOf(' ') > 0) {
fullTextString.append('"');
}
fullTextString.append(termText.replace("/", "\\/").replace(":", "\\:"));
if (termText.indexOf(' ') > 0) {
fullTextString.append('"');
}
String boost = term.getBoost();
if (boost != null) {
fullTextString.append('^');
fullTextString.append(boost);
}
fullTextString.append(' ');
return true;
}
});
return fullTextString.toString();
}
private boolean isSupportedHttpRequest(String nativeQueryString) {
// the query string starts with ${supported-handler.selector}?
return nativeQueryString.matches("(mlt|query|select|get)\\\\?.*");
}
private void setDefaults(SolrQuery solrQuery) {
solrQuery.setParam("q.op", "AND");
solrQuery.setParam("fl", "* score");
String catchAllField = configuration.getCatchAllField();
if (catchAllField != null && catchAllField.length() > 0) {
solrQuery.setParam("df", catchAllField);
}
solrQuery.setParam("rows", String.valueOf(configuration.getRows()));
}
private static String createRangeQuery(String first, String last, boolean firstIncluding, boolean lastIncluding) {
// TODO : handle inclusion / exclusion of bounds
return "[" + (first != null ? first : "*") + " TO " + (last != null ? last : "*") + "]";
}
private static String purgePath(Filter filter) {
return partialEscape(filter.getPath()).toString();
}
// partially borrowed from SolrPluginUtils#partialEscape
private static CharSequence partialEscape(CharSequence s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\\' || c == '!' || c == '(' || c == ')' ||
c == ':' || c == '^' || c == '[' || c == ']' || c == '/' ||
c == '{' || c == '}' || c == '~' || c == '*' || c == '?' ||
c == '-' || c == ' ') {
sb.append('\\');
}
sb.append(c);
}
return sb;
}
@Override
public Cursor query(Filter filter, NodeState root) {
if (log.isDebugEnabled()) {
log.debug("converting filter {}", filter);
}
Cursor cursor;
try {
SolrQuery query = getQuery(filter);
if (log.isDebugEnabled()) {
log.debug("sending query {}", query);
}
QueryResponse queryResponse = solrServer.query(query);
if (log.isDebugEnabled()) {
log.debug("getting response {}", queryResponse);
}
cursor = new SolrCursor(queryResponse, query);
} catch (Exception e) {
throw new RuntimeException(e);
}
return cursor;
}
private class SolrCursor implements Cursor {
private SolrDocumentList results;
private SolrQuery query;
private int counter;
private int offset;
public SolrCursor(QueryResponse queryResponse, SolrQuery query) {
this.results = queryResponse.getResults();
this.counter = 0;
this.offset = 0;
this.query = query;
}
@Override
public boolean hasNext() {
return results != null && offset + counter < results.getNumFound();
}
@Override
public void remove() {
results.remove(counter);
}
public IndexRow next() {
if (counter < results.size() || updateResults()) {
final SolrDocument doc = results.get(counter);
counter++;
return new IndexRow() {
@Override
public String getPath() {
return String.valueOf(doc.getFieldValue(
configuration.getPathField()));
}
@Override
public PropertyValue getValue(String columnName) {
if (QueryImpl.JCR_SCORE.equals(columnName)) {
float score = 0f;
Object scoreObj = doc.get("score");
if (scoreObj != null) {
score = (Float) scoreObj;
}
return PropertyValues.newDouble((double) score);
}
Object o = doc.getFieldValue(columnName);
return o == null ? null : PropertyValues.newString(o.toString());
}
};
} else {
return null;
}
}
private boolean updateResults() {
int newOffset = offset + results.size();
query.setParam("start", String.valueOf(newOffset));
try {
QueryResponse queryResponse = solrServer.query(query);
SolrDocumentList localResults = queryResponse.getResults();
boolean hasMoreResults = localResults.size() > 0;
if (hasMoreResults) {
counter = 0;
offset = newOffset;
results = localResults;
} else {
query.setParam("start", String.valueOf(offset));
}
return hasMoreResults;
} catch (SolrServerException e) {
throw new RuntimeException("error retrieving paged results", e);
}
}
}
@Override
@CheckForNull
public NodeAggregator getNodeAggregator() {
return aggregator;
}
}
|
oak-solr-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/solr/query/SolrQueryIndex.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.index.solr.query;
import java.util.Collection;
import javax.annotation.CheckForNull;
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.oak.api.PropertyValue;
import org.apache.jackrabbit.oak.plugins.index.aggregate.NodeAggregator;
import org.apache.jackrabbit.oak.plugins.index.solr.configuration.OakSolrConfiguration;
import org.apache.jackrabbit.oak.query.QueryImpl;
import org.apache.jackrabbit.oak.query.fulltext.FullTextAnd;
import org.apache.jackrabbit.oak.query.fulltext.FullTextExpression;
import org.apache.jackrabbit.oak.query.fulltext.FullTextOr;
import org.apache.jackrabbit.oak.query.fulltext.FullTextTerm;
import org.apache.jackrabbit.oak.query.fulltext.FullTextVisitor;
import org.apache.jackrabbit.oak.spi.query.Cursor;
import org.apache.jackrabbit.oak.spi.query.Filter;
import org.apache.jackrabbit.oak.spi.query.IndexRow;
import org.apache.jackrabbit.oak.spi.query.PropertyValues;
import org.apache.jackrabbit.oak.spi.query.QueryIndex;
import org.apache.jackrabbit.oak.spi.query.QueryIndex.FulltextQueryIndex;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.jackrabbit.oak.commons.PathUtils.getName;
/**
* A Solr based {@link QueryIndex}
*/
public class SolrQueryIndex implements FulltextQueryIndex {
private static final String NATIVE_SOLR_QUERY = "native*solr";
private static final String NATIVE_LUCENE_QUERY = "native*lucene";
public static final String TYPE = "solr";
private final Logger log = LoggerFactory.getLogger(SolrQueryIndex.class);
private final String name;
private final SolrServer solrServer;
private final OakSolrConfiguration configuration;
private final NodeAggregator aggregator;
public SolrQueryIndex(String name, SolrServer solrServer, OakSolrConfiguration configuration) {
this.name = name;
this.solrServer = solrServer;
this.configuration = configuration;
// TODO this index should support aggregation in the same way as the Lucene index
this.aggregator = null;
}
@Override
public String getIndexName() {
return name;
}
@Override
public double getCost(Filter filter, NodeState root) {
if (filter.getFullTextConstraint() == null && filter.getFulltextConditions() == null ||
(filter.getPropertyRestrictions() != null && filter.getPropertyRestrictions().size() == 1 && filter.getPropertyRestriction(JcrConstants.JCR_UUID) != null)) {
return Double.POSITIVE_INFINITY;
}
int cost = 10;
Collection<Filter.PropertyRestriction> restrictions = filter.getPropertyRestrictions();
if (restrictions != null) {
cost /= 5;
}
if (filter.getPathRestriction() != null) {
cost /= 2;
}
return cost;
}
@Override
public String getPlan(Filter filter, NodeState nodeState) {
return getQuery(filter).toString();
}
private SolrQuery getQuery(Filter filter) {
SolrQuery solrQuery = new SolrQuery();
setDefaults(solrQuery);
StringBuilder queryBuilder = new StringBuilder();
if (filter.getFullTextConstraint() != null) {
queryBuilder.append(getFullTextQuery(filter.getFullTextConstraint()));
queryBuilder.append(' ');
} else if (filter.getFulltextConditions() != null) {
Collection<String> fulltextConditions = filter.getFulltextConditions();
for (String fulltextCondition : fulltextConditions) {
queryBuilder.append(fulltextCondition).append(" ");
}
}
Collection<Filter.PropertyRestriction> propertyRestrictions = filter.getPropertyRestrictions();
if (propertyRestrictions != null && !propertyRestrictions.isEmpty()) {
for (Filter.PropertyRestriction pr : propertyRestrictions) {
// native query support
if (NATIVE_SOLR_QUERY.equals(pr.propertyName) || NATIVE_LUCENE_QUERY.equals(pr.propertyName)) {
String nativeQueryString = String.valueOf(pr.first.getValue(pr.first.getType()));
if (isSupportedHttpRequest(nativeQueryString)) {
// pass through the native HTTP Solr request
String requestHandlerString = nativeQueryString.substring(0, nativeQueryString.indexOf('?'));
if (!"select".equals(requestHandlerString)) {
if (requestHandlerString.charAt(0) != '/') {
requestHandlerString = "/" + requestHandlerString;
}
solrQuery.setRequestHandler(requestHandlerString);
}
String parameterString = nativeQueryString.substring(nativeQueryString.indexOf('?') + 1);
for (String param : parameterString.split("&")) {
String[] kv = param.split("=");
if (kv.length != 2) {
throw new RuntimeException("Unparsable native HTTP Solr query");
} else {
if ("stream.body".equals(kv[0])) {
kv[0] = "q";
String mltFlString = "mlt.fl=";
int mltFlIndex = parameterString.indexOf(mltFlString);
if (mltFlIndex > -1) {
int beginIndex = mltFlIndex + mltFlString.length();
int endIndex = parameterString.indexOf('&', beginIndex);
String fields;
if (endIndex > beginIndex) {
fields = parameterString.substring(beginIndex, endIndex);
} else {
fields = parameterString.substring(beginIndex);
}
kv[1] = "_query_:\"{!dismax qf=" + fields + " q.op=OR}" + kv[1] + "\"";
}
}
solrQuery.setParam(kv[0], kv[1]);
}
}
return solrQuery; // every other restriction is not considered
} else {
queryBuilder.append(nativeQueryString);
}
} else {
if (pr.propertyName.contains("/")) {
// cannot handle child-level property restrictions
continue;
}
if ("rep:excerpt".equals(pr.propertyName)) {
continue;
}
String first = null;
if (pr.first != null) {
first = partialEscape(String.valueOf(pr.first.getValue(pr.first.getType()))).toString();
}
String last = null;
if (pr.last != null) {
last = partialEscape(String.valueOf(pr.last.getValue(pr.last.getType()))).toString();
}
String prField = configuration.getFieldForPropertyRestriction(pr);
CharSequence fieldName = partialEscape(prField != null ?
prField : pr.propertyName);
if ("jcr\\:path".equals(fieldName.toString())) {
queryBuilder.append(configuration.getPathField());
queryBuilder.append(':');
queryBuilder.append(first);
} else {
if (pr.first != null && pr.last != null && pr.first.equals(pr.last)) {
queryBuilder.append(fieldName).append(':');
queryBuilder.append(first);
} else if (pr.first == null && pr.last == null) {
if (!queryBuilder.toString().contains(fieldName + ":")) {
queryBuilder.append(fieldName).append(':');
queryBuilder.append('*');
}
} else if ((pr.first != null && pr.last == null) || (pr.last != null && pr.first == null) || (!pr.first.equals(pr.last))) {
// TODO : need to check if this works for all field types (most likely not!)
queryBuilder.append(fieldName).append(':');
queryBuilder.append(createRangeQuery(first, last, pr.firstIncluding, pr.lastIncluding));
} else if (pr.isLike) {
// TODO : the current parameter substitution is not expected to work well
queryBuilder.append(fieldName).append(':');
queryBuilder.append(partialEscape(String.valueOf(pr.first.getValue(pr.first.getType())).replace('%', '*').replace('_', '?')));
} else {
throw new RuntimeException("[unexpected!] not handled case");
}
}
}
queryBuilder.append(" ");
}
}
String[] pts = filter.getPrimaryTypes().toArray(new String[filter.getPrimaryTypes().size()]);
for (int i = 0; i < pts.length; i++) {
String pt = pts[i];
if (i == 0) {
queryBuilder.append("(");
}
if (i > 0 && i < pts.length) {
queryBuilder.append("OR ");
}
queryBuilder.append("jcr\\:primaryType").append(':').append(partialEscape(pt)).append(" ");
if (i == pts.length - 1) {
queryBuilder.append(")");
queryBuilder.append(' ');
}
}
Filter.PathRestriction pathRestriction = filter.getPathRestriction();
if (pathRestriction != null) {
String path = purgePath(filter);
String fieldName = configuration.getFieldForPathRestriction(pathRestriction);
if (fieldName != null) {
queryBuilder.append(fieldName);
queryBuilder.append(':');
queryBuilder.append(path);
}
}
if (queryBuilder.length() == 0) {
queryBuilder.append("*:*");
}
String escapedQuery = queryBuilder.toString();
solrQuery.setQuery(escapedQuery);
if (log.isDebugEnabled()) {
log.debug("JCR query {} has been converted to Solr query {}",
filter.getQueryStatement(), solrQuery.toString());
}
return solrQuery;
}
private String getFullTextQuery(FullTextExpression ft) {
final StringBuilder fullTextString = new StringBuilder();
ft.accept(new FullTextVisitor() {
@Override
public boolean visit(FullTextOr or) {
fullTextString.append('(');
for (int i = 0; i < or.list.size(); i++) {
if (i > 0 && i < or.list.size()) {
fullTextString.append(" OR ");
}
FullTextExpression e = or.list.get(i);
String orTerm = getFullTextQuery(e);
fullTextString.append(orTerm);
}
fullTextString.append(')');
fullTextString.append(' ');
return true;
}
@Override
public boolean visit(FullTextAnd and) {
fullTextString.append('(');
for (int i = 0; i < and.list.size(); i++) {
if (i > 0 && i < and.list.size()) {
fullTextString.append(" AND ");
}
FullTextExpression e = and.list.get(i);
String andTerm = getFullTextQuery(e);
fullTextString.append(andTerm);
}
fullTextString.append(')');
fullTextString.append(' ');
return true;
}
@Override
public boolean visit(FullTextTerm term) {
if (term.isNot()) {
fullTextString.append('-');
}
String p = term.getPropertyName();
if (p != null && p.indexOf('/') >= 0) {
p = getName(p);
}
if (p == null) {
p = configuration.getCatchAllField();
}
fullTextString.append(partialEscape(p));
fullTextString.append(':');
String termText = term.getText();
if (termText.indexOf(' ') > 0) {
fullTextString.append('"');
}
fullTextString.append(termText.replace("/", "\\/").replace(":", "\\:"));
if (termText.indexOf(' ') > 0) {
fullTextString.append('"');
}
String boost = term.getBoost();
if (boost != null) {
fullTextString.append('^');
fullTextString.append(boost);
}
fullTextString.append(' ');
return true;
}
});
return fullTextString.toString();
}
private boolean isSupportedHttpRequest(String nativeQueryString) {
// the query string starts with ${supported-handler.selector}?
return nativeQueryString.matches("(mlt|query|select|get)\\\\?.*");
}
private void setDefaults(SolrQuery solrQuery) {
solrQuery.setParam("q.op", "AND");
solrQuery.setParam("fl", "* score");
String catchAllField = configuration.getCatchAllField();
if (catchAllField != null && catchAllField.length() > 0) {
solrQuery.setParam("df", catchAllField);
}
solrQuery.setParam("rows", String.valueOf(configuration.getRows()));
}
private static String createRangeQuery(String first, String last, boolean firstIncluding, boolean lastIncluding) {
// TODO : handle inclusion / exclusion of bounds
return "[" + (first != null ? first : "*") + " TO " + (last != null ? last : "*") + "]";
}
private static String purgePath(Filter filter) {
return partialEscape(filter.getPath()).toString();
}
// partially borrowed from SolrPluginUtils#partialEscape
private static CharSequence partialEscape(CharSequence s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\\' || c == '!' || c == '(' || c == ')' ||
c == ':' || c == '^' || c == '[' || c == ']' || c == '/' ||
c == '{' || c == '}' || c == '~' || c == '*' || c == '?' ||
c == '-' || c == ' ') {
sb.append('\\');
}
sb.append(c);
}
return sb;
}
@Override
public Cursor query(Filter filter, NodeState root) {
if (log.isDebugEnabled()) {
log.debug("converting filter {}", filter);
}
Cursor cursor;
try {
SolrQuery query = getQuery(filter);
if (log.isDebugEnabled()) {
log.debug("sending query {}", query);
}
QueryResponse queryResponse = solrServer.query(query);
if (log.isDebugEnabled()) {
log.debug("getting response {}", queryResponse);
}
cursor = new SolrCursor(queryResponse, query);
} catch (Exception e) {
throw new RuntimeException(e);
}
return cursor;
}
private class SolrCursor implements Cursor {
private SolrDocumentList results;
private SolrQuery query;
private int counter;
private int offset;
public SolrCursor(QueryResponse queryResponse, SolrQuery query) {
this.results = queryResponse.getResults();
this.counter = 0;
this.offset = 0;
this.query = query;
}
@Override
public boolean hasNext() {
return results != null && offset + counter < results.getNumFound();
}
@Override
public void remove() {
results.remove(counter);
}
public IndexRow next() {
if (counter < results.size() || updateResults()) {
final SolrDocument doc = results.get(counter);
counter++;
return new IndexRow() {
@Override
public String getPath() {
return String.valueOf(doc.getFieldValue(
configuration.getPathField()));
}
@Override
public PropertyValue getValue(String columnName) {
if (QueryImpl.JCR_SCORE.equals(columnName)) {
float score = 0f;
Object scoreObj = doc.get("score");
if (scoreObj != null) {
score = (Float) scoreObj;
}
return PropertyValues.newDouble((double) score);
}
Object o = doc.getFieldValue(columnName);
return o == null ? null : PropertyValues.newString(o.toString());
}
};
} else {
return null;
}
}
private boolean updateResults() {
int newOffset = offset + results.size();
query.setParam("start", String.valueOf(newOffset));
try {
QueryResponse queryResponse = solrServer.query(query);
SolrDocumentList localResults = queryResponse.getResults();
boolean hasMoreResults = localResults.size() > 0;
if (hasMoreResults) {
counter = 0;
offset = newOffset;
results = localResults;
} else {
query.setParam("start", String.valueOf(offset));
}
return hasMoreResults;
} catch (SolrServerException e) {
throw new RuntimeException("error retrieving paged results", e);
}
}
}
@Override
@CheckForNull
public NodeAggregator getNodeAggregator() {
return aggregator;
}
}
|
OAK-1821 - FT expression with * as field should expand to catch all
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1594800 13f79535-47bb-0310-9956-ffa450edef68
|
oak-solr-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/solr/query/SolrQueryIndex.java
|
OAK-1821 - FT expression with * as field should expand to catch all
|
|
Java
|
apache-2.0
|
03db6ceb0ee415689cd42a1143c0eed2f9a613ba
| 0
|
apache/aurora,apache/aurora,kidaa/aurora,kidaa/aurora,rosmo/aurora,protochron/aurora,shahankhatch/aurora,apache/aurora,mschenck/aurora,rdelval/aurora,mkhutornenko/incubator-aurora,shahankhatch/aurora,wfarner/aurora,rdelval/aurora,rdelval/aurora,thinker0/aurora,medallia/aurora,kidaa/aurora,crashlytics/aurora,thinker0/aurora,apache/aurora,kidaa/aurora,protochron/aurora,rosmo/aurora,thinker0/aurora,rdelval/aurora,wfarner/aurora,rosmo/aurora,wfarner/aurora,thinker0/aurora,protochron/aurora,rdelval/aurora,medallia/aurora,protochron/aurora,shahankhatch/aurora,medallia/aurora,mkhutornenko/incubator-aurora,thinker0/aurora,thinker0/aurora,crashlytics/aurora,crashlytics/aurora,apache/aurora,medallia/aurora,protochron/aurora,protochron/aurora,crashlytics/aurora,shahankhatch/aurora,rosmo/aurora,shahankhatch/aurora,mschenck/aurora,medallia/aurora,mkhutornenko/incubator-aurora,crashlytics/aurora,wfarner/aurora,mschenck/aurora,mschenck/aurora,wfarner/aurora,kidaa/aurora,wfarner/aurora,mkhutornenko/incubator-aurora,rosmo/aurora,rosmo/aurora,crashlytics/aurora,mkhutornenko/incubator-aurora,shahankhatch/aurora,kidaa/aurora,mschenck/aurora,rdelval/aurora,apache/aurora,mschenck/aurora,medallia/aurora
|
package com.twitter.aurora.scheduler.app;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.logging.Logger;
import javax.annotation.Nonnegative;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Module;
import com.google.inject.PrivateModule;
import com.google.inject.Singleton;
import com.twitter.aurora.auth.SessionValidator;
import com.twitter.aurora.auth.UnsecureAuthModule;
import com.twitter.aurora.internal.cron.Cron4jModule;
import com.twitter.aurora.scheduler.DriverFactory;
import com.twitter.aurora.scheduler.DriverFactory.DriverFactoryImpl;
import com.twitter.aurora.scheduler.MesosTaskFactory.ExecutorConfig;
import com.twitter.aurora.scheduler.SchedulerLifecycle;
import com.twitter.aurora.scheduler.SchedulerLifecycle.ShutdownOnDriverExit;
import com.twitter.aurora.scheduler.cron.CronPredictor;
import com.twitter.aurora.scheduler.cron.CronScheduler;
import com.twitter.aurora.scheduler.local.IsolatedSchedulerModule;
import com.twitter.aurora.scheduler.log.mesos.MesosLogStreamModule;
import com.twitter.aurora.scheduler.storage.backup.BackupModule;
import com.twitter.aurora.scheduler.storage.log.LogStorage;
import com.twitter.aurora.scheduler.storage.log.LogStorageModule;
import com.twitter.aurora.scheduler.storage.log.SnapshotStoreImpl;
import com.twitter.aurora.scheduler.storage.mem.MemStorageModule;
import com.twitter.aurora.scheduler.thrift.ThriftConfiguration;
import com.twitter.aurora.scheduler.thrift.ThriftModule;
import com.twitter.aurora.scheduler.thrift.auth.ThriftAuthModule;
import com.twitter.common.application.AbstractApplication;
import com.twitter.common.application.AppLauncher;
import com.twitter.common.application.modules.HttpModule;
import com.twitter.common.application.modules.LocalServiceRegistry;
import com.twitter.common.application.modules.LogModule;
import com.twitter.common.application.modules.StatsModule;
import com.twitter.common.args.Arg;
import com.twitter.common.args.CmdLine;
import com.twitter.common.args.constraints.CanRead;
import com.twitter.common.args.constraints.Exists;
import com.twitter.common.args.constraints.IsDirectory;
import com.twitter.common.args.constraints.NotEmpty;
import com.twitter.common.args.constraints.NotNull;
import com.twitter.common.inject.Bindings;
import com.twitter.common.logging.RootLogConfig;
import com.twitter.common.zookeeper.Group;
import com.twitter.common.zookeeper.SingletonService;
import com.twitter.common.zookeeper.guice.client.ZooKeeperClientModule;
import com.twitter.common.zookeeper.guice.client.ZooKeeperClientModule.ClientConfig;
import com.twitter.common.zookeeper.guice.client.flagged.FlaggedClientConfig;
/**
* Launcher for the aurora scheduler.
*/
public class SchedulerMain extends AbstractApplication {
private static final Logger LOG = Logger.getLogger(SchedulerMain.class.getName());
@CmdLine(name = "testing_isolated_scheduler",
help = "If true, run in a testing mode with the scheduler isolated from other components.")
private static final Arg<Boolean> ISOLATED_SCHEDULER = Arg.create(false);
@NotNull
@CmdLine(name = "cluster_name", help = "Name to identify the cluster being served.")
private static final Arg<String> CLUSTER_NAME = Arg.create();
@NotNull
@NotEmpty
@CmdLine(name = "serverset_path", help = "ZooKeeper ServerSet path to register at.")
private static final Arg<String> SERVERSET_PATH = Arg.create();
@CanRead
@NotNull
@CmdLine(name = "mesos_ssl_keyfile",
help = "JKS keyfile for operating the Mesos Thrift-over-SSL interface.")
private static final Arg<File> MESOS_SSL_KEY_FILE = Arg.create();
@Nonnegative
@CmdLine(name = "thrift_port", help = "Thrift server port.")
private static final Arg<Integer> THRIFT_PORT = Arg.create(0);
@NotNull
@CmdLine(name = "thermos_executor_path", help = "Path to the thermos executor launch script.")
private static final Arg<String> THERMOS_EXECUTOR_PATH = Arg.create();
@NotNull
@Exists
@IsDirectory
@CmdLine(name = "backup_dir", help = "Directory to store backups under.")
private static final Arg<File> BACKUP_DIR = Arg.create();
@CmdLine(name = "auth_module",
help = "A Guice module to provide auth bindings. NOTE: The default is unsecure.")
private static final Arg<? extends Class<? extends Module>> AUTH_MODULE =
Arg.create(UnsecureAuthModule.class);
private static final Iterable<Class<?>> AUTH_MODULE_CLASSES = ImmutableList.<Class<?>>builder()
.add(SessionValidator.class)
.build();
@CmdLine(name = "cron_module",
help = "A Guice module to provide cron bindings.")
private static final Arg<? extends Class<? extends Module>> CRON_MODULE =
Arg.create(Cron4jModule.class);
private static final Iterable<Class<?>> CRON_MODULE_CLASSES = ImmutableList.<Class<?>>builder()
.add(CronPredictor.class)
.add(CronScheduler.class)
.build();
@Inject private SingletonService schedulerService;
@Inject private LocalServiceRegistry serviceRegistry;
@Inject private SchedulerLifecycle schedulerLifecycle;
@Inject private Optional<RootLogConfig.Configuration> glogConfig;
private static Iterable<? extends Module> getSystemModules() {
return ImmutableList.of(
new LogModule(),
new HttpModule(),
new StatsModule()
);
}
// TODO(ksweeney): Consider factoring this out into a ModuleParser library.
private static Module instantiateFlaggedModule(Arg<? extends Class<? extends Module>> moduleArg) {
Class<? extends Module> moduleClass = moduleArg.get();
try {
return moduleClass.newInstance();
} catch (InstantiationException e) {
throw new IllegalArgumentException(
String.format(
"Failed to instantiate module %s. Are you sure it has a no-arg constructor?",
moduleClass.getName()),
e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(
String.format(
"Failed to instantiate module %s. Are you sure it's public?",
moduleClass.getName()),
e);
}
}
// Defensively wrap each module provided on the command-line in a PrivateModule that only
// exposes requested classes to ensure that we don't depend on surprise extra bindings across
// different implementations.
private static Module getFlaggedModule(
Arg<? extends Class<? extends Module>> moduleArg,
final Iterable<Class<?>> exposedClasses) {
final Module module = instantiateFlaggedModule(moduleArg);
return new PrivateModule() {
@Override protected void configure() {
install(module);
for (Class<?> klass : exposedClasses) {
expose(klass);
}
}
};
}
private static Iterable<? extends Module> getFlaggedModules() {
return ImmutableList.of(
getFlaggedModule(AUTH_MODULE, AUTH_MODULE_CLASSES),
getFlaggedModule(CRON_MODULE, CRON_MODULE_CLASSES));
}
static Iterable<? extends Module> getModules(
String clusterName,
String serverSetPath,
File backupDir) {
return ImmutableList.<Module>builder()
.addAll(getFlaggedModules())
.addAll(getSystemModules())
.add(new AppModule(clusterName, serverSetPath))
.add(new BackupModule(backupDir, SnapshotStoreImpl.class))
.add(new LogStorageModule())
.add(new MemStorageModule(Bindings.annotatedKeyFactory(LogStorage.WriteBehind.class)))
.add(new ThriftModule())
.add(new ThriftAuthModule())
.build();
}
@Override
public Iterable<? extends Module> getModules() {
Module additional;
final ClientConfig zkClientConfig = FlaggedClientConfig.create();
if (ISOLATED_SCHEDULER.get()) {
additional = new IsolatedSchedulerModule();
} else {
// TODO(William Farner): Push these bindings down into a "production" module.
additional = new AbstractModule() {
@Override protected void configure() {
bind(DriverFactory.class).to(DriverFactoryImpl.class);
bind(DriverFactoryImpl.class).in(Singleton.class);
bind(Boolean.class).annotatedWith(ShutdownOnDriverExit.class).toInstance(true);
install(new MesosLogStreamModule(zkClientConfig));
}
};
}
Module configModule = new AbstractModule() {
@Override protected void configure() {
bind(ThriftConfiguration.class).toInstance(new ThriftConfiguration() {
@Override public InputStream getSslKeyStream() throws FileNotFoundException {
return new FileInputStream(MESOS_SSL_KEY_FILE.get());
}
@Override public int getServingPort() {
return THRIFT_PORT.get();
}
});
bind(ExecutorConfig.class).toInstance(new ExecutorConfig(THERMOS_EXECUTOR_PATH.get()));
bind(Boolean.class).annotatedWith(ShutdownOnDriverExit.class).toInstance(true);
}
};
return ImmutableList.<Module>builder()
.addAll(getModules(CLUSTER_NAME.get(), SERVERSET_PATH.get(), BACKUP_DIR.get()))
.add(new ZooKeeperClientModule(zkClientConfig))
.add(configModule)
.add(additional)
.build();
}
@Override
public void run() {
if (glogConfig.isPresent()) {
// Setup log4j to match our jul glog config in order to pick up zookeeper logging.
Log4jConfigurator.configureConsole(glogConfig.get());
} else {
LOG.warning("Running without expected glog configuration.");
}
SchedulerLifecycle.SchedulerCandidate candidate = schedulerLifecycle.prepare();
Optional<InetSocketAddress> primarySocket = serviceRegistry.getPrimarySocket();
if (!primarySocket.isPresent()) {
throw new IllegalStateException("No primary service registered with LocalServiceRegistry.");
}
try {
schedulerService.lead(primarySocket.get(), serviceRegistry.getAuxiliarySockets(), candidate);
} catch (Group.WatchException e) {
throw new IllegalStateException("Failed to watch group and lead service.", e);
} catch (Group.JoinException e) {
throw new IllegalStateException("Failed to join scheduler service group.", e);
} catch (InterruptedException e) {
throw new IllegalStateException("Interrupted while joining scheduler service group.", e);
}
candidate.awaitShutdown();
}
public static void main(String[] args) {
AppLauncher.launch(SchedulerMain.class, args);
}
}
|
src/java/com/twitter/aurora/scheduler/app/SchedulerMain.java
|
package com.twitter.aurora.scheduler.app;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnegative;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Module;
import com.google.inject.Singleton;
import com.twitter.aurora.auth.UnsecureAuthModule;
import com.twitter.aurora.internal.cron.Cron4jModule;
import com.twitter.aurora.scheduler.DriverFactory;
import com.twitter.aurora.scheduler.DriverFactory.DriverFactoryImpl;
import com.twitter.aurora.scheduler.MesosTaskFactory.ExecutorConfig;
import com.twitter.aurora.scheduler.SchedulerLifecycle;
import com.twitter.aurora.scheduler.SchedulerLifecycle.ShutdownOnDriverExit;
import com.twitter.aurora.scheduler.local.IsolatedSchedulerModule;
import com.twitter.aurora.scheduler.log.mesos.MesosLogStreamModule;
import com.twitter.aurora.scheduler.storage.backup.BackupModule;
import com.twitter.aurora.scheduler.storage.log.LogStorage;
import com.twitter.aurora.scheduler.storage.log.LogStorageModule;
import com.twitter.aurora.scheduler.storage.log.SnapshotStoreImpl;
import com.twitter.aurora.scheduler.storage.mem.MemStorageModule;
import com.twitter.aurora.scheduler.thrift.ThriftConfiguration;
import com.twitter.aurora.scheduler.thrift.ThriftModule;
import com.twitter.aurora.scheduler.thrift.auth.ThriftAuthModule;
import com.twitter.common.application.AbstractApplication;
import com.twitter.common.application.AppLauncher;
import com.twitter.common.application.modules.HttpModule;
import com.twitter.common.application.modules.LocalServiceRegistry;
import com.twitter.common.application.modules.LogModule;
import com.twitter.common.application.modules.StatsModule;
import com.twitter.common.args.Arg;
import com.twitter.common.args.CmdLine;
import com.twitter.common.args.constraints.CanRead;
import com.twitter.common.args.constraints.Exists;
import com.twitter.common.args.constraints.IsDirectory;
import com.twitter.common.args.constraints.NotEmpty;
import com.twitter.common.args.constraints.NotNull;
import com.twitter.common.inject.Bindings;
import com.twitter.common.logging.RootLogConfig;
import com.twitter.common.zookeeper.Group;
import com.twitter.common.zookeeper.SingletonService;
import com.twitter.common.zookeeper.guice.client.ZooKeeperClientModule;
import com.twitter.common.zookeeper.guice.client.ZooKeeperClientModule.ClientConfig;
import com.twitter.common.zookeeper.guice.client.flagged.FlaggedClientConfig;
/**
* Launcher for the aurora scheduler.
*/
public class SchedulerMain extends AbstractApplication {
private static final Logger LOG = Logger.getLogger(SchedulerMain.class.getName());
@CmdLine(name = "testing_isolated_scheduler",
help = "If true, run in a testing mode with the scheduler isolated from other components.")
private static final Arg<Boolean> ISOLATED_SCHEDULER = Arg.create(false);
@NotNull
@CmdLine(name = "cluster_name", help = "Name to identify the cluster being served.")
private static final Arg<String> CLUSTER_NAME = Arg.create();
@NotNull
@NotEmpty
@CmdLine(name = "serverset_path", help = "ZooKeeper ServerSet path to register at.")
private static final Arg<String> SERVERSET_PATH = Arg.create();
@CanRead
@NotNull
@CmdLine(name = "mesos_ssl_keyfile",
help = "JKS keyfile for operating the Mesos Thrift-over-SSL interface.")
private static final Arg<File> MESOS_SSL_KEY_FILE = Arg.create();
@Nonnegative
@CmdLine(name = "thrift_port", help = "Thrift server port.")
private static final Arg<Integer> THRIFT_PORT = Arg.create(0);
@NotNull
@CmdLine(name = "thermos_executor_path", help = "Path to the thermos executor launch script.")
private static final Arg<String> THERMOS_EXECUTOR_PATH = Arg.create();
@NotNull
@Exists
@IsDirectory
@CmdLine(name = "backup_dir", help = "Directory to store backups under.")
private static final Arg<File> BACKUP_DIR = Arg.create();
@CmdLine(name = "auth_module",
help = "A Guice module to provide auth bindings. NOTE: The default is unsecure.")
public static final Arg<? extends Class<? extends AbstractModule>> AUTH_MODULE =
Arg.create(UnsecureAuthModule.class);
@Inject private SingletonService schedulerService;
@Inject private LocalServiceRegistry serviceRegistry;
@Inject private SchedulerLifecycle schedulerLifecycle;
@Inject private Optional<RootLogConfig.Configuration> glogConfig;
private static Iterable<? extends Module> getSystemModules() {
return Arrays.asList(
new HttpModule(),
new LogModule(),
new StatsModule()
);
}
static Iterable<? extends Module> getModules(
String clusterName,
String serverSetPath,
File backupDir) {
ImmutableList.Builder<Module> modules = ImmutableList.<Module>builder()
.addAll(getSystemModules())
.add(new AppModule(clusterName, serverSetPath))
.add(new Cron4jModule())
.add(new ThriftModule())
.add(new ThriftAuthModule());
Class<? extends AbstractModule> authModule = AUTH_MODULE.get();
try {
// If installation fails, no SessionValidator will be bound and app will fail to startup.
modules.add(authModule.newInstance());
} catch (InstantiationException e) {
LOG.log(Level.WARNING, "Failed to instantiate auth module: " + authModule.getName(), e);
throw new IllegalArgumentException(e);
} catch (IllegalAccessException e) {
LOG.log(Level.WARNING, "Failed to instantiate auth module: " + authModule.getName(), e);
throw new IllegalArgumentException(e);
}
modules.add(new BackupModule(backupDir, SnapshotStoreImpl.class));
modules.add(new MemStorageModule(Bindings.annotatedKeyFactory(LogStorage.WriteBehind.class)));
modules.add(new LogStorageModule());
return modules.build();
}
@Override
public Iterable<? extends Module> getModules() {
Module additional;
final ClientConfig zkClientConfig = FlaggedClientConfig.create();
if (ISOLATED_SCHEDULER.get()) {
additional = new IsolatedSchedulerModule();
} else {
// TODO(William Farner): Push these bindings down into a "production" module.
additional = new AbstractModule() {
@Override protected void configure() {
bind(DriverFactory.class).to(DriverFactoryImpl.class);
bind(DriverFactoryImpl.class).in(Singleton.class);
bind(Boolean.class).annotatedWith(ShutdownOnDriverExit.class).toInstance(true);
install(new MesosLogStreamModule(zkClientConfig));
}
};
}
Module configModule = new AbstractModule() {
@Override protected void configure() {
bind(ThriftConfiguration.class).toInstance(new ThriftConfiguration() {
@Override public InputStream getSslKeyStream() throws FileNotFoundException {
return new FileInputStream(MESOS_SSL_KEY_FILE.get());
}
@Override public int getServingPort() {
return THRIFT_PORT.get();
}
});
bind(ExecutorConfig.class).toInstance(new ExecutorConfig(THERMOS_EXECUTOR_PATH.get()));
bind(Boolean.class).annotatedWith(ShutdownOnDriverExit.class).toInstance(true);
}
};
return ImmutableList.<Module>builder()
.addAll(getModules(CLUSTER_NAME.get(), SERVERSET_PATH.get(), BACKUP_DIR.get()))
.add(new ZooKeeperClientModule(zkClientConfig))
.add(configModule)
.add(additional)
.build();
}
@Override
public void run() {
if (glogConfig.isPresent()) {
// Setup log4j to match our jul glog config in order to pick up zookeeper logging.
Log4jConfigurator.configureConsole(glogConfig.get());
} else {
LOG.warning("Running without expected glog configuration.");
}
SchedulerLifecycle.SchedulerCandidate candidate = schedulerLifecycle.prepare();
Optional<InetSocketAddress> primarySocket = serviceRegistry.getPrimarySocket();
if (!primarySocket.isPresent()) {
throw new IllegalStateException("No primary service registered with LocalServiceRegistry.");
}
try {
schedulerService.lead(primarySocket.get(), serviceRegistry.getAuxiliarySockets(), candidate);
} catch (Group.WatchException e) {
throw new IllegalStateException("Failed to watch group and lead service.", e);
} catch (Group.JoinException e) {
throw new IllegalStateException("Failed to join scheduler service group.", e);
} catch (InterruptedException e) {
throw new IllegalStateException("Interrupted while joining scheduler service group.", e);
}
candidate.awaitShutdown();
}
public static void main(String[] args) {
AppLauncher.launch(SchedulerMain.class, args);
}
}
|
Add cron_module flag and cleanup SchedulerMain.
|
src/java/com/twitter/aurora/scheduler/app/SchedulerMain.java
|
Add cron_module flag and cleanup SchedulerMain.
|
|
Java
|
apache-2.0
|
c878d2b9e63ec69558345eccd7f24f4a33922e3c
| 0
|
Orange-OpenSource/bosh-cloudstack-cpi-core,cloudfoundry-community/bosh-cloudstack-cpi-core,Orange-OpenSource/bosh-cloudstack-cpi-core,cloudfoundry-community/bosh-cloudstack-cpi-core,cloudfoundry-community/bosh-cloudstack-cpi-core,Orange-OpenSource/bosh-cloudstack-cpi-core
|
package com.orange.oss.cloudfoundry.cscpi;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.jclouds.cloudstack.CloudStackApi;
import org.jclouds.cloudstack.domain.*;
import org.jclouds.cloudstack.domain.VirtualMachine.State;
import org.jclouds.cloudstack.features.VolumeApi;
import org.jclouds.cloudstack.options.CreateSnapshotOptions;
import org.jclouds.cloudstack.options.DeployVirtualMachineOptions;
import org.jclouds.cloudstack.options.ListDiskOfferingsOptions;
import org.jclouds.cloudstack.options.ListServiceOfferingsOptions;
import org.jclouds.cloudstack.options.ListTemplatesOptions;
import org.jclouds.cloudstack.options.ListVirtualMachinesOptions;
import org.jclouds.cloudstack.options.ListVolumesOptions;
import org.jclouds.cloudstack.options.ListZonesOptions;
import org.jclouds.cloudstack.predicates.JobComplete;
import org.jclouds.cloudstack.strategy.BlockUntilJobCompletesAndReturnResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Predicate;
/**
* Implementation of the CPI API, translating to CloudStack jclouds API calls
*
*
* @see: http://www.programcreek.com/java-api-examples/index.php?api=org.jclouds.predicates.RetryablePredicate
* @see:
*
*/
public class CPIImpl implements CPI{
private static Logger logger=LoggerFactory.getLogger(CPIImpl.class);
@Value("${cloudstack.state_timeout}")
int state_timeout;
@Value("${cloudstack.state_timeout_volume}")
int state_timeout_volume;
@Value("${cloudstack.stemcell_public_visibility}")
boolean stemcell_public_visibility;
@Value("${cloudstack.default_zone}")
String default_zone;
protected Predicate<String> jobComplete;
@Autowired
private CloudStackApi api;
/**
* creates a vm
*
* @param agent_id
* @param stemcell_id
* @param resource_pool
* @param networks
* @param disk_locality
* @param env
* @return
*/
public String create_vm(String agent_id,
String stemcell_id,
JsonNode resource_pool,
JsonNode networks,
List<String> disk_locality,
Map<String,String> env) {
ObjectMapper mapper = new ObjectMapper();
//
// Template template = api.getVirtualMachineApi().templateBuilder()
// .osFamily(OsFamily.UBUNTU)
// .minRam(2048)
// .options(inboundPorts(22, 80))
// .build();
String vmName="cpivm-"+UUID.randomUUID().toString();
String serviceOfferingName="Ultra Tiny";
//TODO: find csTemplateId from name when template generation is OK
String csTemplateId=stemcell_id;
String zoneId = findZoneId();
//find offering
Set<ServiceOffering> s = api.getOfferingApi().listServiceOfferings(ListServiceOfferingsOptions.Builder.name(serviceOfferingName));
//FIXME assert a single offering
ServiceOffering so=s.iterator().next();
//set options
long dataDiskSize=100;
String userData="testdata=zzz";
DeployVirtualMachineOptions options=DeployVirtualMachineOptions.Builder
.userData(userData.getBytes())
.dataDiskSize(dataDiskSize)
.name(vmName);
AsyncCreateResponse job = api.getVirtualMachineApi().deployVirtualMachineInZone(zoneId, so.getId(), csTemplateId, options);
jobComplete.apply(job.getJobId());
AsyncJob<VirtualMachine> jobWithResult = api.getAsyncJobApi().<VirtualMachine> getAsyncJob(job.getId());
if (jobWithResult.getError() != null) {
throw new RuntimeException("Failed with:" + jobWithResult.getError());
}
VirtualMachine vm = jobWithResult.getResult();
if (! vm.getState().equals(State.RUNNING)) {
throw new RuntimeException("Not in expectedrunning:" + vm.getState());
}
logger.info("vm creation completed, now running ! {}");
return vmName;
}
@Override
public void initialize(Map<String, String> options) {
logger.info("",options);
}
@Override
public String current_vm_id() {
logger.info("current_vm_id");
//FIXME : strange API ? must keep state in CPI with latest changed / created vm ??
return null;
}
@Override
public String create_stemcell(String image_path,
Map<String, String> cloud_properties) {
logger.info("create_stemcell");
//map stemcell to cloudstack template concept.
//FIXME: change with template generation, for now use existing centos template
String stemcellId="cpitemplate-"+UUID.randomUUID();
String csTemplateId=api.getTemplateApi().listTemplates(ListTemplatesOptions.Builder.name("CentOS 5.6(64-bit) no GUI (XenServer)")).iterator().next().getId();
return csTemplateId;
}
@Override
public void delete_stemcell(String stemcell_id) {
logger.info("delete_stemcell");
}
@Override
public void delete_vm(String vm_id) {
logger.info("delete_vm");
//FIXME : check vm is existing
String csVmId=api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id)).iterator().next().getId();
api.getVirtualMachineApi().destroyVirtualMachine(csVmId);
logger.info("deleted successfully vm {}",vm_id);
}
@Override
public boolean has_vm(String vm_id) {
logger.info("has_vm ?");
VirtualMachine vm=api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name("vm_id")).iterator().next();
if (vm==null) return false;
return true;
}
@Override
public boolean has_disk(String disk_id) {
logger.info("has_disk ?");
Volume vol = api.getVolumeApi().getVolume(disk_id);
if (vol==null) return false;
return true;
}
@Override
public void reboot_vm(String vm_id) {
logger.info("reboot_vm");
api.getVirtualMachineApi().rebootVirtualMachine(vm_id);
}
@Override
public void set_vm_metadata(String vm_id, Map<String, String> metadata) {
logger.info("set vm metadata");
}
@Override
public void configure_networks(String vm_id, JsonNode networks) {
logger.info("configure network");
}
@Override
public String create_disk(Integer size, Map<String, String> cloud_properties) {
logger.info("create_disk");
//FIXME see disk offering (cloud properties specificy?)
String name="cpidisk-"+UUID.randomUUID().toString();
//find disk offering
//TODO: Custom disk offering possible, but cant delete vol ?
//String diskOfferingName = "Small";
String diskOfferingName = "Custom";
String diskOfferingId=api.getOfferingApi().listDiskOfferings(ListDiskOfferingsOptions.Builder.name(diskOfferingName)).iterator().next().getId();
//FIXME assert a single offering found
String zoneId=this.findZoneId();
api.getVolumeApi().createVolumeFromCustomDiskOfferingInZone(name, diskOfferingId, zoneId, size);
return name;
}
@Override
public void delete_disk(String disk_id) {
logger.info("delete_disk");
String csDiskId=api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.name(disk_id)).iterator().next().getId();
api.getVolumeApi().deleteVolume(csDiskId);
}
@Override
public void attach_disk(String vm_id, String disk_id) {
logger.info("attach disk");
String csDiskId=api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.name(disk_id)).iterator().next().getId();
String csVmId=api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id)).iterator().next().getId();
VolumeApi vol = this.api.getVolumeApi();
AsyncCreateResponse resp=vol.attachVolume(csDiskId, csVmId);
//TODO: wait for attachment ? need to restart vm ?
logger.info("==> detach disk successfull");
}
@Override
public String snapshot_disk(String disk_id, Map<String, String> metadata) {
logger.info("snapshot disk");
String csDiskId=api.getVolumeApi().getVolume(disk_id).getId();
AsyncCreateResponse async = api.getSnapshotApi().createSnapshot(csDiskId,CreateSnapshotOptions.Builder.domainId("domain"));
//FIXME
return null;
}
@Override
public void delete_snapshot(String snapshot_id) {
logger.info("delete snapshot");
//TODO
}
@Override
public void detach_disk(String vm_id, String disk_id) {
logger.info("detach disk");
String csDiskId=api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.name(disk_id)).iterator().next().getId();
AsyncCreateResponse resp=api.getVolumeApi().detachVolume(csDiskId);
logger.info("==> detach disk successfull");
}
@Override
public List<String> get_disks(String vm_id) {
logger.info("get_disks");
VirtualMachine vm=api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id)).iterator().next();
VolumeApi vol = this.api.getVolumeApi();
Set<Volume> vols=vol.listVolumes(ListVolumesOptions.Builder.virtualMachineId(vm.getId()));
ArrayList<String> disks = new ArrayList<String>();
Iterator<Volume> it=vols.iterator();
while (it.hasNext()){
Volume v=it.next();
String disk_id=v.getName();
disks.add(disk_id);
}
return disks;
}
/**
* utility to retrieve cloudstack zoneId
* @return
*/
private String findZoneId() {
//find zone
ListZonesOptions zoneOptions=ListZonesOptions.Builder.available(true);
Set<Zone> zones = api.getZoneApi().listZones(zoneOptions);
//FIXME: assert a single zone matching
Zone zone=zones.iterator().next();
String zoneId = zone.getId();
return zoneId;
}
}
|
src/main/java/com/orange/oss/cloudfoundry/cscpi/CPIImpl.java
|
package com.orange.oss.cloudfoundry.cscpi;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.jclouds.cloudstack.CloudStackApi;
import org.jclouds.cloudstack.domain.*;
import org.jclouds.cloudstack.domain.VirtualMachine.State;
import org.jclouds.cloudstack.features.VolumeApi;
import org.jclouds.cloudstack.options.CreateSnapshotOptions;
import org.jclouds.cloudstack.options.DeployVirtualMachineOptions;
import org.jclouds.cloudstack.options.ListDiskOfferingsOptions;
import org.jclouds.cloudstack.options.ListServiceOfferingsOptions;
import org.jclouds.cloudstack.options.ListTemplatesOptions;
import org.jclouds.cloudstack.options.ListVirtualMachinesOptions;
import org.jclouds.cloudstack.options.ListVolumesOptions;
import org.jclouds.cloudstack.options.ListZonesOptions;
import org.jclouds.cloudstack.predicates.JobComplete;
import org.jclouds.cloudstack.strategy.BlockUntilJobCompletesAndReturnResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Predicate;
/**
* Implementation of the CPI API, translating to CloudStack jclouds API calls
*
*
* @see: http://www.programcreek.com/java-api-examples/index.php?api=org.jclouds.predicates.RetryablePredicate
* @see:
*
*/
public class CPIImpl implements CPI{
private static Logger logger=LoggerFactory.getLogger(CPIImpl.class);
@Value("${cloudstack.state_timeout}")
int state_timeout;
@Value("${cloudstack.state_timeout_volume}")
int state_timeout_volume;
@Value("${cloudstack.stemcell_public_visibility}")
boolean stemcell_public_visibility;
@Value("${cloudstack.default_zone}")
String default_zone;
protected Predicate<String> jobComplete;
@Autowired
private CloudStackApi api;
/**
* creates a vm
*
* @param agent_id
* @param stemcell_id
* @param resource_pool
* @param networks
* @param disk_locality
* @param env
* @return
*/
public String create_vm(String agent_id,
String stemcell_id,
JsonNode resource_pool,
JsonNode networks,
List<String> disk_locality,
Map<String,String> env) {
ObjectMapper mapper = new ObjectMapper();
//
// Template template = api.getVirtualMachineApi().templateBuilder()
// .osFamily(OsFamily.UBUNTU)
// .minRam(2048)
// .options(inboundPorts(22, 80))
// .build();
String vmName="cpivm-"+UUID.randomUUID().toString();
String serviceOfferingName="Ultra Tiny";
//TODO: find csTemplateId from name when template generation is OK
String csTemplateId=stemcell_id;
String zoneId = findZoneId();
//find offering
Set<ServiceOffering> s = api.getOfferingApi().listServiceOfferings(ListServiceOfferingsOptions.Builder.name(serviceOfferingName));
//FIXME assert a single offering
ServiceOffering so=s.iterator().next();
//set options
long dataDiskSize=100;
String userData="testdata=zzz";
DeployVirtualMachineOptions options=DeployVirtualMachineOptions.Builder
.userData(userData.getBytes())
.dataDiskSize(dataDiskSize)
.name(vmName);
AsyncCreateResponse job = api.getVirtualMachineApi().deployVirtualMachineInZone(zoneId, so.getId(), csTemplateId, options);
AsyncJob<VirtualMachine> jobWithResult = api.getAsyncJobApi().<VirtualMachine> getAsyncJob(job.getId());
if (jobWithResult.getError() != null) {
throw new RuntimeException("Failed with:" + jobWithResult.getError());
}
VirtualMachine vm = jobWithResult.getResult();
if (! vm.getState().equals(State.RUNNING)) {
throw new RuntimeException("Not in expectedrunning:" + vm.getState());
}
logger.info("vm creation completed, now running ! {}");
return vmName;
}
@Override
public void initialize(Map<String, String> options) {
logger.info("",options);
}
@Override
public String current_vm_id() {
logger.info("current_vm_id");
//FIXME : strange API ? must keep state in CPI with latest changed / created vm ??
return null;
}
@Override
public String create_stemcell(String image_path,
Map<String, String> cloud_properties) {
logger.info("create_stemcell");
//map stemcell to cloudstack template concept.
//FIXME: change with template generation, for now use existing centos template
String stemcellId="cpitemplate-"+UUID.randomUUID();
String csTemplateId=api.getTemplateApi().listTemplates(ListTemplatesOptions.Builder.name("CentOS 5.6(64-bit) no GUI (XenServer)")).iterator().next().getId();
return csTemplateId;
}
@Override
public void delete_stemcell(String stemcell_id) {
logger.info("delete_stemcell");
}
@Override
public void delete_vm(String vm_id) {
logger.info("delete_vm");
//FIXME : check vm is existing
String csVmId=api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id)).iterator().next().getId();
api.getVirtualMachineApi().destroyVirtualMachine(csVmId);
logger.info("deleted successfully vm {}",vm_id);
}
@Override
public boolean has_vm(String vm_id) {
logger.info("has_vm ?");
VirtualMachine vm=api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name("vm_id")).iterator().next();
if (vm==null) return false;
return true;
}
@Override
public boolean has_disk(String disk_id) {
logger.info("has_disk ?");
Volume vol = api.getVolumeApi().getVolume(disk_id);
if (vol==null) return false;
return true;
}
@Override
public void reboot_vm(String vm_id) {
logger.info("reboot_vm");
api.getVirtualMachineApi().rebootVirtualMachine(vm_id);
}
@Override
public void set_vm_metadata(String vm_id, Map<String, String> metadata) {
logger.info("set vm metadata");
}
@Override
public void configure_networks(String vm_id, JsonNode networks) {
logger.info("configure network");
}
@Override
public String create_disk(Integer size, Map<String, String> cloud_properties) {
logger.info("create_disk");
//FIXME see disk offering (cloud properties specificy?)
String name="cpidisk-"+UUID.randomUUID().toString();
//find disk offering
//TODO: Custom disk offering possible, but cant delete vol ?
//String diskOfferingName = "Small";
String diskOfferingName = "Custom";
String diskOfferingId=api.getOfferingApi().listDiskOfferings(ListDiskOfferingsOptions.Builder.name(diskOfferingName)).iterator().next().getId();
//FIXME assert a single offering found
String zoneId=this.findZoneId();
api.getVolumeApi().createVolumeFromCustomDiskOfferingInZone(name, diskOfferingId, zoneId, size);
return name;
}
@Override
public void delete_disk(String disk_id) {
logger.info("delete_disk");
String csDiskId=api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.name(disk_id)).iterator().next().getId();
api.getVolumeApi().deleteVolume(csDiskId);
}
@Override
public void attach_disk(String vm_id, String disk_id) {
logger.info("attach disk");
String csDiskId=api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.name(disk_id)).iterator().next().getId();
String csVmId=api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id)).iterator().next().getId();
VolumeApi vol = this.api.getVolumeApi();
AsyncCreateResponse resp=vol.attachVolume(csDiskId, csVmId);
//TODO: wait for attachment ? need to restart vm ?
logger.info("==> detach disk successfull");
}
@Override
public String snapshot_disk(String disk_id, Map<String, String> metadata) {
logger.info("snapshot disk");
String csDiskId=api.getVolumeApi().getVolume(disk_id).getId();
AsyncCreateResponse async = api.getSnapshotApi().createSnapshot(csDiskId,CreateSnapshotOptions.Builder.domainId("domain"));
//FIXME
return null;
}
@Override
public void delete_snapshot(String snapshot_id) {
logger.info("delete snapshot");
//TODO
}
@Override
public void detach_disk(String vm_id, String disk_id) {
logger.info("detach disk");
String csDiskId=api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.name(disk_id)).iterator().next().getId();
AsyncCreateResponse resp=api.getVolumeApi().detachVolume(csDiskId);
logger.info("==> detach disk successfull");
}
@Override
public List<String> get_disks(String vm_id) {
logger.info("get_disks");
VirtualMachine vm=api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id)).iterator().next();
VolumeApi vol = this.api.getVolumeApi();
Set<Volume> vols=vol.listVolumes(ListVolumesOptions.Builder.virtualMachineId(vm.getId()));
ArrayList<String> disks = new ArrayList<String>();
Iterator<Volume> it=vols.iterator();
while (it.hasNext()){
Volume v=it.next();
String disk_id=v.getName();
disks.add(disk_id);
}
return disks;
}
/**
* utility to retrieve cloudstack zoneId
* @return
*/
private String findZoneId() {
//find zone
ListZonesOptions zoneOptions=ListZonesOptions.Builder.available(true);
Set<Zone> zones = api.getZoneApi().listZones(zoneOptions);
//FIXME: assert a single zone matching
Zone zone=zones.iterator().next();
String zoneId = zone.getId();
return zoneId;
}
}
|
Attempt to use async job status
Trying with explicit job complete apply
|
src/main/java/com/orange/oss/cloudfoundry/cscpi/CPIImpl.java
|
Attempt to use async job status
|
|
Java
|
apache-2.0
|
7ae798afe6eda53e720b7164094ad7679b00e97a
| 0
|
BiryukovVA/ignite,SharplEr/ignite,xtern/ignite,shroman/ignite,shroman/ignite,vladisav/ignite,voipp/ignite,endian675/ignite,SharplEr/ignite,daradurvs/ignite,samaitra/ignite,xtern/ignite,nizhikov/ignite,vladisav/ignite,endian675/ignite,amirakhmedov/ignite,ptupitsyn/ignite,SomeFire/ignite,andrey-kuznetsov/ignite,BiryukovVA/ignite,dream-x/ignite,ascherbakoff/ignite,daradurvs/ignite,nizhikov/ignite,wmz7year/ignite,sk0x50/ignite,SomeFire/ignite,andrey-kuznetsov/ignite,NSAmelchev/ignite,StalkXT/ignite,vladisav/ignite,ptupitsyn/ignite,chandresh-pancholi/ignite,alexzaitzev/ignite,SharplEr/ignite,BiryukovVA/ignite,ascherbakoff/ignite,BiryukovVA/ignite,wmz7year/ignite,irudyak/ignite,NSAmelchev/ignite,andrey-kuznetsov/ignite,chandresh-pancholi/ignite,SomeFire/ignite,ptupitsyn/ignite,ascherbakoff/ignite,irudyak/ignite,apache/ignite,sk0x50/ignite,psadusumilli/ignite,ascherbakoff/ignite,SharplEr/ignite,nizhikov/ignite,ascherbakoff/ignite,dream-x/ignite,amirakhmedov/ignite,ilantukh/ignite,samaitra/ignite,WilliamDo/ignite,daradurvs/ignite,vladisav/ignite,SomeFire/ignite,ilantukh/ignite,SharplEr/ignite,shroman/ignite,BiryukovVA/ignite,WilliamDo/ignite,endian675/ignite,StalkXT/ignite,irudyak/ignite,BiryukovVA/ignite,ptupitsyn/ignite,SharplEr/ignite,chandresh-pancholi/ignite,chandresh-pancholi/ignite,wmz7year/ignite,xtern/ignite,NSAmelchev/ignite,shroman/ignite,BiryukovVA/ignite,psadusumilli/ignite,shroman/ignite,apache/ignite,endian675/ignite,xtern/ignite,daradurvs/ignite,BiryukovVA/ignite,dream-x/ignite,WilliamDo/ignite,voipp/ignite,andrey-kuznetsov/ignite,alexzaitzev/ignite,sk0x50/ignite,apache/ignite,wmz7year/ignite,psadusumilli/ignite,ilantukh/ignite,voipp/ignite,StalkXT/ignite,vladisav/ignite,vladisav/ignite,wmz7year/ignite,andrey-kuznetsov/ignite,alexzaitzev/ignite,WilliamDo/ignite,sk0x50/ignite,apache/ignite,wmz7year/ignite,WilliamDo/ignite,apache/ignite,psadusumilli/ignite,SharplEr/ignite,ptupitsyn/ignite,amirakhmedov/ignite,wmz7year/ignite,daradurvs/ignite,andrey-kuznetsov/ignite,NSAmelchev/ignite,NSAmelchev/ignite,psadusumilli/ignite,chandresh-pancholi/ignite,andrey-kuznetsov/ignite,BiryukovVA/ignite,dream-x/ignite,dream-x/ignite,nizhikov/ignite,amirakhmedov/ignite,ptupitsyn/ignite,SomeFire/ignite,apache/ignite,endian675/ignite,samaitra/ignite,ilantukh/ignite,daradurvs/ignite,SharplEr/ignite,WilliamDo/ignite,shroman/ignite,StalkXT/ignite,dream-x/ignite,wmz7year/ignite,alexzaitzev/ignite,sk0x50/ignite,ascherbakoff/ignite,StalkXT/ignite,irudyak/ignite,xtern/ignite,NSAmelchev/ignite,endian675/ignite,endian675/ignite,NSAmelchev/ignite,chandresh-pancholi/ignite,ptupitsyn/ignite,alexzaitzev/ignite,shroman/ignite,SharplEr/ignite,alexzaitzev/ignite,ilantukh/ignite,ilantukh/ignite,irudyak/ignite,ptupitsyn/ignite,dream-x/ignite,samaitra/ignite,endian675/ignite,nizhikov/ignite,NSAmelchev/ignite,voipp/ignite,ilantukh/ignite,StalkXT/ignite,SomeFire/ignite,xtern/ignite,alexzaitzev/ignite,shroman/ignite,vladisav/ignite,nizhikov/ignite,WilliamDo/ignite,psadusumilli/ignite,andrey-kuznetsov/ignite,psadusumilli/ignite,samaitra/ignite,ascherbakoff/ignite,daradurvs/ignite,irudyak/ignite,nizhikov/ignite,ascherbakoff/ignite,xtern/ignite,andrey-kuznetsov/ignite,xtern/ignite,voipp/ignite,daradurvs/ignite,vladisav/ignite,amirakhmedov/ignite,SomeFire/ignite,daradurvs/ignite,samaitra/ignite,voipp/ignite,amirakhmedov/ignite,sk0x50/ignite,chandresh-pancholi/ignite,SomeFire/ignite,SomeFire/ignite,amirakhmedov/ignite,psadusumilli/ignite,voipp/ignite,sk0x50/ignite,StalkXT/ignite,StalkXT/ignite,sk0x50/ignite,WilliamDo/ignite,chandresh-pancholi/ignite,sk0x50/ignite,shroman/ignite,BiryukovVA/ignite,alexzaitzev/ignite,nizhikov/ignite,chandresh-pancholi/ignite,apache/ignite,amirakhmedov/ignite,voipp/ignite,apache/ignite,ptupitsyn/ignite,ilantukh/ignite,irudyak/ignite,ilantukh/ignite,samaitra/ignite,amirakhmedov/ignite,SomeFire/ignite,samaitra/ignite,samaitra/ignite,daradurvs/ignite,xtern/ignite,irudyak/ignite,ptupitsyn/ignite,irudyak/ignite,andrey-kuznetsov/ignite,ascherbakoff/ignite,ilantukh/ignite,dream-x/ignite,NSAmelchev/ignite,apache/ignite,voipp/ignite,nizhikov/ignite,alexzaitzev/ignite,StalkXT/ignite,samaitra/ignite,shroman/ignite
|
/*
* 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.ignite.internal.processors.cache.persistence;
import org.apache.ignite.DataRegionMetrics;
import org.apache.ignite.configuration.DataRegionConfiguration;
import org.apache.ignite.internal.pagemem.PageMemory;
import org.apache.ignite.internal.processors.cache.ratemetrics.HitRateMetrics;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteOutClosure;
import org.jetbrains.annotations.Nullable;
import org.jsr166.LongAdder8;
/**
*
*/
public class DataRegionMetricsImpl implements DataRegionMetrics {
/** */
private final IgniteOutClosure<Float> fillFactorProvider;
/** */
private final LongAdder8 totalAllocatedPages = new LongAdder8();
/**
* Counter for number of pages occupied by large entries (one entry is larger than one page).
*/
private final LongAdder8 largeEntriesPages = new LongAdder8();
/** Counter for number of dirty pages. */
private LongAdder8 dirtyPages = new LongAdder8();
/** */
private volatile boolean metricsEnabled;
/** */
private boolean persistenceEnabled;
/** */
private volatile int subInts;
/** Allocation rate calculator. */
private volatile HitRateMetrics allocRate = new HitRateMetrics(60_000, 5);
/** */
private volatile HitRateMetrics pageReplaceRate = new HitRateMetrics(60_000, 5);
/** */
private volatile HitRateMetrics pageReplaceAge = new HitRateMetrics(60_000, 5);
/** */
private final DataRegionConfiguration memPlcCfg;
/** */
private PageMemory pageMem;
/** Time interval (in milliseconds) when allocations/evictions are counted to calculate rate. */
private volatile long rateTimeInterval;
/**
* @param memPlcCfg DataRegionConfiguration.
*/
public DataRegionMetricsImpl(DataRegionConfiguration memPlcCfg) {
this(memPlcCfg, null);
}
/**
* @param memPlcCfg DataRegionConfiguration.
*/
public DataRegionMetricsImpl(DataRegionConfiguration memPlcCfg, @Nullable IgniteOutClosure<Float> fillFactorProvider) {
this.memPlcCfg = memPlcCfg;
this.fillFactorProvider = fillFactorProvider;
metricsEnabled = memPlcCfg.isMetricsEnabled();
rateTimeInterval = memPlcCfg.getMetricsRateTimeInterval();
subInts = memPlcCfg.getMetricsSubIntervalCount();
}
/** {@inheritDoc} */
@Override public String getName() {
return U.maskName(memPlcCfg.getName());
}
/** {@inheritDoc} */
@Override public long getTotalAllocatedPages() {
return metricsEnabled ? totalAllocatedPages.longValue() : 0;
}
/** {@inheritDoc} */
@Override public float getAllocationRate() {
if (!metricsEnabled)
return 0;
return ((float)allocRate.getRate() * 1000) / rateTimeInterval;
}
/** {@inheritDoc} */
@Override public float getEvictionRate() {
return 0;
}
/** {@inheritDoc} */
@Override public float getLargeEntriesPagesPercentage() {
if (!metricsEnabled)
return 0;
return totalAllocatedPages.longValue() != 0 ?
(float) largeEntriesPages.doubleValue() / totalAllocatedPages.longValue()
: 0;
}
/** {@inheritDoc} */
@Override public float getPagesFillFactor() {
if (!metricsEnabled || fillFactorProvider == null)
return 0;
return fillFactorProvider.apply();
}
/** {@inheritDoc} */
@Override public long getDirtyPages() {
if (!metricsEnabled || !persistenceEnabled)
return 0;
return dirtyPages.longValue();
}
/** {@inheritDoc} */
@Override public float getPagesReplaceRate() {
if (!metricsEnabled || !persistenceEnabled)
return 0;
return ((float)pageReplaceRate.getRate() * 1000) / rateTimeInterval;
}
/** {@inheritDoc} */
@Override public float getPagesReplaceAge() {
if (!metricsEnabled || !persistenceEnabled)
return 0;
long rep = pageReplaceRate.getRate();
return rep == 0 ? 0 : ((float)pageReplaceAge.getRate() / rep);
}
/** {@inheritDoc} */
@Override public long getPhysicalMemoryPages() {
if (!persistenceEnabled)
return getTotalAllocatedPages();
if (!metricsEnabled)
return 0;
assert pageMem != null;
return pageMem.loadedPages();
}
/**
* Updates pageReplaceRate metric.
*/
public void updatePageReplaceRate(long pageAge) {
if (metricsEnabled) {
pageReplaceRate.onHit();
pageReplaceAge.onHits(pageAge);
}
}
/**
* Increments dirtyPages counter.
*/
public void incrementDirtyPages() {
if (metricsEnabled)
dirtyPages.increment();
}
/**
* Decrements dirtyPages counter.
*/
public void decrementDirtyPages() {
if (metricsEnabled)
dirtyPages.decrement();
}
/**
* Resets dirtyPages counter to zero.
*/
public void resetDirtyPages() {
if (metricsEnabled)
dirtyPages.reset();
}
/**
* Increments totalAllocatedPages counter.
*/
public void incrementTotalAllocatedPages() {
if (metricsEnabled) {
totalAllocatedPages.increment();
updateAllocationRateMetrics();
}
}
/**
*
*/
private void updateAllocationRateMetrics() {
allocRate.onHit();
}
/**
* @param intervalNum Interval number.
*/
private long subInt(int intervalNum) {
return (rateTimeInterval * intervalNum) / subInts;
}
/**
*
*/
public void incrementLargeEntriesPages() {
if (metricsEnabled)
largeEntriesPages.increment();
}
/**
*
*/
public void decrementLargeEntriesPages() {
if (metricsEnabled)
largeEntriesPages.decrement();
}
/**
* Enable metrics.
*/
public void enableMetrics() {
metricsEnabled = true;
}
/**
* Disable metrics.
*/
public void disableMetrics() {
metricsEnabled = false;
}
/**
* @param persistenceEnabled Persistence enabled.
*/
public void persistenceEnabled(boolean persistenceEnabled) {
this.persistenceEnabled = persistenceEnabled;
}
/**
* @param pageMem Page mem.
*/
public void pageMemory(PageMemory pageMem) {
this.pageMem = pageMem;
}
/**
* @param rateTimeInterval Time interval (in milliseconds) used to calculate allocation/eviction rate.
*/
public void rateTimeInterval(long rateTimeInterval) {
this.rateTimeInterval = rateTimeInterval;
allocRate = new HitRateMetrics((int) rateTimeInterval, subInts);
pageReplaceRate = new HitRateMetrics((int)rateTimeInterval, subInts);
pageReplaceAge = new HitRateMetrics((int)rateTimeInterval, subInts);
}
/**
* Sets number of subintervals the whole rateTimeInterval will be split into to calculate allocation rate.
*
* @param subInts Number of subintervals.
*/
public void subIntervals(int subInts) {
assert subInts > 0;
if (this.subInts == subInts)
return;
if (rateTimeInterval / subInts < 10)
subInts = (int) rateTimeInterval / 10;
allocRate = new HitRateMetrics((int) rateTimeInterval, subInts);
pageReplaceRate = new HitRateMetrics((int)rateTimeInterval, subInts);
pageReplaceAge = new HitRateMetrics((int)rateTimeInterval, subInts);
}
}
|
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/DataRegionMetricsImpl.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.ignite.internal.processors.cache.persistence;
import org.apache.ignite.DataRegionMetrics;
import org.apache.ignite.configuration.DataRegionConfiguration;
import org.apache.ignite.internal.pagemem.PageMemory;
import org.apache.ignite.internal.processors.cache.ratemetrics.HitRateMetrics;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteOutClosure;
import org.jetbrains.annotations.Nullable;
import org.jsr166.LongAdder8;
/**
*
*/
public class DataRegionMetricsImpl implements DataRegionMetrics {
/** */
private final IgniteOutClosure<Float> fillFactorProvider;
/** */
private final LongAdder8 totalAllocatedPages = new LongAdder8();
/**
* Counter for number of pages occupied by large entries (one entry is larger than one page).
*/
private final LongAdder8 largeEntriesPages = new LongAdder8();
/** Counter for number of dirty pages. */
private LongAdder8 dirtyPages = new LongAdder8();
/** */
private volatile boolean metricsEnabled;
/** */
private boolean persistenceEnabled;
/** */
private volatile int subInts;
/** Allocation rate calculator. */
private volatile HitRateMetrics allocRate = new HitRateMetrics(60_000, 5);
/** */
private volatile HitRateMetrics pageReplaceRate = new HitRateMetrics(60_000, 5);
/** */
private volatile HitRateMetrics pageReplaceAge = new HitRateMetrics(60_000, 5);
/** */
private final DataRegionConfiguration memPlcCfg;
/** */
private PageMemory pageMem;
/** Time interval (in milliseconds) when allocations/evictions are counted to calculate rate. */
private volatile long rateTimeInterval;
/**
* @param memPlcCfg DataRegionConfiguration.
*/
public DataRegionMetricsImpl(DataRegionConfiguration memPlcCfg) {
this(memPlcCfg, null);
}
/**
* @param memPlcCfg DataRegionConfiguration.
*/
public DataRegionMetricsImpl(DataRegionConfiguration memPlcCfg, @Nullable IgniteOutClosure<Float> fillFactorProvider) {
this.memPlcCfg = memPlcCfg;
this.fillFactorProvider = fillFactorProvider;
metricsEnabled = memPlcCfg.isMetricsEnabled();
rateTimeInterval = memPlcCfg.getMetricsRateTimeInterval();
subInts = memPlcCfg.getMetricsSubIntervalCount();
}
/** {@inheritDoc} */
@Override public String getName() {
return U.maskName(memPlcCfg.getName());
}
/** {@inheritDoc} */
@Override public long getTotalAllocatedPages() {
return metricsEnabled ? totalAllocatedPages.longValue() : 0;
}
/** {@inheritDoc} */
@Override public float getAllocationRate() {
if (!metricsEnabled)
return 0;
return ((float)allocRate.getRate() * 1000) / rateTimeInterval;
}
/** {@inheritDoc} */
@Override public float getEvictionRate() {
return 0;
}
/** {@inheritDoc} */
@Override public float getLargeEntriesPagesPercentage() {
if (!metricsEnabled)
return 0;
return totalAllocatedPages.longValue() != 0 ?
(float) largeEntriesPages.doubleValue() / totalAllocatedPages.longValue()
: 0;
}
/** {@inheritDoc} */
@Override public float getPagesFillFactor() {
if (!metricsEnabled || fillFactorProvider == null)
return 0;
return fillFactorProvider.apply();
}
/** {@inheritDoc} */
@Override public long getDirtyPages() {
if (!metricsEnabled || !persistenceEnabled)
return 0;
return dirtyPages.longValue();
}
/** {@inheritDoc} */
@Override public float getPagesReplaceRate() {
if (!metricsEnabled || !persistenceEnabled)
return 0;
return ((float)pageReplaceRate.getRate() * 1000) / rateTimeInterval;
}
/** {@inheritDoc} */
@Override public float getPagesReplaceAge() {
if (!metricsEnabled || !persistenceEnabled)
return 0;
long rep = pageReplaceRate.getRate();
return rep == 0 ? 0 : ((float)pageReplaceAge.getRate() / rep);
}
/** {@inheritDoc} */
@Override public long getPhysicalMemoryPages() {
if (!metricsEnabled || !persistenceEnabled)
return 0;
assert pageMem != null;
return pageMem.loadedPages();
}
/**
* Updates pageReplaceRate metric.
*/
public void updatePageReplaceRate(long pageAge) {
if (metricsEnabled) {
pageReplaceRate.onHit();
pageReplaceAge.onHits(pageAge);
}
}
/**
* Increments dirtyPages counter.
*/
public void incrementDirtyPages() {
if (metricsEnabled)
dirtyPages.increment();
}
/**
* Decrements dirtyPages counter.
*/
public void decrementDirtyPages() {
if (metricsEnabled)
dirtyPages.decrement();
}
/**
* Resets dirtyPages counter to zero.
*/
public void resetDirtyPages() {
if (metricsEnabled)
dirtyPages.reset();
}
/**
* Increments totalAllocatedPages counter.
*/
public void incrementTotalAllocatedPages() {
if (metricsEnabled) {
totalAllocatedPages.increment();
updateAllocationRateMetrics();
}
}
/**
*
*/
private void updateAllocationRateMetrics() {
allocRate.onHit();
}
/**
* @param intervalNum Interval number.
*/
private long subInt(int intervalNum) {
return (rateTimeInterval * intervalNum) / subInts;
}
/**
*
*/
public void incrementLargeEntriesPages() {
if (metricsEnabled)
largeEntriesPages.increment();
}
/**
*
*/
public void decrementLargeEntriesPages() {
if (metricsEnabled)
largeEntriesPages.decrement();
}
/**
* Enable metrics.
*/
public void enableMetrics() {
metricsEnabled = true;
}
/**
* Disable metrics.
*/
public void disableMetrics() {
metricsEnabled = false;
}
/**
* @param persistenceEnabled Persistence enabled.
*/
public void persistenceEnabled(boolean persistenceEnabled) {
this.persistenceEnabled = persistenceEnabled;
}
/**
* @param pageMem Page mem.
*/
public void pageMemory(PageMemory pageMem) {
this.pageMem = pageMem;
}
/**
* @param rateTimeInterval Time interval (in milliseconds) used to calculate allocation/eviction rate.
*/
public void rateTimeInterval(long rateTimeInterval) {
this.rateTimeInterval = rateTimeInterval;
allocRate = new HitRateMetrics((int) rateTimeInterval, subInts);
pageReplaceRate = new HitRateMetrics((int)rateTimeInterval, subInts);
pageReplaceAge = new HitRateMetrics((int)rateTimeInterval, subInts);
}
/**
* Sets number of subintervals the whole rateTimeInterval will be split into to calculate allocation rate.
*
* @param subInts Number of subintervals.
*/
public void subIntervals(int subInts) {
assert subInts > 0;
if (this.subInts == subInts)
return;
if (rateTimeInterval / subInts < 10)
subInts = (int) rateTimeInterval / 10;
allocRate = new HitRateMetrics((int) rateTimeInterval, subInts);
pageReplaceRate = new HitRateMetrics((int)rateTimeInterval, subInts);
pageReplaceAge = new HitRateMetrics((int)rateTimeInterval, subInts);
}
}
|
IGNITE-6963 TotalAllocatedPages metric does not match PhysicalMemoryPages when persistence is disabled
Signed-off-by: Anton Vinogradov <8ccb8a3f7ac5bd9c4f1ab74cb453f7f32903fb1b@apache.org>
|
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/DataRegionMetricsImpl.java
|
IGNITE-6963 TotalAllocatedPages metric does not match PhysicalMemoryPages when persistence is disabled
|
|
Java
|
apache-2.0
|
bbcff68114fd017a9d1d256d6f8ec3e23035a709
| 0
|
finmath/finmath-lib,finmath/finmath-lib
|
/*
* (c) Copyright Christian P. Fries, Germany. Contact: email@christian-fries.de.
*
* Created on 26.05.2013
*/
package net.finmath.montecarlo.interestrate.models.covariance;
import java.util.Map;
import net.finmath.exception.CalculationException;
import net.finmath.montecarlo.AbstractRandomVariableFactory;
import net.finmath.stochastic.RandomVariable;
import net.finmath.stochastic.Scalar;
/**
* Exponential decay model build on top of a given covariance model.
*
* The model constructed for the <i>i</i>-th factor loading is
* <center>
* <i>(L<sub>i</sub>(t) + d) F<sub>i</sub>(t)</i>
* </center>
* where <i>d</i> is the displacement and <i>L<sub>i</sub></i> is
* the realization of the <i>i</i>-th component of the stochastic process and
* <i>F<sub>i</sub></i> is the factor loading from the given covariance model.
*
* The parameter of this model is a joint parameter vector, consisting
* of the parameter vector of the given base covariance model and
* appending the displacement parameter at the end.
*
* If this model is not calibrateable, its parameter vector is that of the
* covariance model, i.e., only the displacement parameter will be not
* part of the calibration.
*
* @author Christian Fries
* @version 1.0
*/
public class ExponentialDecayLocalVolatilityModel extends AbstractLIBORCovarianceModelParametric {
private static final long serialVersionUID = 4522227972747028512L;
private final AbstractRandomVariableFactory randomVariableFactory;
private final AbstractLIBORCovarianceModelParametric covarianceModel;
private final RandomVariable decay;
private boolean isCalibrateable = false;
/**
* Exponential decay model build on top of a standard covariance model.
*
* The model constructed for the <i>i</i>-th factor loading is
* <center>
* <i>(exp(- a t) F<sub>i</sub>(t)</i>
* </center>
* where <i>a</i> is the decay parameter and
* <i>F<sub>i</sub></i> is the factor loading from the given covariance model.
*
* The parameter of this model is a joint parameter vector, consisting
* of the parameter vector of the given base covariance model and
* appending the decay parameter at the end.
*
* If this model is not calibrateable, its parameter vector is that of the
* underlying covariance model, i.e., only the decay parameter will be not
* part of the calibration.
*
* @param covarianceModel The given covariance model specifying the factor loadings <i>F</i>.
* @param decay The decay <i>a</i>.
* @param isCalibrateable If true, the parameter <i>a</i> is a free parameter. Note that the covariance model may have its own parameter calibration settings.
*/
public ExponentialDecayLocalVolatilityModel(AbstractRandomVariableFactory randomVariableFactory, AbstractLIBORCovarianceModelParametric covarianceModel, RandomVariable decay, boolean isCalibrateable) {
super(covarianceModel.getTimeDiscretization(), covarianceModel.getLiborPeriodDiscretization(), covarianceModel.getNumberOfFactors());
this.randomVariableFactory = randomVariableFactory;
this.covarianceModel = covarianceModel;
this.decay = decay;
this.isCalibrateable = isCalibrateable;
}
/**
* Exponential decay model build on top of a standard covariance model.
*
* The model constructed for the <i>i</i>-th factor loading is
* <center>
* <i>(exp(- a t) F<sub>i</sub>(t)</i>
* </center>
* where <i>a</i> is the decay parameter and
* <i>F<sub>i</sub></i> is the factor loading from the given covariance model.
*
* The parameter of this model is a joint parameter vector, consisting
* of the parameter vector of the given base covariance model and
* appending the decay parameter at the end.
*
* If this model is not calibrateable, its parameter vector is that of the
* underlying covariance model, i.e., only the decay parameter will be not
* part of the calibration.
*
* @param covarianceModel The given covariance model specifying the factor loadings <i>F</i>.
* @param decay The displacement <i>a</i>.
* @param isCalibrateable If true, the parameter <i>a</i> is a free parameter. Note that the covariance model may have its own parameter calibration settings.
*/
public ExponentialDecayLocalVolatilityModel(AbstractLIBORCovarianceModelParametric covarianceModel, double decay, boolean isCalibrateable) {
super(covarianceModel.getTimeDiscretization(), covarianceModel.getLiborPeriodDiscretization(), covarianceModel.getNumberOfFactors());
randomVariableFactory = null;
this.covarianceModel = covarianceModel;
this.decay = new Scalar(decay);
this.isCalibrateable = isCalibrateable;
}
@Override
public Object clone() {
return new ExponentialDecayLocalVolatilityModel(randomVariableFactory, (AbstractLIBORCovarianceModelParametric) covarianceModel.clone(), decay, isCalibrateable);
}
/**
* Returns the base covariance model, i.e., the model providing the factor loading <i>F</i>
* such that this model's <i>i</i>-th factor loading is
* <center>
* <i>(a L<sub>i,0</sub> + (1-a)L<sub>i</sub>(t)) F<sub>i</sub>(t)</i>
* </center>
* where <i>a</i> is the displacement and <i>L<sub>i</sub></i> is
* the realization of the <i>i</i>-th component of the stochastic process and
* <i>F<sub>i</sub></i> is the factor loading loading from the given covariance model.
*
* @return The base covariance model.
*/
public AbstractLIBORCovarianceModelParametric getBaseCovarianceModel() {
return covarianceModel;
}
@Override
public RandomVariable[] getParameter() {
if(!isCalibrateable) {
return covarianceModel.getParameter();
}
RandomVariable[] covarianceParameters = covarianceModel.getParameter();
if(covarianceParameters == null) {
return new RandomVariable[] { decay };
}
// Append decay to the end of covarianceParameters
RandomVariable[] jointParameters = new RandomVariable[covarianceParameters.length+1];
System.arraycopy(covarianceParameters, 0, jointParameters, 0, covarianceParameters.length);
jointParameters[covarianceParameters.length] = decay;
return jointParameters;
}
@Override
public double[] getParameterAsDouble() {
RandomVariable[] parameters = getParameter();
double[] parametersAsDouble = new double[parameters.length];
for(int i=0; i<parameters.length; i++) {
parametersAsDouble[i] = parameters[i].doubleValue();
}
return parametersAsDouble;
}
@Override
public AbstractLIBORCovarianceModelParametric getCloneWithModifiedParameters(RandomVariable[] parameters) {
if(parameters == null || parameters.length == 0) {
return this;
}
if(!isCalibrateable) {
return new ExponentialDecayLocalVolatilityModel(randomVariableFactory, covarianceModel.getCloneWithModifiedParameters(parameters), decay, isCalibrateable);
}
RandomVariable[] covarianceParameters = new RandomVariable[parameters.length-1];
System.arraycopy(parameters, 0, covarianceParameters, 0, covarianceParameters.length);
AbstractLIBORCovarianceModelParametric newCovarianceModel = covarianceModel.getCloneWithModifiedParameters(covarianceParameters);
RandomVariable newDisplacement = parameters[covarianceParameters.length];
return new ExponentialDecayLocalVolatilityModel(randomVariableFactory, newCovarianceModel, newDisplacement, isCalibrateable);
}
@Override
public AbstractLIBORCovarianceModelParametric getCloneWithModifiedParameters(double[] parameters) {
return getCloneWithModifiedParameters(Scalar.arrayOf(parameters));
}
@Override
public RandomVariable[] getFactorLoading(int timeIndex, int component, RandomVariable[] realizationAtTimeIndex) {
RandomVariable[] factorLoading = covarianceModel.getFactorLoading(timeIndex, component, realizationAtTimeIndex);
double time = getTimeDiscretization().getTime(timeIndex);
for (int factorIndex = 0; factorIndex < factorLoading.length; factorIndex++) {
factorLoading[factorIndex] = factorLoading[factorIndex].mult(decay.mult(-time).exp());
}
return factorLoading;
}
@Override
public RandomVariable getFactorLoadingPseudoInverse(int timeIndex, int component, int factor, RandomVariable[] realizationAtTimeIndex) {
throw new UnsupportedOperationException();
}
public RandomVariable getDisplacement() {
return decay;
}
@Override
public AbstractLIBORCovarianceModelParametric getCloneWithModifiedData(Map<String, Object> dataModified)
throws CalculationException {
RandomVariable newDecay = decay;
boolean isCalibrateable = this.isCalibrateable;
AbstractLIBORCovarianceModelParametric covarianceModel = this.covarianceModel;
AbstractRandomVariableFactory newRandomVariableFactory = randomVariableFactory;
if(dataModified != null) {
if(dataModified.containsKey("randomVariableFactory")) {
newRandomVariableFactory = (AbstractRandomVariableFactory)dataModified.get("randomVariableFactory");
newDecay = randomVariableFactory.createRandomVariable(newDecay.doubleValue());
}
if (!dataModified.containsKey("covarianceModel")) {
covarianceModel = covarianceModel.getCloneWithModifiedData(dataModified);
}
// Explicitly passed covarianceModel has priority
covarianceModel = (AbstractLIBORCovarianceModelParametric)dataModified.getOrDefault("covarianceModel", covarianceModel);
isCalibrateable = (boolean)dataModified.getOrDefault("isCalibrateable", isCalibrateable);
if (dataModified.getOrDefault("decay", newDecay) instanceof RandomVariable) {
newDecay = (RandomVariable) dataModified.getOrDefault("decay", newDecay);
} else if (newRandomVariableFactory == null) {
newDecay = new Scalar((double) dataModified.get("decay"));
} else {
newDecay = newRandomVariableFactory.createRandomVariable((double) dataModified.get("decay"));
}
}
AbstractLIBORCovarianceModelParametric newModel = new ExponentialDecayLocalVolatilityModel(newRandomVariableFactory, covarianceModel, newDecay, isCalibrateable);
return newModel;
}
}
|
src/main/java/net/finmath/montecarlo/interestrate/models/covariance/ExponentialDecayLocalVolatilityModel.java
|
/*
* (c) Copyright Christian P. Fries, Germany. Contact: email@christian-fries.de.
*
* Created on 26.05.2013
*/
package net.finmath.montecarlo.interestrate.models.covariance;
import java.util.Map;
import net.finmath.exception.CalculationException;
import net.finmath.marketdata.model.curves.ForwardCurve;
import net.finmath.montecarlo.AbstractRandomVariableFactory;
import net.finmath.montecarlo.RandomVariableFactory;
import net.finmath.stochastic.RandomVariable;
import net.finmath.stochastic.Scalar;
/**
* Exponential decay model build on top of a given covariance model.
*
* The model constructed for the <i>i</i>-th factor loading is
* <center>
* <i>(L<sub>i</sub>(t) + d) F<sub>i</sub>(t)</i>
* </center>
* where <i>d</i> is the displacement and <i>L<sub>i</sub></i> is
* the realization of the <i>i</i>-th component of the stochastic process and
* <i>F<sub>i</sub></i> is the factor loading from the given covariance model.
*
* The parameter of this model is a joint parameter vector, consisting
* of the parameter vector of the given base covariance model and
* appending the displacement parameter at the end.
*
* If this model is not calibrateable, its parameter vector is that of the
* covariance model, i.e., only the displacement parameter will be not
* part of the calibration.
*
* @author Christian Fries
* @version 1.0
*/
public class ExponentialDecayLocalVolatilityModel extends AbstractLIBORCovarianceModelParametric {
private static final long serialVersionUID = 4522227972747028512L;
private final AbstractRandomVariableFactory randomVariableFactory;
private final AbstractLIBORCovarianceModelParametric covarianceModel;
private final RandomVariable decay;
private boolean isCalibrateable = false;
/**
* Exponential decay model build on top of a standard covariance model.
*
* The model constructed for the <i>i</i>-th factor loading is
* <center>
* <i>(exp(- a t) F<sub>i</sub>(t)</i>
* </center>
* where <i>a</i> is the decay parameter and
* <i>F<sub>i</sub></i> is the factor loading from the given covariance model.
*
* The parameter of this model is a joint parameter vector, consisting
* of the parameter vector of the given base covariance model and
* appending the decay parameter at the end.
*
* If this model is not calibrateable, its parameter vector is that of the
* underlying covariance model, i.e., only the decay parameter will be not
* part of the calibration.
*
* @param covarianceModel The given covariance model specifying the factor loadings <i>F</i>.
* @param decay The decay <i>a</i>.
* @param isCalibrateable If true, the parameter <i>a</i> is a free parameter. Note that the covariance model may have its own parameter calibration settings.
*/
public ExponentialDecayLocalVolatilityModel(AbstractRandomVariableFactory randomVariableFactory, AbstractLIBORCovarianceModelParametric covarianceModel, RandomVariable decay, boolean isCalibrateable) {
super(covarianceModel.getTimeDiscretization(), covarianceModel.getLiborPeriodDiscretization(), covarianceModel.getNumberOfFactors());
this.randomVariableFactory = randomVariableFactory;
this.covarianceModel = covarianceModel;
this.decay = decay;
this.isCalibrateable = isCalibrateable;
}
/**
* Exponential decay model build on top of a standard covariance model.
*
* The model constructed for the <i>i</i>-th factor loading is
* <center>
* <i>(exp(- a t) F<sub>i</sub>(t)</i>
* </center>
* where <i>a</i> is the decay parameter and
* <i>F<sub>i</sub></i> is the factor loading from the given covariance model.
*
* The parameter of this model is a joint parameter vector, consisting
* of the parameter vector of the given base covariance model and
* appending the decay parameter at the end.
*
* If this model is not calibrateable, its parameter vector is that of the
* underlying covariance model, i.e., only the decay parameter will be not
* part of the calibration.
*
* @param covarianceModel The given covariance model specifying the factor loadings <i>F</i>.
* @param decay The displacement <i>a</i>.
* @param isCalibrateable If true, the parameter <i>a</i> is a free parameter. Note that the covariance model may have its own parameter calibration settings.
*/
public ExponentialDecayLocalVolatilityModel(AbstractLIBORCovarianceModelParametric covarianceModel, double decay, boolean isCalibrateable) {
super(covarianceModel.getTimeDiscretization(), covarianceModel.getLiborPeriodDiscretization(), covarianceModel.getNumberOfFactors());
this.randomVariableFactory = null;
this.covarianceModel = covarianceModel;
this.decay = new Scalar(decay);
this.isCalibrateable = isCalibrateable;
}
@Override
public Object clone() {
return new ExponentialDecayLocalVolatilityModel(randomVariableFactory, (AbstractLIBORCovarianceModelParametric) covarianceModel.clone(), decay, isCalibrateable);
}
/**
* Returns the base covariance model, i.e., the model providing the factor loading <i>F</i>
* such that this model's <i>i</i>-th factor loading is
* <center>
* <i>(a L<sub>i,0</sub> + (1-a)L<sub>i</sub>(t)) F<sub>i</sub>(t)</i>
* </center>
* where <i>a</i> is the displacement and <i>L<sub>i</sub></i> is
* the realization of the <i>i</i>-th component of the stochastic process and
* <i>F<sub>i</sub></i> is the factor loading loading from the given covariance model.
*
* @return The base covariance model.
*/
public AbstractLIBORCovarianceModelParametric getBaseCovarianceModel() {
return covarianceModel;
}
@Override
public RandomVariable[] getParameter() {
if(!isCalibrateable) {
return covarianceModel.getParameter();
}
RandomVariable[] covarianceParameters = covarianceModel.getParameter();
if(covarianceParameters == null) {
return new RandomVariable[] { decay };
}
// Append decay to the end of covarianceParameters
RandomVariable[] jointParameters = new RandomVariable[covarianceParameters.length+1];
System.arraycopy(covarianceParameters, 0, jointParameters, 0, covarianceParameters.length);
jointParameters[covarianceParameters.length] = decay;
return jointParameters;
}
@Override
public double[] getParameterAsDouble() {
RandomVariable[] parameters = getParameter();
double[] parametersAsDouble = new double[parameters.length];
for(int i=0; i<parameters.length; i++) {
parametersAsDouble[i] = parameters[i].doubleValue();
}
return parametersAsDouble;
}
@Override
public AbstractLIBORCovarianceModelParametric getCloneWithModifiedParameters(RandomVariable[] parameters) {
if(parameters == null || parameters.length == 0) {
return this;
}
if(!isCalibrateable) {
return new ExponentialDecayLocalVolatilityModel(randomVariableFactory, covarianceModel.getCloneWithModifiedParameters(parameters), decay, isCalibrateable);
}
RandomVariable[] covarianceParameters = new RandomVariable[parameters.length-1];
System.arraycopy(parameters, 0, covarianceParameters, 0, covarianceParameters.length);
AbstractLIBORCovarianceModelParametric newCovarianceModel = covarianceModel.getCloneWithModifiedParameters(covarianceParameters);
RandomVariable newDisplacement = parameters[covarianceParameters.length];
return new ExponentialDecayLocalVolatilityModel(randomVariableFactory, newCovarianceModel, newDisplacement, isCalibrateable);
}
@Override
public AbstractLIBORCovarianceModelParametric getCloneWithModifiedParameters(double[] parameters) {
return getCloneWithModifiedParameters(Scalar.arrayOf(parameters));
}
@Override
public RandomVariable[] getFactorLoading(int timeIndex, int component, RandomVariable[] realizationAtTimeIndex) {
RandomVariable[] factorLoading = covarianceModel.getFactorLoading(timeIndex, component, realizationAtTimeIndex);
double time = getTimeDiscretization().getTime(timeIndex);
for (int factorIndex = 0; factorIndex < factorLoading.length; factorIndex++) {
factorLoading[factorIndex] = factorLoading[factorIndex].mult(decay.mult(-time).exp());
}
return factorLoading;
}
@Override
public RandomVariable getFactorLoadingPseudoInverse(int timeIndex, int component, int factor, RandomVariable[] realizationAtTimeIndex) {
throw new UnsupportedOperationException();
}
public RandomVariable getDisplacement() {
return decay;
}
@Override
public AbstractLIBORCovarianceModelParametric getCloneWithModifiedData(Map<String, Object> dataModified)
throws CalculationException {
RandomVariable newDecay = this.decay;
boolean isCalibrateable = this.isCalibrateable;
AbstractLIBORCovarianceModelParametric covarianceModel = this.covarianceModel;
AbstractRandomVariableFactory newRandomVariableFactory = randomVariableFactory;
if(dataModified != null) {
if(dataModified.containsKey("randomVariableFactory")) {
newRandomVariableFactory = (AbstractRandomVariableFactory)dataModified.get("randomVariableFactory");
newDecay = randomVariableFactory.createRandomVariable(newDecay.doubleValue());
}
if (!dataModified.containsKey("covarianceModel")) {
covarianceModel = covarianceModel.getCloneWithModifiedData(dataModified);
}
// Explicitly passed covarianceModel has priority
covarianceModel = (AbstractLIBORCovarianceModelParametric)dataModified.getOrDefault("covarianceModel", covarianceModel);
isCalibrateable = (boolean)dataModified.getOrDefault("isCalibrateable", isCalibrateable);
if (dataModified.getOrDefault("decay", newDecay) instanceof RandomVariable) {
newDecay = (RandomVariable) dataModified.getOrDefault("decay", newDecay);
} else if (newRandomVariableFactory == null) {
newDecay = new Scalar((double) dataModified.get("decay"));
} else {
newDecay = newRandomVariableFactory.createRandomVariable((double) dataModified.get("decay"));
}
}
AbstractLIBORCovarianceModelParametric newModel = new ExponentialDecayLocalVolatilityModel(newRandomVariableFactory, covarianceModel, newDecay, isCalibrateable);
return newModel;
}
}
|
Clean up.
|
src/main/java/net/finmath/montecarlo/interestrate/models/covariance/ExponentialDecayLocalVolatilityModel.java
|
Clean up.
|
|
Java
|
apache-2.0
|
7e6ebc3cb3219105e1a8ea505c74e2f93c7d1951
| 0
|
RohanHart/camel,jamesnetherton/camel,zregvart/camel,alvinkwekel/camel,pkletsko/camel,jlpedrosa/camel,onders86/camel,isavin/camel,veithen/camel,jarst/camel,bgaudaen/camel,driseley/camel,ssharma/camel,nboukhed/camel,jkorab/camel,anton-k11/camel,lburgazzoli/camel,NickCis/camel,yuruki/camel,bhaveshdt/camel,Fabryprog/camel,bhaveshdt/camel,lburgazzoli/apache-camel,RohanHart/camel,yuruki/camel,tkopczynski/camel,dmvolod/camel,tkopczynski/camel,snurmine/camel,gnodet/camel,christophd/camel,jmandawg/camel,gautric/camel,prashant2402/camel,JYBESSON/camel,lburgazzoli/camel,nikvaessen/camel,pmoerenhout/camel,jarst/camel,ssharma/camel,driseley/camel,RohanHart/camel,CodeSmell/camel,mgyongyosi/camel,neoramon/camel,scranton/camel,gilfernandes/camel,nikvaessen/camel,onders86/camel,cunningt/camel,w4tson/camel,bgaudaen/camel,anton-k11/camel,FingolfinTEK/camel,apache/camel,driseley/camel,ssharma/camel,veithen/camel,pax95/camel,adessaigne/camel,driseley/camel,jkorab/camel,bhaveshdt/camel,yuruki/camel,NickCis/camel,ullgren/camel,jmandawg/camel,RohanHart/camel,scranton/camel,lburgazzoli/camel,sirlatrom/camel,lburgazzoli/camel,punkhorn/camel-upstream,tadayosi/camel,NickCis/camel,sverkera/camel,sverkera/camel,pax95/camel,tdiesler/camel,yuruki/camel,sirlatrom/camel,jlpedrosa/camel,isavin/camel,onders86/camel,oalles/camel,rmarting/camel,w4tson/camel,JYBESSON/camel,borcsokj/camel,anoordover/camel,tlehoux/camel,nikvaessen/camel,akhettar/camel,cunningt/camel,apache/camel,jamesnetherton/camel,cunningt/camel,Thopap/camel,lburgazzoli/camel,scranton/camel,ssharma/camel,pkletsko/camel,scranton/camel,tdiesler/camel,oalles/camel,jmandawg/camel,jlpedrosa/camel,mcollovati/camel,chirino/camel,mgyongyosi/camel,ssharma/camel,snurmine/camel,nboukhed/camel,onders86/camel,salikjan/camel,davidkarlsen/camel,tlehoux/camel,FingolfinTEK/camel,sabre1041/camel,christophd/camel,akhettar/camel,nikhilvibhav/camel,mgyongyosi/camel,gnodet/camel,acartapanis/camel,jmandawg/camel,dmvolod/camel,allancth/camel,jarst/camel,pax95/camel,w4tson/camel,sverkera/camel,pax95/camel,yuruki/camel,pax95/camel,lburgazzoli/apache-camel,acartapanis/camel,neoramon/camel,tkopczynski/camel,tlehoux/camel,gnodet/camel,JYBESSON/camel,mgyongyosi/camel,nicolaferraro/camel,lburgazzoli/apache-camel,anton-k11/camel,apache/camel,sirlatrom/camel,rmarting/camel,nboukhed/camel,prashant2402/camel,acartapanis/camel,anoordover/camel,objectiser/camel,lburgazzoli/apache-camel,tkopczynski/camel,tdiesler/camel,lburgazzoli/apache-camel,snurmine/camel,tkopczynski/camel,rmarting/camel,Thopap/camel,neoramon/camel,NickCis/camel,chirino/camel,dmvolod/camel,prashant2402/camel,gnodet/camel,DariusX/camel,tlehoux/camel,bhaveshdt/camel,isavin/camel,drsquidop/camel,alvinkwekel/camel,YoshikiHigo/camel,bhaveshdt/camel,oalles/camel,akhettar/camel,pkletsko/camel,hqstevenson/camel,neoramon/camel,chirino/camel,borcsokj/camel,pax95/camel,sabre1041/camel,FingolfinTEK/camel,punkhorn/camel-upstream,NickCis/camel,pkletsko/camel,sverkera/camel,nicolaferraro/camel,tkopczynski/camel,kevinearls/camel,akhettar/camel,jamesnetherton/camel,adessaigne/camel,adessaigne/camel,curso007/camel,RohanHart/camel,kevinearls/camel,mgyongyosi/camel,DariusX/camel,alvinkwekel/camel,acartapanis/camel,prashant2402/camel,sabre1041/camel,drsquidop/camel,allancth/camel,mcollovati/camel,nikvaessen/camel,JYBESSON/camel,salikjan/camel,jonmcewen/camel,nikhilvibhav/camel,w4tson/camel,neoramon/camel,apache/camel,JYBESSON/camel,kevinearls/camel,sirlatrom/camel,mcollovati/camel,oalles/camel,ullgren/camel,jlpedrosa/camel,allancth/camel,YoshikiHigo/camel,punkhorn/camel-upstream,veithen/camel,acartapanis/camel,pmoerenhout/camel,zregvart/camel,pmoerenhout/camel,allancth/camel,punkhorn/camel-upstream,nikhilvibhav/camel,gilfernandes/camel,davidkarlsen/camel,curso007/camel,hqstevenson/camel,jamesnetherton/camel,YoshikiHigo/camel,FingolfinTEK/camel,rmarting/camel,jlpedrosa/camel,jonmcewen/camel,jmandawg/camel,snurmine/camel,nicolaferraro/camel,pmoerenhout/camel,anoordover/camel,hqstevenson/camel,prashant2402/camel,anoordover/camel,tdiesler/camel,pkletsko/camel,nboukhed/camel,CodeSmell/camel,sirlatrom/camel,zregvart/camel,gautric/camel,akhettar/camel,gautric/camel,driseley/camel,jamesnetherton/camel,onders86/camel,borcsokj/camel,hqstevenson/camel,isavin/camel,chirino/camel,scranton/camel,RohanHart/camel,tdiesler/camel,tadayosi/camel,nikvaessen/camel,cunningt/camel,dmvolod/camel,jamesnetherton/camel,davidkarlsen/camel,anton-k11/camel,yuruki/camel,bgaudaen/camel,acartapanis/camel,nboukhed/camel,drsquidop/camel,jkorab/camel,DariusX/camel,nboukhed/camel,anton-k11/camel,tdiesler/camel,drsquidop/camel,jarst/camel,objectiser/camel,rmarting/camel,onders86/camel,christophd/camel,gilfernandes/camel,anton-k11/camel,anoordover/camel,akhettar/camel,CodeSmell/camel,alvinkwekel/camel,lburgazzoli/camel,drsquidop/camel,jmandawg/camel,Thopap/camel,ullgren/camel,allancth/camel,snurmine/camel,kevinearls/camel,borcsokj/camel,Thopap/camel,isavin/camel,hqstevenson/camel,sirlatrom/camel,adessaigne/camel,allancth/camel,gilfernandes/camel,jkorab/camel,gnodet/camel,lburgazzoli/apache-camel,jonmcewen/camel,gautric/camel,tadayosi/camel,tadayosi/camel,chirino/camel,dmvolod/camel,anoordover/camel,tlehoux/camel,curso007/camel,mgyongyosi/camel,kevinearls/camel,gautric/camel,prashant2402/camel,veithen/camel,jkorab/camel,jonmcewen/camel,gilfernandes/camel,objectiser/camel,FingolfinTEK/camel,adessaigne/camel,Fabryprog/camel,NickCis/camel,ullgren/camel,sverkera/camel,sabre1041/camel,borcsokj/camel,nikhilvibhav/camel,Fabryprog/camel,borcsokj/camel,Fabryprog/camel,jarst/camel,JYBESSON/camel,YoshikiHigo/camel,davidkarlsen/camel,snurmine/camel,apache/camel,drsquidop/camel,sverkera/camel,neoramon/camel,jkorab/camel,sabre1041/camel,nikvaessen/camel,isavin/camel,w4tson/camel,rmarting/camel,jonmcewen/camel,pmoerenhout/camel,curso007/camel,bhaveshdt/camel,jonmcewen/camel,pmoerenhout/camel,cunningt/camel,DariusX/camel,tlehoux/camel,jlpedrosa/camel,YoshikiHigo/camel,veithen/camel,mcollovati/camel,pkletsko/camel,bgaudaen/camel,dmvolod/camel,gilfernandes/camel,cunningt/camel,FingolfinTEK/camel,tadayosi/camel,sabre1041/camel,hqstevenson/camel,CodeSmell/camel,ssharma/camel,YoshikiHigo/camel,jarst/camel,scranton/camel,curso007/camel,oalles/camel,bgaudaen/camel,Thopap/camel,nicolaferraro/camel,apache/camel,kevinearls/camel,zregvart/camel,christophd/camel,curso007/camel,tadayosi/camel,veithen/camel,christophd/camel,bgaudaen/camel,objectiser/camel,Thopap/camel,chirino/camel,adessaigne/camel,christophd/camel,w4tson/camel,oalles/camel,driseley/camel,gautric/camel
|
/**
* 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.camel.maven.packaging;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import static org.apache.camel.maven.packaging.PackageHelper.loadText;
/**
* Prepares the camel catalog to include component, data format, and eip descriptors,
* and generates a report.
*
* @goal prepare-catalog
*/
public class PrepareCatalogMojo extends AbstractMojo {
public static final int BUFFER_SIZE = 128 * 1024;
private static final String[] EXCLUDE_DOC_FILES = {"camel-core-osgi", "camel-core-xml", "camel-http-common", "camel-jetty", "camel-jetty-common"};
private static final Pattern LABEL_PATTERN = Pattern.compile("\\\"label\\\":\\s\\\"([\\w,]+)\\\"");
private static final int UNUSED_LABELS_WARN = 15;
/**
* The maven project.
*
* @parameter property="project"
* @required
* @readonly
*/
protected MavenProject project;
/**
* Whether to validate if the components, data formats, and languages are properly documented and have all the needed details.
*
* @parameter default-value="true"
*/
protected Boolean validate;
/**
* The output directory for components catalog
*
* @parameter default-value="${project.build.directory}/classes/org/apache/camel/catalog/components"
*/
protected File componentsOutDir;
/**
* The output directory for dataformats catalog
*
* @parameter default-value="${project.build.directory}/classes/org/apache/camel/catalog/dataformats"
*/
protected File dataFormatsOutDir;
/**
* The output directory for languages catalog
*
* @parameter default-value="${project.build.directory}/classes/org/apache/camel/catalog/languages"
*/
protected File languagesOutDir;
/**
* The output directory for documents catalog
*
* @parameter default-value="${project.build.directory}/classes/org/apache/camel/catalog/docs"
*/
protected File documentsOutDir;
/**
* The output directory for models catalog
*
* @parameter default-value="${project.build.directory}/classes/org/apache/camel/catalog/models"
*/
protected File modelsOutDir;
/**
* The output directory for archetypes catalog
*
* @parameter default-value="${project.build.directory}/classes/org/apache/camel/catalog/archetypes"
*/
protected File archetypesOutDir;
/**
* The output directory for XML schemas catalog
*
* @parameter default-value="${project.build.directory}/classes/org/apache/camel/catalog/schemas"
*/
protected File schemasOutDir;
/**
* The components directory where all the Apache Camel components are
*
* @parameter default-value="${project.build.directory}/../../../components"
*/
protected File componentsDir;
/**
* The camel-core directory where camel-core components are
*
* @parameter default-value="${project.build.directory}/../../../camel-core"
*/
protected File coreDir;
/**
* The archetypes directory where all the Apache Camel Maven archetypes are
*
* @parameter default-value="${project.build.directory}/../../../tooling/archetypes"
*/
protected File archetypesDir;
/**
* The directory where the camel-spring XML schema are
*
* @parameter default-value="${project.build.directory}/../../../components/camel-spring/target/schema"
*/
protected File springSchemaDir;
/**
* The directory where the camel-blueprint XML schema are
*
* @parameter default-value="${project.build.directory}/../../../components/camel-blueprint/target/schema"
*/
protected File blueprintSchemaDir;
/**
* Maven ProjectHelper.
*
* @component
* @readonly
*/
private MavenProjectHelper projectHelper;
/**
* Execute goal.
*
* @throws org.apache.maven.plugin.MojoExecutionException execution of the main class or one of the
* threads it generated failed.
* @throws org.apache.maven.plugin.MojoFailureException something bad happened...
*/
public void execute() throws MojoExecutionException, MojoFailureException {
executeModel();
executeComponents();
executeDataFormats();
executeLanguages();
executeDocuments();
executeArchetypes();
executeXmlSchemas();
}
protected void executeModel() throws MojoExecutionException, MojoFailureException {
getLog().info("================================================================================");
getLog().info("Copying all Camel model json descriptors");
// lets use sorted set/maps
Set<File> jsonFiles = new TreeSet<File>();
Set<File> duplicateJsonFiles = new TreeSet<File>();
Set<File> missingLabels = new TreeSet<File>();
Set<File> missingJavaDoc = new TreeSet<File>();
Map<String, Set<String>> usedLabels = new TreeMap<String, Set<String>>();
// find all json files in camel-core
if (coreDir != null && coreDir.isDirectory()) {
File target = new File(coreDir, "target/classes/org/apache/camel/model");
PackageHelper.findJsonFiles(target, jsonFiles, new PackageHelper.CamelComponentsModelFilter());
}
getLog().info("Found " + jsonFiles.size() + " model json files");
// make sure to create out dir
modelsOutDir.mkdirs();
for (File file : jsonFiles) {
File to = new File(modelsOutDir, file.getName());
if (to.exists()) {
duplicateJsonFiles.add(to);
getLog().warn("Duplicate model name detected: " + to);
}
try {
copyFile(file, to);
} catch (IOException e) {
throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
}
try {
// check if we have a label as we want the eip to include labels
String text = loadText(new FileInputStream(file));
// just do a basic label check
if (text.contains("\"label\": \"\"")) {
missingLabels.add(file);
} else {
String name = asComponentName(file);
Matcher matcher = LABEL_PATTERN.matcher(text);
// grab the label, and remember it in the used labels
if (matcher.find()) {
String label = matcher.group(1);
String[] labels = label.split(",");
for (String s : labels) {
Set<String> models = usedLabels.get(s);
if (models == null) {
models = new TreeSet<String>();
usedLabels.put(s, models);
}
models.add(name);
}
}
}
// check all the properties if they have description
List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("properties", text, true);
for (Map<String, String> row : rows) {
String name = row.get("name");
// skip checking these as they have no documentation
if ("outputs".equals(name)) {
continue;
}
String doc = row.get("description");
if (doc == null || doc.isEmpty()) {
missingJavaDoc.add(file);
break;
}
}
} catch (IOException e) {
// ignore
}
}
File all = new File(modelsOutDir, "../models.properties");
try {
FileOutputStream fos = new FileOutputStream(all, false);
String[] names = modelsOutDir.list();
List<String> models = new ArrayList<String>();
// sort the names
for (String name : names) {
if (name.endsWith(".json")) {
// strip out .json from the name
String modelName = name.substring(0, name.length() - 5);
models.add(modelName);
}
}
Collections.sort(models);
for (String name : models) {
fos.write(name.getBytes());
fos.write("\n".getBytes());
}
fos.close();
} catch (IOException e) {
throw new MojoFailureException("Error writing to file " + all);
}
printModelsReport(jsonFiles, duplicateJsonFiles, missingLabels, usedLabels, missingJavaDoc);
}
protected void executeComponents() throws MojoExecutionException, MojoFailureException {
getLog().info("Copying all Camel component json descriptors");
// lets use sorted set/maps
Set<File> jsonFiles = new TreeSet<File>();
Set<File> duplicateJsonFiles = new TreeSet<File>();
Set<File> componentFiles = new TreeSet<File>();
Set<File> missingComponents = new TreeSet<File>();
Map<String, Set<String>> usedComponentLabels = new TreeMap<String, Set<String>>();
Set<String> usedOptionLabels = new TreeSet<String>();
Set<String> unlabeledOptions = new TreeSet<String>();
// find all json files in components and camel-core
if (componentsDir != null && componentsDir.isDirectory()) {
File[] components = componentsDir.listFiles();
if (components != null) {
for (File dir : components) {
// skip camel-spring-dm
if (dir.isDirectory() && "camel-spring-dm".equals(dir.getName())) {
continue;
}
if (dir.isDirectory() && !"target".equals(dir.getName())) {
File target = new File(dir, "target/classes");
// special for camel-salesforce which is in a sub dir
if ("camel-salesforce".equals(dir.getName())) {
target = new File(dir, "camel-salesforce-component/target/classes");
} else if ("camel-linkedin".equals(dir.getName())) {
target = new File(dir, "camel-linkedin-component/target/classes");
}
int before = componentFiles.size();
int before2 = jsonFiles.size();
findComponentFilesRecursive(target, jsonFiles, componentFiles, new CamelComponentsFileFilter());
int after = componentFiles.size();
int after2 = jsonFiles.size();
if (before != after && before2 == after2) {
missingComponents.add(dir);
}
}
}
}
}
if (coreDir != null && coreDir.isDirectory()) {
File target = new File(coreDir, "target/classes");
int before = componentFiles.size();
int before2 = jsonFiles.size();
findComponentFilesRecursive(target, jsonFiles, componentFiles, new CamelComponentsFileFilter());
int after = componentFiles.size();
int after2 = jsonFiles.size();
if (before != after && before2 == after2) {
missingComponents.add(coreDir);
}
}
getLog().info("Found " + componentFiles.size() + " component.properties files");
getLog().info("Found " + jsonFiles.size() + " component json files");
// make sure to create out dir
componentsOutDir.mkdirs();
for (File file : jsonFiles) {
File to = new File(componentsOutDir, file.getName());
if (to.exists()) {
duplicateJsonFiles.add(to);
getLog().warn("Duplicate component name detected: " + to);
}
try {
copyFile(file, to);
} catch (IOException e) {
throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
}
// check if we have a component label as we want the components to include labels
try {
String text = loadText(new FileInputStream(file));
String name = asComponentName(file);
Matcher matcher = LABEL_PATTERN.matcher(text);
// grab the label, and remember it in the used labels
if (matcher.find()) {
String label = matcher.group(1);
String[] labels = label.split(",");
for (String s : labels) {
Set<String> components = usedComponentLabels.get(s);
if (components == null) {
components = new TreeSet<String>();
usedComponentLabels.put(s, components);
}
components.add(name);
}
}
// check all the component options and grab the label(s) they use
List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("componentProperties", text, true);
for (Map<String, String> row : rows) {
String label = row.get("label");
if (label != null && !label.isEmpty()) {
String[] parts = label.split(",");
for (String part : parts) {
usedOptionLabels.add(part);
}
}
}
// check all the endpoint options and grab the label(s) they use
int unused = 0;
rows = JSonSchemaHelper.parseJsonSchema("properties", text, true);
for (Map<String, String> row : rows) {
String label = row.get("label");
if (label != null && !label.isEmpty()) {
String[] parts = label.split(",");
for (String part : parts) {
usedOptionLabels.add(part);
}
} else {
unused++;
}
}
if (unused >= UNUSED_LABELS_WARN) {
unlabeledOptions.add(name);
}
} catch (IOException e) {
// ignore
}
}
File all = new File(componentsOutDir, "../components.properties");
try {
FileOutputStream fos = new FileOutputStream(all, false);
String[] names = componentsOutDir.list();
List<String> components = new ArrayList<String>();
// sort the names
for (String name : names) {
if (name.endsWith(".json")) {
// strip out .json from the name
String componentName = name.substring(0, name.length() - 5);
components.add(componentName);
}
}
Collections.sort(components);
for (String name : components) {
fos.write(name.getBytes());
fos.write("\n".getBytes());
}
fos.close();
} catch (IOException e) {
throw new MojoFailureException("Error writing to file " + all);
}
printComponentsReport(jsonFiles, duplicateJsonFiles, missingComponents, usedComponentLabels, usedOptionLabels, unlabeledOptions);
}
protected void executeDataFormats() throws MojoExecutionException, MojoFailureException {
getLog().info("Copying all Camel dataformat json descriptors");
// lets use sorted set/maps
Set<File> jsonFiles = new TreeSet<File>();
Set<File> duplicateJsonFiles = new TreeSet<File>();
Set<File> dataFormatFiles = new TreeSet<File>();
Map<String, Set<String>> usedLabels = new TreeMap<String, Set<String>>();
// find all data formats from the components directory
if (componentsDir != null && componentsDir.isDirectory()) {
File[] dataFormats = componentsDir.listFiles();
if (dataFormats != null) {
for (File dir : dataFormats) {
if (dir.isDirectory() && !"target".equals(dir.getName())) {
File target = new File(dir, "target/classes");
findDataFormatFilesRecursive(target, jsonFiles, dataFormatFiles, new CamelDataFormatsFileFilter());
}
}
}
}
if (coreDir != null && coreDir.isDirectory()) {
File target = new File(coreDir, "target/classes");
findDataFormatFilesRecursive(target, jsonFiles, dataFormatFiles, new CamelDataFormatsFileFilter());
}
getLog().info("Found " + dataFormatFiles.size() + " dataformat.properties files");
getLog().info("Found " + jsonFiles.size() + " dataformat json files");
// make sure to create out dir
dataFormatsOutDir.mkdirs();
for (File file : jsonFiles) {
File to = new File(dataFormatsOutDir, file.getName());
if (to.exists()) {
duplicateJsonFiles.add(to);
getLog().warn("Duplicate dataformat name detected: " + to);
}
try {
copyFile(file, to);
} catch (IOException e) {
throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
}
// check if we have a label as we want the data format to include labels
try {
String text = loadText(new FileInputStream(file));
String name = asComponentName(file);
Matcher matcher = LABEL_PATTERN.matcher(text);
// grab the label, and remember it in the used labels
if (matcher.find()) {
String label = matcher.group(1);
String[] labels = label.split(",");
for (String s : labels) {
Set<String> dataFormats = usedLabels.get(s);
if (dataFormats == null) {
dataFormats = new TreeSet<String>();
usedLabels.put(s, dataFormats);
}
dataFormats.add(name);
}
}
} catch (IOException e) {
// ignore
}
}
File all = new File(dataFormatsOutDir, "../dataformats.properties");
try {
FileOutputStream fos = new FileOutputStream(all, false);
String[] names = dataFormatsOutDir.list();
List<String> dataFormats = new ArrayList<String>();
// sort the names
for (String name : names) {
if (name.endsWith(".json")) {
// strip out .json from the name
String dataFormatName = name.substring(0, name.length() - 5);
dataFormats.add(dataFormatName);
}
}
Collections.sort(dataFormats);
for (String name : dataFormats) {
fos.write(name.getBytes());
fos.write("\n".getBytes());
}
fos.close();
} catch (IOException e) {
throw new MojoFailureException("Error writing to file " + all);
}
printDataFormatsReport(jsonFiles, duplicateJsonFiles, usedLabels);
}
protected void executeLanguages() throws MojoExecutionException, MojoFailureException {
getLog().info("Copying all Camel language json descriptors");
// lets use sorted set/maps
Set<File> jsonFiles = new TreeSet<File>();
Set<File> duplicateJsonFiles = new TreeSet<File>();
Set<File> languageFiles = new TreeSet<File>();
Map<String, Set<String>> usedLabels = new TreeMap<String, Set<String>>();
// find all languages from the components directory
if (componentsDir != null && componentsDir.isDirectory()) {
File[] languages = componentsDir.listFiles();
if (languages != null) {
for (File dir : languages) {
// skip camel-spring-dm
if (dir.isDirectory() && "camel-spring-dm".equals(dir.getName())) {
continue;
}
if (dir.isDirectory() && !"target".equals(dir.getName())) {
File target = new File(dir, "target/classes");
findLanguageFilesRecursive(target, jsonFiles, languageFiles, new CamelLanguagesFileFilter());
}
}
}
}
if (coreDir != null && coreDir.isDirectory()) {
File target = new File(coreDir, "target/classes");
findLanguageFilesRecursive(target, jsonFiles, languageFiles, new CamelLanguagesFileFilter());
}
getLog().info("Found " + languageFiles.size() + " language.properties files");
getLog().info("Found " + jsonFiles.size() + " language json files");
// make sure to create out dir
languagesOutDir.mkdirs();
for (File file : jsonFiles) {
File to = new File(languagesOutDir, file.getName());
if (to.exists()) {
duplicateJsonFiles.add(to);
getLog().warn("Duplicate language name detected: " + to);
}
try {
copyFile(file, to);
} catch (IOException e) {
throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
}
// check if we have a label as we want the data format to include labels
try {
String text = loadText(new FileInputStream(file));
String name = asComponentName(file);
Matcher matcher = LABEL_PATTERN.matcher(text);
// grab the label, and remember it in the used labels
if (matcher.find()) {
String label = matcher.group(1);
String[] labels = label.split(",");
for (String s : labels) {
Set<String> languages = usedLabels.get(s);
if (languages == null) {
languages = new TreeSet<String>();
usedLabels.put(s, languages);
}
languages.add(name);
}
}
} catch (IOException e) {
// ignore
}
}
File all = new File(languagesOutDir, "../languages.properties");
try {
FileOutputStream fos = new FileOutputStream(all, false);
String[] names = languagesOutDir.list();
List<String> languages = new ArrayList<String>();
// sort the names
for (String name : names) {
if (name.endsWith(".json")) {
// strip out .json from the name
String languageName = name.substring(0, name.length() - 5);
languages.add(languageName);
}
}
Collections.sort(languages);
for (String name : languages) {
fos.write(name.getBytes());
fos.write("\n".getBytes());
}
fos.close();
} catch (IOException e) {
throw new MojoFailureException("Error writing to file " + all);
}
printLanguagesReport(jsonFiles, duplicateJsonFiles, usedLabels);
}
protected void executeArchetypes() throws MojoExecutionException, MojoFailureException {
getLog().info("Copying Archetype Catalog");
// find the generate catalog
File file = new File(archetypesDir, "target/classes/archetype-catalog.xml");
// make sure to create out dir
archetypesOutDir.mkdirs();
if (file.exists() && file.isFile()) {
File to = new File(archetypesOutDir, file.getName());
try {
copyFile(file, to);
} catch (IOException e) {
throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
}
}
}
protected void executeXmlSchemas() throws MojoExecutionException, MojoFailureException {
getLog().info("Copying Spring/Blueprint XML schemas");
schemasOutDir.mkdirs();
File file = new File(springSchemaDir, "camel-spring.xsd");
if (file.exists() && file.isFile()) {
File to = new File(schemasOutDir, file.getName());
try {
copyFile(file, to);
} catch (IOException e) {
throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
}
}
file = new File(blueprintSchemaDir, "camel-blueprint.xsd");
if (file.exists() && file.isFile()) {
File to = new File(schemasOutDir, file.getName());
try {
copyFile(file, to);
} catch (IOException e) {
throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
}
}
}
protected void executeDocuments() throws MojoExecutionException, MojoFailureException {
getLog().info("Copying all Camel documents (ascii docs)");
// lets use sorted set/maps
Set<File> adocFiles = new TreeSet<File>();
Set<File> missingAdocFiles = new TreeSet<File>();
Set<File> duplicateAdocFiles = new TreeSet<File>();
// find all languages from the components directory
if (componentsDir != null && componentsDir.isDirectory()) {
File[] components = componentsDir.listFiles();
if (components != null) {
for (File dir : components) {
if (dir.isDirectory() && !"target".equals(dir.getName()) && !dir.getName().startsWith(".") && !excludeDocumentDir(dir.getName())) {
File target = new File(dir, "src/main/docs");
int before = adocFiles.size();
findAsciiDocFilesRecursive(target, adocFiles, new CamelAsciiDocFileFilter());
int after = adocFiles.size();
if (before == after) {
missingAdocFiles.add(dir);
}
}
}
}
}
if (coreDir != null && coreDir.isDirectory()) {
File target = new File(coreDir, "src/main/docs");
findAsciiDocFilesRecursive(target, adocFiles, new CamelAsciiDocFileFilter());
}
getLog().info("Found " + adocFiles.size() + " ascii document files");
// make sure to create out dir
documentsOutDir.mkdirs();
for (File file : adocFiles) {
File to = new File(documentsOutDir, file.getName());
if (to.exists()) {
duplicateAdocFiles.add(to);
getLog().warn("Duplicate document name detected: " + to);
}
try {
copyFile(file, to);
} catch (IOException e) {
throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
}
}
File all = new File(documentsOutDir, "../docs.properties");
try {
FileOutputStream fos = new FileOutputStream(all, false);
String[] names = documentsOutDir.list();
List<String> documents = new ArrayList<String>();
// sort the names
for (String name : names) {
if (name.endsWith(".adoc")) {
// strip out .json from the name
String documentName = name.substring(0, name.length() - 5);
documents.add(documentName);
}
}
Collections.sort(documents);
for (String name : documents) {
fos.write(name.getBytes());
fos.write("\n".getBytes());
}
fos.close();
} catch (IOException e) {
throw new MojoFailureException("Error writing to file " + all);
}
printDocumentsReport(adocFiles, duplicateAdocFiles, missingAdocFiles);
}
private void printModelsReport(Set<File> json, Set<File> duplicate, Set<File> missingLabels, Map<String, Set<String>> usedLabels, Set<File> missingJavaDoc) {
getLog().info("================================================================================");
getLog().info("");
getLog().info("Camel model catalog report");
getLog().info("");
getLog().info("\tModels found: " + json.size());
for (File file : json) {
getLog().info("\t\t" + asComponentName(file));
}
if (!duplicate.isEmpty()) {
getLog().info("");
getLog().warn("\tDuplicate models detected: " + duplicate.size());
for (File file : duplicate) {
getLog().warn("\t\t" + asComponentName(file));
}
}
if (!missingLabels.isEmpty()) {
getLog().info("");
getLog().warn("\tMissing labels detected: " + missingLabels.size());
for (File file : missingLabels) {
getLog().warn("\t\t" + asComponentName(file));
}
}
if (!usedLabels.isEmpty()) {
getLog().info("");
getLog().info("\tUsed labels: " + usedLabels.size());
for (Map.Entry<String, Set<String>> entry : usedLabels.entrySet()) {
getLog().info("\t\t" + entry.getKey() + ":");
for (String name : entry.getValue()) {
getLog().info("\t\t\t" + name);
}
}
}
if (!missingJavaDoc.isEmpty()) {
getLog().info("");
getLog().warn("\tMissing javadoc on models: " + missingJavaDoc.size());
for (File file : missingJavaDoc) {
getLog().warn("\t\t" + asComponentName(file));
}
}
getLog().info("");
getLog().info("================================================================================");
}
private void printComponentsReport(Set<File> json, Set<File> duplicate, Set<File> missing, Map<String,
Set<String>> usedComponentLabels, Set<String> usedOptionsLabels, Set<String> unusedLabels) {
getLog().info("================================================================================");
getLog().info("");
getLog().info("Camel component catalog report");
getLog().info("");
getLog().info("\tComponents found: " + json.size());
for (File file : json) {
getLog().info("\t\t" + asComponentName(file));
}
if (!duplicate.isEmpty()) {
getLog().info("");
getLog().warn("\tDuplicate components detected: " + duplicate.size());
for (File file : duplicate) {
getLog().warn("\t\t" + asComponentName(file));
}
}
if (!usedComponentLabels.isEmpty()) {
getLog().info("");
getLog().info("\tUsed component labels: " + usedComponentLabels.size());
for (Map.Entry<String, Set<String>> entry : usedComponentLabels.entrySet()) {
getLog().info("\t\t" + entry.getKey() + ":");
for (String name : entry.getValue()) {
getLog().info("\t\t\t" + name);
}
}
}
if (!usedOptionsLabels.isEmpty()) {
getLog().info("");
getLog().info("\tUsed component/endpoint options labels: " + usedOptionsLabels.size());
for (String name : usedOptionsLabels) {
getLog().info("\t\t\t" + name);
}
}
if (!unusedLabels.isEmpty()) {
getLog().info("");
getLog().info("\tComponent with more than " + UNUSED_LABELS_WARN + " unlabelled options: " + unusedLabels.size());
for (String name : unusedLabels) {
getLog().info("\t\t\t" + name);
}
}
if (!missing.isEmpty()) {
getLog().info("");
getLog().warn("\tMissing components detected: " + missing.size());
for (File name : missing) {
getLog().warn("\t\t" + name.getName());
}
}
getLog().info("");
getLog().info("================================================================================");
}
private void printDataFormatsReport(Set<File> json, Set<File> duplicate, Map<String, Set<String>> usedLabels) {
getLog().info("================================================================================");
getLog().info("");
getLog().info("Camel data format catalog report");
getLog().info("");
getLog().info("\tDataFormats found: " + json.size());
for (File file : json) {
getLog().info("\t\t" + asComponentName(file));
}
if (!duplicate.isEmpty()) {
getLog().info("");
getLog().warn("\tDuplicate dataformat detected: " + duplicate.size());
for (File file : duplicate) {
getLog().warn("\t\t" + asComponentName(file));
}
}
if (!usedLabels.isEmpty()) {
getLog().info("");
getLog().info("\tUsed labels: " + usedLabels.size());
for (Map.Entry<String, Set<String>> entry : usedLabels.entrySet()) {
getLog().info("\t\t" + entry.getKey() + ":");
for (String name : entry.getValue()) {
getLog().info("\t\t\t" + name);
}
}
}
getLog().info("");
getLog().info("================================================================================");
}
private void printLanguagesReport(Set<File> json, Set<File> duplicate, Map<String, Set<String>> usedLabels) {
getLog().info("================================================================================");
getLog().info("");
getLog().info("Camel language catalog report");
getLog().info("");
getLog().info("\tLanguages found: " + json.size());
for (File file : json) {
getLog().info("\t\t" + asComponentName(file));
}
if (!duplicate.isEmpty()) {
getLog().info("");
getLog().warn("\tDuplicate language detected: " + duplicate.size());
for (File file : duplicate) {
getLog().warn("\t\t" + asComponentName(file));
}
}
if (!usedLabels.isEmpty()) {
getLog().info("");
getLog().info("\tUsed labels: " + usedLabels.size());
for (Map.Entry<String, Set<String>> entry : usedLabels.entrySet()) {
getLog().info("\t\t" + entry.getKey() + ":");
for (String name : entry.getValue()) {
getLog().info("\t\t\t" + name);
}
}
}
getLog().info("");
getLog().info("================================================================================");
}
private void printDocumentsReport(Set<File> docs, Set<File> duplicate, Set<File> missing) {
getLog().info("================================================================================");
getLog().info("");
getLog().info("Camel document catalog report");
getLog().info("");
getLog().info("\tDocuments found: " + docs.size());
for (File file : docs) {
getLog().info("\t\t" + asComponentName(file));
}
if (!duplicate.isEmpty()) {
getLog().info("");
getLog().warn("\tDuplicate document detected: " + duplicate.size());
for (File file : duplicate) {
getLog().warn("\t\t" + asComponentName(file));
}
}
getLog().info("");
if (!missing.isEmpty()) {
getLog().info("");
getLog().warn("\tMissing document detected: " + missing.size());
for (File name : missing) {
getLog().warn("\t\t" + name.getName());
}
}
getLog().info("");
getLog().info("================================================================================");
}
private static String asComponentName(File file) {
String name = file.getName();
if (name.endsWith(".json") || name.endsWith(".adoc")) {
return name.substring(0, name.length() - 5);
}
return name;
}
private void findComponentFilesRecursive(File dir, Set<File> found, Set<File> components, FileFilter filter) {
File[] files = dir.listFiles(filter);
if (files != null) {
for (File file : files) {
// skip files in root dirs as Camel does not store information there but others may do
boolean rootDir = "classes".equals(dir.getName()) || "META-INF".equals(dir.getName());
boolean jsonFile = !rootDir && file.isFile() && file.getName().endsWith(".json");
boolean componentFile = !rootDir && file.isFile() && file.getName().equals("component.properties");
if (jsonFile) {
found.add(file);
} else if (componentFile) {
components.add(file);
} else if (file.isDirectory()) {
findComponentFilesRecursive(file, found, components, filter);
}
}
}
}
private void findDataFormatFilesRecursive(File dir, Set<File> found, Set<File> dataFormats, FileFilter filter) {
File[] files = dir.listFiles(filter);
if (files != null) {
for (File file : files) {
// skip files in root dirs as Camel does not store information there but others may do
boolean rootDir = "classes".equals(dir.getName()) || "META-INF".equals(dir.getName());
boolean jsonFile = !rootDir && file.isFile() && file.getName().endsWith(".json");
boolean dataFormatFile = !rootDir && file.isFile() && file.getName().equals("dataformat.properties");
if (jsonFile) {
found.add(file);
} else if (dataFormatFile) {
dataFormats.add(file);
} else if (file.isDirectory()) {
findDataFormatFilesRecursive(file, found, dataFormats, filter);
}
}
}
}
private void findLanguageFilesRecursive(File dir, Set<File> found, Set<File> languages, FileFilter filter) {
File[] files = dir.listFiles(filter);
if (files != null) {
for (File file : files) {
// skip files in root dirs as Camel does not store information there but others may do
boolean rootDir = "classes".equals(dir.getName()) || "META-INF".equals(dir.getName());
boolean jsonFile = !rootDir && file.isFile() && file.getName().endsWith(".json");
boolean languageFile = !rootDir && file.isFile() && file.getName().equals("language.properties");
if (jsonFile) {
found.add(file);
} else if (languageFile) {
languages.add(file);
} else if (file.isDirectory()) {
findLanguageFilesRecursive(file, found, languages, filter);
}
}
}
}
private void findAsciiDocFilesRecursive(File dir, Set<File> found, FileFilter filter) {
File[] files = dir.listFiles(filter);
if (files != null) {
for (File file : files) {
// skip files in root dirs as Camel does not store information there but others may do
boolean rootDir = "classes".equals(dir.getName()) || "META-INF".equals(dir.getName());
boolean adocFile = !rootDir && file.isFile() && file.getName().endsWith(".adoc");
if (adocFile) {
found.add(file);
} else if (file.isDirectory()) {
findAsciiDocFilesRecursive(file, found, filter);
}
}
}
}
private class CamelComponentsFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory() && pathname.getName().equals("model")) {
// do not check the camel-core model packages as there is no components there
return false;
}
if (pathname.isFile() && pathname.getName().endsWith(".json")) {
// must be a components json file
try {
String json = loadText(new FileInputStream(pathname));
return json != null && json.contains("\"kind\": \"component\"");
} catch (IOException e) {
// ignore
}
}
return pathname.isDirectory() || (pathname.isFile() && pathname.getName().equals("component.properties"));
}
}
private class CamelDataFormatsFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory() && pathname.getName().equals("model")) {
// do not check the camel-core model packages as there is no components there
return false;
}
if (pathname.isFile() && pathname.getName().endsWith(".json")) {
// must be a dataformat json file
try {
String json = loadText(new FileInputStream(pathname));
return json != null && json.contains("\"kind\": \"dataformat\"");
} catch (IOException e) {
// ignore
}
}
return pathname.isDirectory() || (pathname.isFile() && pathname.getName().equals("dataformat.properties"));
}
}
private class CamelLanguagesFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory() && pathname.getName().equals("model")) {
// do not check the camel-core model packages as there is no components there
return false;
}
if (pathname.isFile() && pathname.getName().endsWith(".json")) {
// must be a language json file
try {
String json = loadText(new FileInputStream(pathname));
return json != null && json.contains("\"kind\": \"language\"");
} catch (IOException e) {
// ignore
}
}
return pathname.isDirectory() || (pathname.isFile() && pathname.getName().equals("language.properties"));
}
}
private class CamelAsciiDocFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return pathname.isFile() && pathname.getName().endsWith(".adoc");
}
}
public static void copyFile(File from, File to) throws IOException {
FileChannel in = null;
FileChannel out = null;
try {
in = new FileInputStream(from).getChannel();
out = new FileOutputStream(to).getChannel();
long size = in.size();
long position = 0;
while (position < size) {
position += in.transferTo(position, BUFFER_SIZE, out);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
private static boolean excludeDocumentDir(String name) {
for (String exclude : EXCLUDE_DOC_FILES) {
if (exclude.equals(name)) {
return true;
}
}
return false;
}
}
|
tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/PrepareCatalogMojo.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.camel.maven.packaging;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import static org.apache.camel.maven.packaging.PackageHelper.loadText;
/**
* Prepares the camel catalog to include component, data format, and eip descriptors,
* and generates a report.
*
* @goal prepare-catalog
*/
public class PrepareCatalogMojo extends AbstractMojo {
public static final int BUFFER_SIZE = 128 * 1024;
private static final String[] EXCLUDE_DOC_FILES = {"camel-core-osgi", "camel-core-xml", "camel-http-common", "camel-jetty-common"};
private static final Pattern LABEL_PATTERN = Pattern.compile("\\\"label\\\":\\s\\\"([\\w,]+)\\\"");
private static final int UNUSED_LABELS_WARN = 15;
/**
* The maven project.
*
* @parameter property="project"
* @required
* @readonly
*/
protected MavenProject project;
/**
* Whether to validate if the components, data formats, and languages are properly documented and have all the needed details.
*
* @parameter default-value="true"
*/
protected Boolean validate;
/**
* The output directory for components catalog
*
* @parameter default-value="${project.build.directory}/classes/org/apache/camel/catalog/components"
*/
protected File componentsOutDir;
/**
* The output directory for dataformats catalog
*
* @parameter default-value="${project.build.directory}/classes/org/apache/camel/catalog/dataformats"
*/
protected File dataFormatsOutDir;
/**
* The output directory for languages catalog
*
* @parameter default-value="${project.build.directory}/classes/org/apache/camel/catalog/languages"
*/
protected File languagesOutDir;
/**
* The output directory for documents catalog
*
* @parameter default-value="${project.build.directory}/classes/org/apache/camel/catalog/docs"
*/
protected File documentsOutDir;
/**
* The output directory for models catalog
*
* @parameter default-value="${project.build.directory}/classes/org/apache/camel/catalog/models"
*/
protected File modelsOutDir;
/**
* The output directory for archetypes catalog
*
* @parameter default-value="${project.build.directory}/classes/org/apache/camel/catalog/archetypes"
*/
protected File archetypesOutDir;
/**
* The output directory for XML schemas catalog
*
* @parameter default-value="${project.build.directory}/classes/org/apache/camel/catalog/schemas"
*/
protected File schemasOutDir;
/**
* The components directory where all the Apache Camel components are
*
* @parameter default-value="${project.build.directory}/../../../components"
*/
protected File componentsDir;
/**
* The camel-core directory where camel-core components are
*
* @parameter default-value="${project.build.directory}/../../../camel-core"
*/
protected File coreDir;
/**
* The archetypes directory where all the Apache Camel Maven archetypes are
*
* @parameter default-value="${project.build.directory}/../../../tooling/archetypes"
*/
protected File archetypesDir;
/**
* The directory where the camel-spring XML schema are
*
* @parameter default-value="${project.build.directory}/../../../components/camel-spring/target/schema"
*/
protected File springSchemaDir;
/**
* The directory where the camel-blueprint XML schema are
*
* @parameter default-value="${project.build.directory}/../../../components/camel-blueprint/target/schema"
*/
protected File blueprintSchemaDir;
/**
* Maven ProjectHelper.
*
* @component
* @readonly
*/
private MavenProjectHelper projectHelper;
/**
* Execute goal.
*
* @throws org.apache.maven.plugin.MojoExecutionException execution of the main class or one of the
* threads it generated failed.
* @throws org.apache.maven.plugin.MojoFailureException something bad happened...
*/
public void execute() throws MojoExecutionException, MojoFailureException {
executeModel();
executeComponents();
executeDataFormats();
executeLanguages();
executeDocuments();
executeArchetypes();
executeXmlSchemas();
}
protected void executeModel() throws MojoExecutionException, MojoFailureException {
getLog().info("================================================================================");
getLog().info("Copying all Camel model json descriptors");
// lets use sorted set/maps
Set<File> jsonFiles = new TreeSet<File>();
Set<File> duplicateJsonFiles = new TreeSet<File>();
Set<File> missingLabels = new TreeSet<File>();
Set<File> missingJavaDoc = new TreeSet<File>();
Map<String, Set<String>> usedLabels = new TreeMap<String, Set<String>>();
// find all json files in camel-core
if (coreDir != null && coreDir.isDirectory()) {
File target = new File(coreDir, "target/classes/org/apache/camel/model");
PackageHelper.findJsonFiles(target, jsonFiles, new PackageHelper.CamelComponentsModelFilter());
}
getLog().info("Found " + jsonFiles.size() + " model json files");
// make sure to create out dir
modelsOutDir.mkdirs();
for (File file : jsonFiles) {
File to = new File(modelsOutDir, file.getName());
if (to.exists()) {
duplicateJsonFiles.add(to);
getLog().warn("Duplicate model name detected: " + to);
}
try {
copyFile(file, to);
} catch (IOException e) {
throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
}
try {
// check if we have a label as we want the eip to include labels
String text = loadText(new FileInputStream(file));
// just do a basic label check
if (text.contains("\"label\": \"\"")) {
missingLabels.add(file);
} else {
String name = asComponentName(file);
Matcher matcher = LABEL_PATTERN.matcher(text);
// grab the label, and remember it in the used labels
if (matcher.find()) {
String label = matcher.group(1);
String[] labels = label.split(",");
for (String s : labels) {
Set<String> models = usedLabels.get(s);
if (models == null) {
models = new TreeSet<String>();
usedLabels.put(s, models);
}
models.add(name);
}
}
}
// check all the properties if they have description
List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("properties", text, true);
for (Map<String, String> row : rows) {
String name = row.get("name");
// skip checking these as they have no documentation
if ("outputs".equals(name)) {
continue;
}
String doc = row.get("description");
if (doc == null || doc.isEmpty()) {
missingJavaDoc.add(file);
break;
}
}
} catch (IOException e) {
// ignore
}
}
File all = new File(modelsOutDir, "../models.properties");
try {
FileOutputStream fos = new FileOutputStream(all, false);
String[] names = modelsOutDir.list();
List<String> models = new ArrayList<String>();
// sort the names
for (String name : names) {
if (name.endsWith(".json")) {
// strip out .json from the name
String modelName = name.substring(0, name.length() - 5);
models.add(modelName);
}
}
Collections.sort(models);
for (String name : models) {
fos.write(name.getBytes());
fos.write("\n".getBytes());
}
fos.close();
} catch (IOException e) {
throw new MojoFailureException("Error writing to file " + all);
}
printModelsReport(jsonFiles, duplicateJsonFiles, missingLabels, usedLabels, missingJavaDoc);
}
protected void executeComponents() throws MojoExecutionException, MojoFailureException {
getLog().info("Copying all Camel component json descriptors");
// lets use sorted set/maps
Set<File> jsonFiles = new TreeSet<File>();
Set<File> duplicateJsonFiles = new TreeSet<File>();
Set<File> componentFiles = new TreeSet<File>();
Set<File> missingComponents = new TreeSet<File>();
Map<String, Set<String>> usedComponentLabels = new TreeMap<String, Set<String>>();
Set<String> usedOptionLabels = new TreeSet<String>();
Set<String> unlabeledOptions = new TreeSet<String>();
// find all json files in components and camel-core
if (componentsDir != null && componentsDir.isDirectory()) {
File[] components = componentsDir.listFiles();
if (components != null) {
for (File dir : components) {
// skip camel-spring-dm
if (dir.isDirectory() && "camel-spring-dm".equals(dir.getName())) {
continue;
}
if (dir.isDirectory() && !"target".equals(dir.getName())) {
File target = new File(dir, "target/classes");
// special for camel-salesforce which is in a sub dir
if ("camel-salesforce".equals(dir.getName())) {
target = new File(dir, "camel-salesforce-component/target/classes");
} else if ("camel-linkedin".equals(dir.getName())) {
target = new File(dir, "camel-linkedin-component/target/classes");
}
int before = componentFiles.size();
int before2 = jsonFiles.size();
findComponentFilesRecursive(target, jsonFiles, componentFiles, new CamelComponentsFileFilter());
int after = componentFiles.size();
int after2 = jsonFiles.size();
if (before != after && before2 == after2) {
missingComponents.add(dir);
}
}
}
}
}
if (coreDir != null && coreDir.isDirectory()) {
File target = new File(coreDir, "target/classes");
int before = componentFiles.size();
int before2 = jsonFiles.size();
findComponentFilesRecursive(target, jsonFiles, componentFiles, new CamelComponentsFileFilter());
int after = componentFiles.size();
int after2 = jsonFiles.size();
if (before != after && before2 == after2) {
missingComponents.add(coreDir);
}
}
getLog().info("Found " + componentFiles.size() + " component.properties files");
getLog().info("Found " + jsonFiles.size() + " component json files");
// make sure to create out dir
componentsOutDir.mkdirs();
for (File file : jsonFiles) {
File to = new File(componentsOutDir, file.getName());
if (to.exists()) {
duplicateJsonFiles.add(to);
getLog().warn("Duplicate component name detected: " + to);
}
try {
copyFile(file, to);
} catch (IOException e) {
throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
}
// check if we have a component label as we want the components to include labels
try {
String text = loadText(new FileInputStream(file));
String name = asComponentName(file);
Matcher matcher = LABEL_PATTERN.matcher(text);
// grab the label, and remember it in the used labels
if (matcher.find()) {
String label = matcher.group(1);
String[] labels = label.split(",");
for (String s : labels) {
Set<String> components = usedComponentLabels.get(s);
if (components == null) {
components = new TreeSet<String>();
usedComponentLabels.put(s, components);
}
components.add(name);
}
}
// check all the component options and grab the label(s) they use
List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("componentProperties", text, true);
for (Map<String, String> row : rows) {
String label = row.get("label");
if (label != null && !label.isEmpty()) {
String[] parts = label.split(",");
for (String part : parts) {
usedOptionLabels.add(part);
}
}
}
// check all the endpoint options and grab the label(s) they use
int unused = 0;
rows = JSonSchemaHelper.parseJsonSchema("properties", text, true);
for (Map<String, String> row : rows) {
String label = row.get("label");
if (label != null && !label.isEmpty()) {
String[] parts = label.split(",");
for (String part : parts) {
usedOptionLabels.add(part);
}
} else {
unused++;
}
}
if (unused >= UNUSED_LABELS_WARN) {
unlabeledOptions.add(name);
}
} catch (IOException e) {
// ignore
}
}
File all = new File(componentsOutDir, "../components.properties");
try {
FileOutputStream fos = new FileOutputStream(all, false);
String[] names = componentsOutDir.list();
List<String> components = new ArrayList<String>();
// sort the names
for (String name : names) {
if (name.endsWith(".json")) {
// strip out .json from the name
String componentName = name.substring(0, name.length() - 5);
components.add(componentName);
}
}
Collections.sort(components);
for (String name : components) {
fos.write(name.getBytes());
fos.write("\n".getBytes());
}
fos.close();
} catch (IOException e) {
throw new MojoFailureException("Error writing to file " + all);
}
printComponentsReport(jsonFiles, duplicateJsonFiles, missingComponents, usedComponentLabels, usedOptionLabels, unlabeledOptions);
}
protected void executeDataFormats() throws MojoExecutionException, MojoFailureException {
getLog().info("Copying all Camel dataformat json descriptors");
// lets use sorted set/maps
Set<File> jsonFiles = new TreeSet<File>();
Set<File> duplicateJsonFiles = new TreeSet<File>();
Set<File> dataFormatFiles = new TreeSet<File>();
Map<String, Set<String>> usedLabels = new TreeMap<String, Set<String>>();
// find all data formats from the components directory
if (componentsDir != null && componentsDir.isDirectory()) {
File[] dataFormats = componentsDir.listFiles();
if (dataFormats != null) {
for (File dir : dataFormats) {
if (dir.isDirectory() && !"target".equals(dir.getName())) {
File target = new File(dir, "target/classes");
findDataFormatFilesRecursive(target, jsonFiles, dataFormatFiles, new CamelDataFormatsFileFilter());
}
}
}
}
if (coreDir != null && coreDir.isDirectory()) {
File target = new File(coreDir, "target/classes");
findDataFormatFilesRecursive(target, jsonFiles, dataFormatFiles, new CamelDataFormatsFileFilter());
}
getLog().info("Found " + dataFormatFiles.size() + " dataformat.properties files");
getLog().info("Found " + jsonFiles.size() + " dataformat json files");
// make sure to create out dir
dataFormatsOutDir.mkdirs();
for (File file : jsonFiles) {
File to = new File(dataFormatsOutDir, file.getName());
if (to.exists()) {
duplicateJsonFiles.add(to);
getLog().warn("Duplicate dataformat name detected: " + to);
}
try {
copyFile(file, to);
} catch (IOException e) {
throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
}
// check if we have a label as we want the data format to include labels
try {
String text = loadText(new FileInputStream(file));
String name = asComponentName(file);
Matcher matcher = LABEL_PATTERN.matcher(text);
// grab the label, and remember it in the used labels
if (matcher.find()) {
String label = matcher.group(1);
String[] labels = label.split(",");
for (String s : labels) {
Set<String> dataFormats = usedLabels.get(s);
if (dataFormats == null) {
dataFormats = new TreeSet<String>();
usedLabels.put(s, dataFormats);
}
dataFormats.add(name);
}
}
} catch (IOException e) {
// ignore
}
}
File all = new File(dataFormatsOutDir, "../dataformats.properties");
try {
FileOutputStream fos = new FileOutputStream(all, false);
String[] names = dataFormatsOutDir.list();
List<String> dataFormats = new ArrayList<String>();
// sort the names
for (String name : names) {
if (name.endsWith(".json")) {
// strip out .json from the name
String dataFormatName = name.substring(0, name.length() - 5);
dataFormats.add(dataFormatName);
}
}
Collections.sort(dataFormats);
for (String name : dataFormats) {
fos.write(name.getBytes());
fos.write("\n".getBytes());
}
fos.close();
} catch (IOException e) {
throw new MojoFailureException("Error writing to file " + all);
}
printDataFormatsReport(jsonFiles, duplicateJsonFiles, usedLabels);
}
protected void executeLanguages() throws MojoExecutionException, MojoFailureException {
getLog().info("Copying all Camel language json descriptors");
// lets use sorted set/maps
Set<File> jsonFiles = new TreeSet<File>();
Set<File> duplicateJsonFiles = new TreeSet<File>();
Set<File> languageFiles = new TreeSet<File>();
Map<String, Set<String>> usedLabels = new TreeMap<String, Set<String>>();
// find all languages from the components directory
if (componentsDir != null && componentsDir.isDirectory()) {
File[] languages = componentsDir.listFiles();
if (languages != null) {
for (File dir : languages) {
// skip camel-spring-dm
if (dir.isDirectory() && "camel-spring-dm".equals(dir.getName())) {
continue;
}
if (dir.isDirectory() && !"target".equals(dir.getName())) {
File target = new File(dir, "target/classes");
findLanguageFilesRecursive(target, jsonFiles, languageFiles, new CamelLanguagesFileFilter());
}
}
}
}
if (coreDir != null && coreDir.isDirectory()) {
File target = new File(coreDir, "target/classes");
findLanguageFilesRecursive(target, jsonFiles, languageFiles, new CamelLanguagesFileFilter());
}
getLog().info("Found " + languageFiles.size() + " language.properties files");
getLog().info("Found " + jsonFiles.size() + " language json files");
// make sure to create out dir
languagesOutDir.mkdirs();
for (File file : jsonFiles) {
File to = new File(languagesOutDir, file.getName());
if (to.exists()) {
duplicateJsonFiles.add(to);
getLog().warn("Duplicate language name detected: " + to);
}
try {
copyFile(file, to);
} catch (IOException e) {
throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
}
// check if we have a label as we want the data format to include labels
try {
String text = loadText(new FileInputStream(file));
String name = asComponentName(file);
Matcher matcher = LABEL_PATTERN.matcher(text);
// grab the label, and remember it in the used labels
if (matcher.find()) {
String label = matcher.group(1);
String[] labels = label.split(",");
for (String s : labels) {
Set<String> languages = usedLabels.get(s);
if (languages == null) {
languages = new TreeSet<String>();
usedLabels.put(s, languages);
}
languages.add(name);
}
}
} catch (IOException e) {
// ignore
}
}
File all = new File(languagesOutDir, "../languages.properties");
try {
FileOutputStream fos = new FileOutputStream(all, false);
String[] names = languagesOutDir.list();
List<String> languages = new ArrayList<String>();
// sort the names
for (String name : names) {
if (name.endsWith(".json")) {
// strip out .json from the name
String languageName = name.substring(0, name.length() - 5);
languages.add(languageName);
}
}
Collections.sort(languages);
for (String name : languages) {
fos.write(name.getBytes());
fos.write("\n".getBytes());
}
fos.close();
} catch (IOException e) {
throw new MojoFailureException("Error writing to file " + all);
}
printLanguagesReport(jsonFiles, duplicateJsonFiles, usedLabels);
}
protected void executeArchetypes() throws MojoExecutionException, MojoFailureException {
getLog().info("Copying Archetype Catalog");
// find the generate catalog
File file = new File(archetypesDir, "target/classes/archetype-catalog.xml");
// make sure to create out dir
archetypesOutDir.mkdirs();
if (file.exists() && file.isFile()) {
File to = new File(archetypesOutDir, file.getName());
try {
copyFile(file, to);
} catch (IOException e) {
throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
}
}
}
protected void executeXmlSchemas() throws MojoExecutionException, MojoFailureException {
getLog().info("Copying Spring/Blueprint XML schemas");
schemasOutDir.mkdirs();
File file = new File(springSchemaDir, "camel-spring.xsd");
if (file.exists() && file.isFile()) {
File to = new File(schemasOutDir, file.getName());
try {
copyFile(file, to);
} catch (IOException e) {
throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
}
}
file = new File(blueprintSchemaDir, "camel-blueprint.xsd");
if (file.exists() && file.isFile()) {
File to = new File(schemasOutDir, file.getName());
try {
copyFile(file, to);
} catch (IOException e) {
throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
}
}
}
protected void executeDocuments() throws MojoExecutionException, MojoFailureException {
getLog().info("Copying all Camel documents (ascii docs)");
// lets use sorted set/maps
Set<File> adocFiles = new TreeSet<File>();
Set<File> missingAdocFiles = new TreeSet<File>();
Set<File> duplicateAdocFiles = new TreeSet<File>();
// find all languages from the components directory
if (componentsDir != null && componentsDir.isDirectory()) {
File[] components = componentsDir.listFiles();
if (components != null) {
for (File dir : components) {
if (dir.isDirectory() && !"target".equals(dir.getName()) && !dir.getName().startsWith(".") && !excludeDocumentDir(dir.getName())) {
File target = new File(dir, "src/main/docs");
int before = adocFiles.size();
findAsciiDocFilesRecursive(target, adocFiles, new CamelAsciiDocFileFilter());
int after = adocFiles.size();
if (before == after) {
missingAdocFiles.add(dir);
}
}
}
}
}
if (coreDir != null && coreDir.isDirectory()) {
File target = new File(coreDir, "src/main/docs");
findAsciiDocFilesRecursive(target, adocFiles, new CamelAsciiDocFileFilter());
}
getLog().info("Found " + adocFiles.size() + " ascii document files");
// make sure to create out dir
documentsOutDir.mkdirs();
for (File file : adocFiles) {
File to = new File(documentsOutDir, file.getName());
if (to.exists()) {
duplicateAdocFiles.add(to);
getLog().warn("Duplicate document name detected: " + to);
}
try {
copyFile(file, to);
} catch (IOException e) {
throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
}
}
File all = new File(documentsOutDir, "../docs.properties");
try {
FileOutputStream fos = new FileOutputStream(all, false);
String[] names = documentsOutDir.list();
List<String> documents = new ArrayList<String>();
// sort the names
for (String name : names) {
if (name.endsWith(".adoc")) {
// strip out .json from the name
String documentName = name.substring(0, name.length() - 5);
documents.add(documentName);
}
}
Collections.sort(documents);
for (String name : documents) {
fos.write(name.getBytes());
fos.write("\n".getBytes());
}
fos.close();
} catch (IOException e) {
throw new MojoFailureException("Error writing to file " + all);
}
printDocumentsReport(adocFiles, duplicateAdocFiles, missingAdocFiles);
}
private void printModelsReport(Set<File> json, Set<File> duplicate, Set<File> missingLabels, Map<String, Set<String>> usedLabels, Set<File> missingJavaDoc) {
getLog().info("================================================================================");
getLog().info("");
getLog().info("Camel model catalog report");
getLog().info("");
getLog().info("\tModels found: " + json.size());
for (File file : json) {
getLog().info("\t\t" + asComponentName(file));
}
if (!duplicate.isEmpty()) {
getLog().info("");
getLog().warn("\tDuplicate models detected: " + duplicate.size());
for (File file : duplicate) {
getLog().warn("\t\t" + asComponentName(file));
}
}
if (!missingLabels.isEmpty()) {
getLog().info("");
getLog().warn("\tMissing labels detected: " + missingLabels.size());
for (File file : missingLabels) {
getLog().warn("\t\t" + asComponentName(file));
}
}
if (!usedLabels.isEmpty()) {
getLog().info("");
getLog().info("\tUsed labels: " + usedLabels.size());
for (Map.Entry<String, Set<String>> entry : usedLabels.entrySet()) {
getLog().info("\t\t" + entry.getKey() + ":");
for (String name : entry.getValue()) {
getLog().info("\t\t\t" + name);
}
}
}
if (!missingJavaDoc.isEmpty()) {
getLog().info("");
getLog().warn("\tMissing javadoc on models: " + missingJavaDoc.size());
for (File file : missingJavaDoc) {
getLog().warn("\t\t" + asComponentName(file));
}
}
getLog().info("");
getLog().info("================================================================================");
}
private void printComponentsReport(Set<File> json, Set<File> duplicate, Set<File> missing, Map<String,
Set<String>> usedComponentLabels, Set<String> usedOptionsLabels, Set<String> unusedLabels) {
getLog().info("================================================================================");
getLog().info("");
getLog().info("Camel component catalog report");
getLog().info("");
getLog().info("\tComponents found: " + json.size());
for (File file : json) {
getLog().info("\t\t" + asComponentName(file));
}
if (!duplicate.isEmpty()) {
getLog().info("");
getLog().warn("\tDuplicate components detected: " + duplicate.size());
for (File file : duplicate) {
getLog().warn("\t\t" + asComponentName(file));
}
}
if (!usedComponentLabels.isEmpty()) {
getLog().info("");
getLog().info("\tUsed component labels: " + usedComponentLabels.size());
for (Map.Entry<String, Set<String>> entry : usedComponentLabels.entrySet()) {
getLog().info("\t\t" + entry.getKey() + ":");
for (String name : entry.getValue()) {
getLog().info("\t\t\t" + name);
}
}
}
if (!usedOptionsLabels.isEmpty()) {
getLog().info("");
getLog().info("\tUsed component/endpoint options labels: " + usedOptionsLabels.size());
for (String name : usedOptionsLabels) {
getLog().info("\t\t\t" + name);
}
}
if (!unusedLabels.isEmpty()) {
getLog().info("");
getLog().info("\tComponent with more than " + UNUSED_LABELS_WARN + " unlabelled options: " + unusedLabels.size());
for (String name : unusedLabels) {
getLog().info("\t\t\t" + name);
}
}
if (!missing.isEmpty()) {
getLog().info("");
getLog().warn("\tMissing components detected: " + missing.size());
for (File name : missing) {
getLog().warn("\t\t" + name.getName());
}
}
getLog().info("");
getLog().info("================================================================================");
}
private void printDataFormatsReport(Set<File> json, Set<File> duplicate, Map<String, Set<String>> usedLabels) {
getLog().info("================================================================================");
getLog().info("");
getLog().info("Camel data format catalog report");
getLog().info("");
getLog().info("\tDataFormats found: " + json.size());
for (File file : json) {
getLog().info("\t\t" + asComponentName(file));
}
if (!duplicate.isEmpty()) {
getLog().info("");
getLog().warn("\tDuplicate dataformat detected: " + duplicate.size());
for (File file : duplicate) {
getLog().warn("\t\t" + asComponentName(file));
}
}
if (!usedLabels.isEmpty()) {
getLog().info("");
getLog().info("\tUsed labels: " + usedLabels.size());
for (Map.Entry<String, Set<String>> entry : usedLabels.entrySet()) {
getLog().info("\t\t" + entry.getKey() + ":");
for (String name : entry.getValue()) {
getLog().info("\t\t\t" + name);
}
}
}
getLog().info("");
getLog().info("================================================================================");
}
private void printLanguagesReport(Set<File> json, Set<File> duplicate, Map<String, Set<String>> usedLabels) {
getLog().info("================================================================================");
getLog().info("");
getLog().info("Camel language catalog report");
getLog().info("");
getLog().info("\tLanguages found: " + json.size());
for (File file : json) {
getLog().info("\t\t" + asComponentName(file));
}
if (!duplicate.isEmpty()) {
getLog().info("");
getLog().warn("\tDuplicate language detected: " + duplicate.size());
for (File file : duplicate) {
getLog().warn("\t\t" + asComponentName(file));
}
}
if (!usedLabels.isEmpty()) {
getLog().info("");
getLog().info("\tUsed labels: " + usedLabels.size());
for (Map.Entry<String, Set<String>> entry : usedLabels.entrySet()) {
getLog().info("\t\t" + entry.getKey() + ":");
for (String name : entry.getValue()) {
getLog().info("\t\t\t" + name);
}
}
}
getLog().info("");
getLog().info("================================================================================");
}
private void printDocumentsReport(Set<File> docs, Set<File> duplicate, Set<File> missing) {
getLog().info("================================================================================");
getLog().info("");
getLog().info("Camel document catalog report");
getLog().info("");
getLog().info("\tDocuments found: " + docs.size());
for (File file : docs) {
getLog().info("\t\t" + asComponentName(file));
}
if (!duplicate.isEmpty()) {
getLog().info("");
getLog().warn("\tDuplicate document detected: " + duplicate.size());
for (File file : duplicate) {
getLog().warn("\t\t" + asComponentName(file));
}
}
getLog().info("");
if (!missing.isEmpty()) {
getLog().info("");
getLog().warn("\tMissing document detected: " + missing.size());
for (File name : missing) {
getLog().warn("\t\t" + name.getName());
}
}
getLog().info("");
getLog().info("================================================================================");
}
private static String asComponentName(File file) {
String name = file.getName();
if (name.endsWith(".json") || name.endsWith(".adoc")) {
return name.substring(0, name.length() - 5);
}
return name;
}
private void findComponentFilesRecursive(File dir, Set<File> found, Set<File> components, FileFilter filter) {
File[] files = dir.listFiles(filter);
if (files != null) {
for (File file : files) {
// skip files in root dirs as Camel does not store information there but others may do
boolean rootDir = "classes".equals(dir.getName()) || "META-INF".equals(dir.getName());
boolean jsonFile = !rootDir && file.isFile() && file.getName().endsWith(".json");
boolean componentFile = !rootDir && file.isFile() && file.getName().equals("component.properties");
if (jsonFile) {
found.add(file);
} else if (componentFile) {
components.add(file);
} else if (file.isDirectory()) {
findComponentFilesRecursive(file, found, components, filter);
}
}
}
}
private void findDataFormatFilesRecursive(File dir, Set<File> found, Set<File> dataFormats, FileFilter filter) {
File[] files = dir.listFiles(filter);
if (files != null) {
for (File file : files) {
// skip files in root dirs as Camel does not store information there but others may do
boolean rootDir = "classes".equals(dir.getName()) || "META-INF".equals(dir.getName());
boolean jsonFile = !rootDir && file.isFile() && file.getName().endsWith(".json");
boolean dataFormatFile = !rootDir && file.isFile() && file.getName().equals("dataformat.properties");
if (jsonFile) {
found.add(file);
} else if (dataFormatFile) {
dataFormats.add(file);
} else if (file.isDirectory()) {
findDataFormatFilesRecursive(file, found, dataFormats, filter);
}
}
}
}
private void findLanguageFilesRecursive(File dir, Set<File> found, Set<File> languages, FileFilter filter) {
File[] files = dir.listFiles(filter);
if (files != null) {
for (File file : files) {
// skip files in root dirs as Camel does not store information there but others may do
boolean rootDir = "classes".equals(dir.getName()) || "META-INF".equals(dir.getName());
boolean jsonFile = !rootDir && file.isFile() && file.getName().endsWith(".json");
boolean languageFile = !rootDir && file.isFile() && file.getName().equals("language.properties");
if (jsonFile) {
found.add(file);
} else if (languageFile) {
languages.add(file);
} else if (file.isDirectory()) {
findLanguageFilesRecursive(file, found, languages, filter);
}
}
}
}
private void findAsciiDocFilesRecursive(File dir, Set<File> found, FileFilter filter) {
File[] files = dir.listFiles(filter);
if (files != null) {
for (File file : files) {
// skip files in root dirs as Camel does not store information there but others may do
boolean rootDir = "classes".equals(dir.getName()) || "META-INF".equals(dir.getName());
boolean adocFile = !rootDir && file.isFile() && file.getName().endsWith(".adoc");
if (adocFile) {
found.add(file);
} else if (file.isDirectory()) {
findAsciiDocFilesRecursive(file, found, filter);
}
}
}
}
private class CamelComponentsFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory() && pathname.getName().equals("model")) {
// do not check the camel-core model packages as there is no components there
return false;
}
if (pathname.isFile() && pathname.getName().endsWith(".json")) {
// must be a components json file
try {
String json = loadText(new FileInputStream(pathname));
return json != null && json.contains("\"kind\": \"component\"");
} catch (IOException e) {
// ignore
}
}
return pathname.isDirectory() || (pathname.isFile() && pathname.getName().equals("component.properties"));
}
}
private class CamelDataFormatsFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory() && pathname.getName().equals("model")) {
// do not check the camel-core model packages as there is no components there
return false;
}
if (pathname.isFile() && pathname.getName().endsWith(".json")) {
// must be a dataformat json file
try {
String json = loadText(new FileInputStream(pathname));
return json != null && json.contains("\"kind\": \"dataformat\"");
} catch (IOException e) {
// ignore
}
}
return pathname.isDirectory() || (pathname.isFile() && pathname.getName().equals("dataformat.properties"));
}
}
private class CamelLanguagesFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory() && pathname.getName().equals("model")) {
// do not check the camel-core model packages as there is no components there
return false;
}
if (pathname.isFile() && pathname.getName().endsWith(".json")) {
// must be a language json file
try {
String json = loadText(new FileInputStream(pathname));
return json != null && json.contains("\"kind\": \"language\"");
} catch (IOException e) {
// ignore
}
}
return pathname.isDirectory() || (pathname.isFile() && pathname.getName().equals("language.properties"));
}
}
private class CamelAsciiDocFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return pathname.isFile() && pathname.getName().endsWith(".adoc");
}
}
public static void copyFile(File from, File to) throws IOException {
FileChannel in = null;
FileChannel out = null;
try {
in = new FileInputStream(from).getChannel();
out = new FileOutputStream(to).getChannel();
long size = in.size();
long position = 0;
while (position < size) {
position += in.transferTo(position, BUFFER_SIZE, out);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
private static boolean excludeDocumentDir(String name) {
for (String exclude : EXCLUDE_DOC_FILES) {
if (exclude.equals(name)) {
return true;
}
}
return false;
}
}
|
Added camel-jetty to the excluded components docs list
|
tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/PrepareCatalogMojo.java
|
Added camel-jetty to the excluded components docs list
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.